package com.rj.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rj.common.DictItemConstants;
import com.rj.dto.QiWeiConfig;
import com.rj.entity.DictItem;
import com.rj.service.IDictItemService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 字典项/配置项前端控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/dictItem")
@Tag(name = "字典项/配置项(dict_item)", description = "增删改查与分页")
public class DictItemController {

    @Autowired
    private IDictItemService dictItemService;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @PostMapping("/add")
    @Operation(summary = "新增")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体", required = true) @RequestBody DictItem entity) {
        Map<String, Object> result = dictItemService.add(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PutMapping("/update")
    @Operation(summary = "更新")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "实体", required = true) @RequestBody DictItem entity) {
        Map<String, Object> result = dictItemService.update(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除")
    public ResponseEntity<Map<String, Object>> delete(
            @Parameter(description = "主键ID", required = true) @PathVariable String id) {
        Map<String, Object> result = dictItemService.deleteById(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @GetMapping("/list")
    @Operation(summary = "分页查询")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String tenantId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String microService,
            @RequestParam(required = false) String valueRange) {
        Map<String, Object> result = dictItemService.pageQuery(current, size, tenantId, name, type, microService, valueRange);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.internalServerError().body(result);
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "按ID查询")
    public ResponseEntity<Map<String, Object>> getById(
            @Parameter(description = "主键ID", required = true) @PathVariable String id,
            @Parameter(description = "名称(可为空)。当 name=qiwei_config 且数据库不存在时，返回默认 QiWeiConfig JSON", required = false)
            @RequestParam(required = false) String name) {
        Map<String, Object> result = new HashMap<>();
        try {
            DictItem data = dictItemService.getById(id);
            if (data == null) {
                if (DictItemConstants.QIWEI_CONFIG.equals(name)) {
                    result.put("success", true);
                    result.put("message", "查询成功");
                    data= new DictItem();
                    QiWeiConfig cfg = new QiWeiConfig();
                    cfg.setCorpid("-");
                    cfg.setAppSecret("-");
                    cfg.setContractSecret("-");
                    data.setValue(OBJECT_MAPPER.writeValueAsString(cfg));
                    data.setName(DictItemConstants.QIWEI_CONFIG);
                    data.setDescription("企微的默认配置项");
                    result.put("data", data);
                    return ResponseEntity.ok(result);
                }

                result.put("success", false);
                result.put("message", "记录不存在");
                return ResponseEntity.notFound().build();
            }
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", data);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("dict_item get by id error, id={}", id, e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}

