package com.pangu.web.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
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/dept")
public class SysDeptController {

    @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 NOT FIND_IN_SET(?, ancestors) 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'";
        Map<String, Object> dept = jdbcTemplate.queryForMap(sql, deptId);
        return AjaxResult.success(dept);
    }

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

    /**
     * 新增部门
     */
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> dept) {
        Long parentId = dept.get("parentId") != null ? Long.valueOf(dept.get("parentId").toString()) : 0L;

        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("修改部门失败，上级部门不能是自己");
        }

        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, Long parentId) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> item : list) {
            Long pid = ((Number) item.get("parent_id")).longValue();
            if (pid.equals(parentId)) {
                Map<String, Object> node = new HashMap<>();
                Long id = ((Number) item.get("dept_id")).longValue();
                node.put("id", id);
                node.put("label", item.get("dept_name"));
                List<Map<String, Object>> children = buildTree(list, id);
                if (!children.isEmpty()) {
                    node.put("children", children);
                }
                result.add(node);
            }
        }
        return result;
    }
}
