package com.pangu.system.controller;

import com.pangu.common.core.controller.BaseController;
import com.pangu.common.core.domain.AjaxResult;
import com.pangu.common.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 字典管理Controller
 * @author 湖北新华业务中台研发团队
 */
@RestController
@RequestMapping("/api/system/dict")
public class SysDictController extends BaseController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // ==================== 字典类型 ====================

    /**
     * 查询字典类型列表
     */
    @GetMapping("/type/list")
    public TableDataInfo typeList(
            @RequestParam(required = false) String dictName,
            @RequestParam(required = false) String dictType,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT dict_id, dict_name, dict_type, status, create_time, remark ");
        sql.append("FROM sys_dict_type WHERE 1=1 ");
        
        List<Object> params = new ArrayList<>();
        if (dictName != null && !dictName.isEmpty()) {
            sql.append("AND dict_name LIKE ? ");
            params.add("%" + dictName + "%");
        }
        if (dictType != null && !dictType.isEmpty()) {
            sql.append("AND dict_type LIKE ? ");
            params.add("%" + dictType + "%");
        }
        if (status != null && !status.isEmpty()) {
            sql.append("AND status = ? ");
            params.add(status);
        }
        
        String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") t";
        Integer total = jdbcTemplate.queryForObject(countSql, params.toArray(), Integer.class);
        
        sql.append("ORDER BY dict_id LIMIT ? OFFSET ?");
        params.add(pageSize);
        params.add((pageNum - 1) * pageSize);
        
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql.toString(), params.toArray());
        
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(200);
        dataInfo.setMsg("查询成功");
        dataInfo.setRows(rows);
        dataInfo.setTotal(total != null ? total : 0);
        return dataInfo;
    }

    /**
     * 获取字典类型详情
     */
    @GetMapping("/type/{dictId}")
    public AjaxResult getTypeInfo(@PathVariable Long dictId) {
        String sql = "SELECT * FROM sys_dict_type WHERE dict_id = ?";
        List<Map<String, Object>> types = jdbcTemplate.queryForList(sql, dictId);
        if (types.isEmpty()) {
            return AjaxResult.error("字典类型不存在");
        }
        return AjaxResult.success(types.get(0));
    }

    /**
     * 新增字典类型
     */
    @PostMapping("/type")
    public AjaxResult addType(@RequestBody Map<String, Object> dictType) {
        String type = (String) dictType.get("dictType");
        
        Integer count = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM sys_dict_type WHERE dict_type = ?",
            Integer.class, type);
        if (count != null && count > 0) {
            return AjaxResult.error("字典类型已存在");
        }
        
        String sql = "INSERT INTO sys_dict_type (dict_name, dict_type, status, " +
                    "create_by, create_time, remark) VALUES (?, ?, ?, 'admin', NOW(), ?)";
        
        jdbcTemplate.update(sql,
            dictType.get("dictName"),
            type,
            dictType.getOrDefault("status", "0"),
            dictType.get("remark")
        );
        
        return AjaxResult.success("新增成功");
    }

    /**
     * 修改字典类型
     */
    @PutMapping("/type")
    public AjaxResult editType(@RequestBody Map<String, Object> dictType) {
        Long dictId = Long.valueOf(dictType.get("dictId").toString());
        
        String sql = "UPDATE sys_dict_type SET dict_name = ?, dict_type = ?, status = ?, " +
                    "remark = ?, update_by = 'admin', update_time = NOW() WHERE dict_id = ?";
        
        jdbcTemplate.update(sql,
            dictType.get("dictName"),
            dictType.get("dictType"),
            dictType.getOrDefault("status", "0"),
            dictType.get("remark"),
            dictId
        );
        
        return AjaxResult.success("修改成功");
    }

    /**
     * 删除字典类型
     */
    @DeleteMapping("/type/{dictIds}")
    public AjaxResult removeType(@PathVariable String dictIds) {
        String[] ids = dictIds.split(",");
        for (String id : ids) {
            // 获取字典类型
            List<Map<String, Object>> types = jdbcTemplate.queryForList(
                "SELECT dict_type FROM sys_dict_type WHERE dict_id = ?", Long.valueOf(id));
            if (!types.isEmpty()) {
                String dictType = (String) types.get(0).get("dict_type");
                // 删除字典数据
                jdbcTemplate.update("DELETE FROM sys_dict_data WHERE dict_type = ?", dictType);
            }
            jdbcTemplate.update("DELETE FROM sys_dict_type WHERE dict_id = ?", Long.valueOf(id));
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 获取字典类型选项
     */
    @GetMapping("/type/optionselect")
    public AjaxResult optionselect() {
        String sql = "SELECT dict_id as dictId, dict_name as dictName, dict_type as dictType " +
                    "FROM sys_dict_type WHERE status = '0' ORDER BY dict_id";
        return AjaxResult.success(jdbcTemplate.queryForList(sql));
    }

    // ==================== 字典数据 ====================

    /**
     * 查询字典数据列表
     */
    @GetMapping("/data/list")
    public TableDataInfo dataList(
            @RequestParam(required = false) String dictType,
            @RequestParam(required = false) String dictLabel,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT dict_code, dict_sort, dict_label, dict_value, dict_type, ");
        sql.append("css_class, list_class, is_default, status, create_time, remark ");
        sql.append("FROM sys_dict_data WHERE 1=1 ");
        
        List<Object> params = new ArrayList<>();
        if (dictType != null && !dictType.isEmpty()) {
            sql.append("AND dict_type = ? ");
            params.add(dictType);
        }
        if (dictLabel != null && !dictLabel.isEmpty()) {
            sql.append("AND dict_label LIKE ? ");
            params.add("%" + dictLabel + "%");
        }
        if (status != null && !status.isEmpty()) {
            sql.append("AND status = ? ");
            params.add(status);
        }
        
        String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") t";
        Integer total = jdbcTemplate.queryForObject(countSql, params.toArray(), Integer.class);
        
        sql.append("ORDER BY dict_sort LIMIT ? OFFSET ?");
        params.add(pageSize);
        params.add((pageNum - 1) * pageSize);
        
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql.toString(), params.toArray());
        
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(200);
        dataInfo.setMsg("查询成功");
        dataInfo.setRows(rows);
        dataInfo.setTotal(total != null ? total : 0);
        return dataInfo;
    }

    /**
     * 根据字典类型查询字典数据
     */
    @GetMapping("/data/type/{dictType}")
    public AjaxResult dictDataByType(@PathVariable String dictType) {
        String sql = "SELECT dict_code as dictCode, dict_value as dictValue, dict_label as dictLabel, " +
                    "css_class as cssClass, list_class as listClass, is_default as isDefault " +
                    "FROM sys_dict_data WHERE dict_type = ? AND status = '0' ORDER BY dict_sort";
        return AjaxResult.success(jdbcTemplate.queryForList(sql, dictType));
    }

    /**
     * 获取字典数据详情
     */
    @GetMapping("/data/{dictCode}")
    public AjaxResult getDataInfo(@PathVariable Long dictCode) {
        String sql = "SELECT * FROM sys_dict_data WHERE dict_code = ?";
        List<Map<String, Object>> datas = jdbcTemplate.queryForList(sql, dictCode);
        if (datas.isEmpty()) {
            return AjaxResult.error("字典数据不存在");
        }
        return AjaxResult.success(datas.get(0));
    }

    /**
     * 新增字典数据
     */
    @PostMapping("/data")
    public AjaxResult addData(@RequestBody Map<String, Object> dictData) {
        String sql = "INSERT INTO sys_dict_data (dict_sort, dict_label, dict_value, dict_type, " +
                    "css_class, list_class, is_default, status, create_by, create_time, remark) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'admin', NOW(), ?)";
        
        jdbcTemplate.update(sql,
            dictData.getOrDefault("dictSort", 0),
            dictData.get("dictLabel"),
            dictData.get("dictValue"),
            dictData.get("dictType"),
            dictData.get("cssClass"),
            dictData.getOrDefault("listClass", "default"),
            dictData.getOrDefault("isDefault", "N"),
            dictData.getOrDefault("status", "0"),
            dictData.get("remark")
        );
        
        return AjaxResult.success("新增成功");
    }

    /**
     * 修改字典数据
     */
    @PutMapping("/data")
    public AjaxResult editData(@RequestBody Map<String, Object> dictData) {
        Long dictCode = Long.valueOf(dictData.get("dictCode").toString());
        
        String sql = "UPDATE sys_dict_data SET dict_sort = ?, dict_label = ?, dict_value = ?, " +
                    "dict_type = ?, css_class = ?, list_class = ?, is_default = ?, status = ?, " +
                    "remark = ?, update_by = 'admin', update_time = NOW() WHERE dict_code = ?";
        
        jdbcTemplate.update(sql,
            dictData.getOrDefault("dictSort", 0),
            dictData.get("dictLabel"),
            dictData.get("dictValue"),
            dictData.get("dictType"),
            dictData.get("cssClass"),
            dictData.getOrDefault("listClass", "default"),
            dictData.getOrDefault("isDefault", "N"),
            dictData.getOrDefault("status", "0"),
            dictData.get("remark"),
            dictCode
        );
        
        return AjaxResult.success("修改成功");
    }

    /**
     * 删除字典数据
     */
    @DeleteMapping("/data/{dictCodes}")
    public AjaxResult removeData(@PathVariable String dictCodes) {
        String[] codes = dictCodes.split(",");
        for (String code : codes) {
            jdbcTemplate.update("DELETE FROM sys_dict_data WHERE dict_code = ?", Long.valueOf(code));
        }
        return AjaxResult.success("删除成功");
    }
}
