package com.pangu.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.pangu.common.core.domain.AjaxResult;

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

    @Autowired
    private JdbcTemplate jdbcTemplate;

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

    @GetMapping("/type/list")
    public AjaxResult 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, Integer.class, params.toArray());

        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());

        return AjaxResult.success().put("rows", rows).put("total", total != null ? total : 0);
    }

    @GetMapping("/type/{dictId}")
    public AjaxResult getTypeInfo(@PathVariable Long dictId) {
        String sql = "SELECT * FROM sys_dict_type WHERE dict_id = ?";
        Map<String, Object> type = jdbcTemplate.queryForMap(sql, dictId);
        return AjaxResult.success(type);
    }

    @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("/data/list")
    public AjaxResult 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, Integer.class, params.toArray());

        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());

        return AjaxResult.success().put("rows", rows).put("total", total != null ? total : 0);
    }

    @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 " +
                "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 = ?";
        Map<String, Object> data = jdbcTemplate.queryForMap(sql, dictCode);
        return AjaxResult.success(data);
    }

    @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();
    }
}
