package com.pangu.system.controller;

import com.pangu.common.core.controller.BaseController;
import com.pangu.common.core.domain.AjaxResult;
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/dept")
public class SysDeptController extends BaseController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询部门列表
     */
    @GetMapping("/list")
    public AjaxResult list(
            @RequestParam(required = false) String deptName,
            @RequestParam(required = false) String status) {
        
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT dept_id, parent_id, ancestors, dept_name, order_num, leader, phone, email, status, create_time ");
        sql.append("FROM sys_dept WHERE del_flag = '0' ");
        
        List<Object> params = new ArrayList<>();
        if (deptName != null && !deptName.isEmpty()) {
            sql.append("AND dept_name LIKE ? ");
            params.add("%" + deptName + "%");
        }
        if (status != null && !status.isEmpty()) {
            sql.append("AND status = ? ");
            params.add(status);
        }
        sql.append("ORDER BY parent_id, order_num");
        
        List<Map<String, Object>> depts = jdbcTemplate.queryForList(sql.toString(), params.toArray());
        return AjaxResult.success(depts);
    }

    /**
     * 查询部门列表（排除某节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable Long deptId) {
        String sql = "SELECT dept_id, parent_id, ancestors, dept_name, order_num, leader, phone, email, status " +
                    "FROM sys_dept WHERE del_flag = '0' AND dept_id != ? " +
                    "AND FIND_IN_SET(?, ancestors) = 0 ORDER BY parent_id, order_num";
        List<Map<String, Object>> depts = jdbcTemplate.queryForList(sql, deptId, deptId);
        return AjaxResult.success(depts);
    }

    /**
     * 获取部门详情
     */
    @GetMapping("/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        String sql = "SELECT * FROM sys_dept WHERE dept_id = ? AND del_flag = '0'";
        List<Map<String, Object>> depts = jdbcTemplate.queryForList(sql, deptId);
        if (depts.isEmpty()) {
            return AjaxResult.error("部门不存在");
        }
        return AjaxResult.success(depts.get(0));
    }

    /**
     * 获取部门树
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect() {
        String sql = "SELECT dept_id as id, parent_id as parentId, dept_name as label " +
                    "FROM sys_dept WHERE del_flag = '0' ORDER BY parent_id, order_num";
        List<Map<String, Object>> depts = jdbcTemplate.queryForList(sql);
        return AjaxResult.success(buildTree(depts));
    }

    /**
     * 新增部门
     */
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> dept) {
        Long parentId = dept.get("parentId") != null ? Long.valueOf(dept.get("parentId").toString()) : 0L;
        
        // 获取父部门ancestors
        String ancestors = "0";
        if (parentId != 0) {
            List<Map<String, Object>> parents = jdbcTemplate.queryForList(
                "SELECT ancestors FROM sys_dept WHERE dept_id = ?", parentId);
            if (!parents.isEmpty()) {
                ancestors = parents.get(0).get("ancestors") + "," + parentId;
            }
        }
        
        String sql = "INSERT INTO sys_dept (parent_id, ancestors, dept_name, order_num, leader, " +
                    "phone, email, status, create_by, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'admin', NOW())";
        
        jdbcTemplate.update(sql,
            parentId,
            ancestors,
            dept.get("deptName"),
            dept.getOrDefault("orderNum", 0),
            dept.get("leader"),
            dept.get("phone"),
            dept.get("email"),
            dept.getOrDefault("status", "0")
        );
        
        return AjaxResult.success("新增成功");
    }

    /**
     * 修改部门
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String, Object> dept) {
        Long deptId = Long.valueOf(dept.get("deptId").toString());
        Long parentId = dept.get("parentId") != null ? Long.valueOf(dept.get("parentId").toString()) : 0L;
        
        // 不能将父部门设为自己
        if (deptId.equals(parentId)) {
            return AjaxResult.error("修改部门失败，上级部门不能是自己");
        }
        
        // 不能将父部门设为自己的子部门
        List<Map<String, Object>> children = jdbcTemplate.queryForList(
            "SELECT dept_id FROM sys_dept WHERE FIND_IN_SET(?, ancestors) AND del_flag = '0'", deptId);
        for (Map<String, Object> child : children) {
            if (parentId.equals(((Number) child.get("dept_id")).longValue())) {
                return AjaxResult.error("修改部门失败，上级部门不能是自己的子部门");
            }
        }
        
        // 获取新的ancestors
        String ancestors = "0";
        if (parentId != 0) {
            List<Map<String, Object>> parents = jdbcTemplate.queryForList(
                "SELECT ancestors FROM sys_dept WHERE dept_id = ?", parentId);
            if (!parents.isEmpty()) {
                ancestors = parents.get(0).get("ancestors") + "," + parentId;
            }
        }
        
        String sql = "UPDATE sys_dept SET parent_id = ?, ancestors = ?, dept_name = ?, order_num = ?, " +
                    "leader = ?, phone = ?, email = ?, status = ?, update_by = 'admin', update_time = NOW() " +
                    "WHERE dept_id = ?";
        
        jdbcTemplate.update(sql,
            parentId,
            ancestors,
            dept.get("deptName"),
            dept.getOrDefault("orderNum", 0),
            dept.get("leader"),
            dept.get("phone"),
            dept.get("email"),
            dept.getOrDefault("status", "0"),
            deptId
        );
        
        return AjaxResult.success("修改成功");
    }

    /**
     * 删除部门
     */
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        // 检查是否有子部门
        Integer count = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM sys_dept WHERE parent_id = ? AND del_flag = '0'",
            Integer.class, deptId);
        if (count != null && count > 0) {
            return AjaxResult.error("存在子部门，不允许删除");
        }
        
        // 检查是否有用户
        count = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM sys_user WHERE dept_id = ? AND del_flag = '0'",
            Integer.class, deptId);
        if (count != null && count > 0) {
            return AjaxResult.error("部门下存在用户，不允许删除");
        }
        
        jdbcTemplate.update("UPDATE sys_dept SET del_flag = '2' WHERE dept_id = ?", deptId);
        return AjaxResult.success("删除成功");
    }

    private List<Map<String, Object>> buildTree(List<Map<String, Object>> list) {
        List<Map<String, Object>> result = new ArrayList<>();
        Map<Long, Map<String, Object>> nodeMap = new HashMap<>();
        
        for (Map<String, Object> node : list) {
            Long id = ((Number) node.get("id")).longValue();
            nodeMap.put(id, node);
            node.put("children", new ArrayList<Map<String, Object>>());
        }
        
        for (Map<String, Object> node : list) {
            Long parentId = ((Number) node.get("parentId")).longValue();
            if (parentId == 0) {
                result.add(node);
            } else {
                Map<String, Object> parent = nodeMap.get(parentId);
                if (parent != null) {
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
                    children.add(node);
                }
            }
        }
        return result;
    }
}
