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.security.crypto.bcrypt.BCryptPasswordEncoder;
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 pangu
 */
@RestController
@RequestMapping("/api/system/user")
public class SysUserController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 查询用户列表
     */
    @GetMapping("/list")
    public AjaxResult list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String phonenumber,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long deptId) {

        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 ancestors LIKE CONCAT('%,', ?, ',%') OR ancestors LIKE CONCAT('%,', ?))) ");
            params.add(deptId);
            params.add(deptId);
            params.add(deptId);
        }

        // 统计总数
        String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") t";
        Integer total = jdbcTemplate.queryForObject(countSql, Integer.class, params.toArray());

        // 分页查询
        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());

        // 返回分页格式数据
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "查询成功");
        result.put("rows", rows);
        result.put("total", total != null ? total : 0);
        return AjaxResult.success(result).put("rows", rows).put("total", total != null ? total : 0);
    }

    /**
     * 获取用户详情
     */
    @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'";
        Map<String, Object> user = jdbcTemplate.queryForMap(sql, userId);

        // 查询用户角色
        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);
    }

    /**
     * 获取角色和岗位选项
     */
    @GetMapping("/options")
    public AjaxResult getOptions() {
        Map<String, Object> result = new HashMap<>();

        // 查询所有角色
        List<Map<String, Object>> roles = jdbcTemplate.queryForList(
                "SELECT role_id, role_name FROM sys_role WHERE status = '0' AND del_flag = '0' ORDER BY role_sort");
        result.put("roles", roles);

        // 查询所有岗位
        List<Map<String, Object>> posts = jdbcTemplate.queryForList(
                "SELECT post_id, post_name FROM sys_post WHERE status = '0' ORDER BY post_sort");
        result.put("posts", posts);

        return AjaxResult.success(result);
    }

    /**
     * 获取角色列表（下拉选项）
     */
    @GetMapping("/roleOptions")
    public AjaxResult roleOptions() {
        List<Map<String, Object>> roles = jdbcTemplate.queryForList(
                "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(roles);
    }

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

    /**
     * 新增用户
     */
    @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 > 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.get("nickName"),
                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) {
            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) {
            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) {
            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) {
            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() {
        List<Map<String, Object>> depts = jdbcTemplate.queryForList(
                "SELECT dept_id, parent_id, dept_name FROM sys_dept WHERE status = '0' AND del_flag = '0' ORDER BY order_num");

        List<Map<String, Object>> tree = buildTree(depts, 0L);
        return AjaxResult.success(tree);
    }

    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 deptId = ((Number) item.get("dept_id")).longValue();
                node.put("id", deptId);
                node.put("label", item.get("dept_name"));
                List<Map<String, Object>> children = buildTree(list, deptId);
                if (!children.isEmpty()) {
                    node.put("children", children);
                }
                result.add(node);
            }
        }
        return result;
    }
}
