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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 系统用户管理Controller
 * @author 湖北新华业务中台研发团队
 */
@RestController
@RequestMapping("/api/system/user")
public class SysUserController extends BaseController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 查询用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String phonenumber,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long deptId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT u.user_id, u.dept_id, u.user_name, u.nick_name, u.email, ");
        sql.append("u.phonenumber, u.sex, u.status, u.create_time, d.dept_name ");
        sql.append("FROM sys_user u LEFT JOIN sys_dept d ON u.dept_id = d.dept_id ");
        sql.append("WHERE u.del_flag = '0' ");
        
        List<Object> params = new ArrayList<>();
        if (userName != null && !userName.isEmpty()) {
            sql.append("AND u.user_name LIKE ? ");
            params.add("%" + userName + "%");
        }
        if (phonenumber != null && !phonenumber.isEmpty()) {
            sql.append("AND u.phonenumber LIKE ? ");
            params.add("%" + phonenumber + "%");
        }
        if (status != null && !status.isEmpty()) {
            sql.append("AND u.status = ? ");
            params.add(status);
        }
        if (deptId != null) {
            sql.append("AND (u.dept_id = ? OR u.dept_id IN (SELECT dept_id FROM sys_dept WHERE FIND_IN_SET(?, ancestors))) ");
            params.add(deptId);
            params.add(deptId);
        }
        
        // 统计总数
        String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") t";
        Integer total = jdbcTemplate.queryForObject(countSql, params.toArray(), Integer.class);
        
        // 分页查询
        sql.append("ORDER BY u.create_time DESC 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("/{userId}")
    public AjaxResult getInfo(@PathVariable Long userId) {
        String sql = "SELECT u.*, d.dept_name FROM sys_user u " +
                    "LEFT JOIN sys_dept d ON u.dept_id = d.dept_id " +
                    "WHERE u.user_id = ? AND u.del_flag = '0'";
        List<Map<String, Object>> users = jdbcTemplate.queryForList(sql, userId);
        if (users.isEmpty()) {
            return AjaxResult.error("用户不存在");
        }
        
        Map<String, Object> user = users.get(0);
        user.remove("password"); // 移除密码字段
        
        // 查询用户角色
        String roleSql = "SELECT r.role_id, r.role_name FROM sys_role r " +
                        "INNER JOIN sys_user_role ur ON r.role_id = ur.role_id " +
                        "WHERE ur.user_id = ?";
        List<Map<String, Object>> roles = jdbcTemplate.queryForList(roleSql, userId);
        user.put("roles", roles);
        
        // 查询用户岗位
        String postSql = "SELECT p.post_id, p.post_name FROM sys_post p " +
                        "INNER JOIN sys_user_post up ON p.post_id = up.post_id " +
                        "WHERE up.user_id = ?";
        List<Map<String, Object>> posts = jdbcTemplate.queryForList(postSql, userId);
        user.put("posts", posts);
        
        return AjaxResult.success(user);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> user) {
        String userName = (String) user.get("userName");
        
        // 检查用户名是否存在
        Integer count = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM sys_user WHERE user_name = ? AND del_flag = '0'",
            Integer.class, userName);
        if (count != null && count > 0) {
            return AjaxResult.error("用户名已存在");
        }
        
        String password = (String) user.getOrDefault("password", "123456");
        String encodedPassword = passwordEncoder.encode(password);
        
        String sql = "INSERT INTO sys_user (dept_id, user_name, nick_name, email, phonenumber, " +
                    "sex, password, status, create_by, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'admin', NOW())";
        
        jdbcTemplate.update(sql,
            user.get("deptId"),
            userName,
            user.getOrDefault("nickName", userName),
            user.get("email"),
            user.get("phonenumber"),
            user.getOrDefault("sex", "0"),
            encodedPassword,
            user.getOrDefault("status", "0")
        );
        
        // 获取新用户ID
        Long userId = jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Long.class);
        
        // 分配角色
        if (user.get("roleIds") != null) {
            @SuppressWarnings("unchecked")
            List<Integer> roleIds = (List<Integer>) user.get("roleIds");
            for (Integer roleId : roleIds) {
                jdbcTemplate.update("INSERT INTO sys_user_role (user_id, role_id) VALUES (?, ?)", userId, roleId);
            }
        }
        
        // 分配岗位
        if (user.get("postIds") != null) {
            @SuppressWarnings("unchecked")
            List<Integer> postIds = (List<Integer>) user.get("postIds");
            for (Integer postId : postIds) {
                jdbcTemplate.update("INSERT INTO sys_user_post (user_id, post_id) VALUES (?, ?)", userId, postId);
            }
        }
        
        return AjaxResult.success("新增成功");
    }

    /**
     * 修改用户
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String, Object> user) {
        Long userId = Long.valueOf(user.get("userId").toString());
        
        String sql = "UPDATE sys_user SET dept_id = ?, nick_name = ?, email = ?, " +
                    "phonenumber = ?, sex = ?, status = ?, update_by = 'admin', update_time = NOW() " +
                    "WHERE user_id = ?";
        
        jdbcTemplate.update(sql,
            user.get("deptId"),
            user.get("nickName"),
            user.get("email"),
            user.get("phonenumber"),
            user.getOrDefault("sex", "0"),
            user.getOrDefault("status", "0"),
            userId
        );
        
        // 更新角色
        jdbcTemplate.update("DELETE FROM sys_user_role WHERE user_id = ?", userId);
        if (user.get("roleIds") != null) {
            @SuppressWarnings("unchecked")
            List<Integer> roleIds = (List<Integer>) user.get("roleIds");
            for (Integer roleId : roleIds) {
                jdbcTemplate.update("INSERT INTO sys_user_role (user_id, role_id) VALUES (?, ?)", userId, roleId);
            }
        }
        
        // 更新岗位
        jdbcTemplate.update("DELETE FROM sys_user_post WHERE user_id = ?", userId);
        if (user.get("postIds") != null) {
            @SuppressWarnings("unchecked")
            List<Integer> postIds = (List<Integer>) user.get("postIds");
            for (Integer postId : postIds) {
                jdbcTemplate.update("INSERT INTO sys_user_post (user_id, post_id) VALUES (?, ?)", userId, postId);
            }
        }
        
        return AjaxResult.success("修改成功");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable String userIds) {
        String[] ids = userIds.split(",");
        for (String id : ids) {
            if ("1".equals(id)) {
                return AjaxResult.error("不允许删除超级管理员");
            }
            jdbcTemplate.update("UPDATE sys_user SET del_flag = '2' WHERE user_id = ?", Long.valueOf(id));
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 重置密码
     */
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody Map<String, Object> user) {
        Long userId = Long.valueOf(user.get("userId").toString());
        String password = (String) user.getOrDefault("password", "123456");
        String encodedPassword = passwordEncoder.encode(password);
        
        jdbcTemplate.update("UPDATE sys_user SET password = ?, update_time = NOW() WHERE user_id = ?",
            encodedPassword, userId);
        
        return AjaxResult.success("密码重置成功");
    }

    /**
     * 修改状态
     */
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody Map<String, Object> user) {
        Long userId = Long.valueOf(user.get("userId").toString());
        String status = (String) user.get("status");
        
        jdbcTemplate.update("UPDATE sys_user SET status = ?, update_time = NOW() WHERE user_id = ?",
            status, userId);
        
        return AjaxResult.success("状态修改成功");
    }

    /**
     * 获取部门树
     */
    @GetMapping("/deptTree")
    public AjaxResult deptTree() {
        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));
    }

    /**
     * 获取角色列表（下拉选项）
     */
    @GetMapping("/roleOptions")
    public AjaxResult roleOptions() {
        String sql = "SELECT role_id as roleId, role_name as roleName FROM sys_role " +
                    "WHERE status = '0' AND del_flag = '0' ORDER BY role_sort";
        return AjaxResult.success(jdbcTemplate.queryForList(sql));
    }

    /**
     * 获取岗位列表（下拉选项）
     */
    @GetMapping("/postOptions")
    public AjaxResult postOptions() {
        String sql = "SELECT post_id as postId, post_name as postName FROM sys_post " +
                    "WHERE status = '0' ORDER BY post_sort";
        return AjaxResult.success(jdbcTemplate.queryForList(sql));
    }

    /**
     * 构建树形结构
     */
    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;
    }
}
