package com.zhentao.controller;

import com.zhentao.common.Result;
import com.zhentao.entity.AdminUser;
import com.zhentao.entity.Role;
import com.zhentao.service.AuthService;
import com.zhentao.service.RoleService;
import com.zhentao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理员用户管理控制器
 */
@RestController
@RequestMapping("/admin/admin-user")
@CrossOrigin(origins = "*")
public class AdminUserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 注册新管理员（仅超级管理员可用）
     */
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestBody Map<String, Object> params,
                                                  @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 验证token
            if (token == null || token.isEmpty()) {
                return Result.error(401, "未授权，请先登录");
            }
            
            AdminUser currentUser = authService.getUserByToken(token);
            if (currentUser == null) {
                return Result.error(401, "Token无效或已过期，请重新登录");
            }
            
            // 检查当前用户是否是超级管理员
            if (!userService.isSuperAdmin(currentUser.getId())) {
                return Result.error(403, "只有超级管理员可以注册新管理员");
            }
            
            // 获取参数
            String username = (String) params.get("username");
            String password = (String) params.get("password");
            String realName = (String) params.get("realName");
            String phone = (String) params.get("phone");
            String email = (String) params.get("email");
            Integer roleId = params.get("roleId") != null ? Integer.parseInt(params.get("roleId").toString()) : null;
            
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            if (password.length() < 6) {
                return Result.error("密码长度不能少于6位");
            }
            
            // 创建用户对象
            AdminUser user = new AdminUser();
            user.setUsername(username.trim());
            user.setPassword(password);
            user.setRealName(realName);
            user.setPhone(phone);
            user.setEmail(email);
            
            // 注册用户
            AdminUser newUser = userService.register(user, roleId);
            
            Map<String, Object> data = new HashMap<>();
            data.put("user", newUser);
            data.put("message", "注册成功");
            
            return Result.success(data);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("注册失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员列表（分页）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "keyword", required = false) String keyword) {
        try {
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<AdminUser> result = userService.getUserList(page, pageSize, keyword);
            
            // 为每个用户填充角色信息
            List<Map<String, Object>> userList = result.getRecords().stream().map(user -> {
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("id", user.getId());
                userMap.put("username", user.getUsername());
                userMap.put("realName", user.getRealName());
                userMap.put("phone", user.getPhone());
                userMap.put("email", user.getEmail());
                userMap.put("status", user.getStatus());
                userMap.put("createTime", user.getCreateTime());
                userMap.put("updateTime", user.getUpdateTime());
                userMap.put("lastLoginTime", user.getLastLoginTime());
                
                // 查询角色
                List<Role> roles = userService.getUserRoles(user.getId());
                userMap.put("roles", roles);
                
                return userMap;
            }).collect(Collectors.toList());
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", userList);
            data.put("total", result.getTotal());
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取管理员详情
     */
    @GetMapping("/detail/{userId}")
    public Result<Map<String, Object>> detail(@PathVariable Integer userId) {
        try {
            AdminUser user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("管理员不存在");
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("realName", user.getRealName());
            data.put("phone", user.getPhone());
            data.put("email", user.getEmail());
            data.put("status", user.getStatus());
            data.put("createTime", user.getCreateTime());
            data.put("updateTime", user.getUpdateTime());
            data.put("lastLoginTime", user.getLastLoginTime());
            
            // 查询角色
            List<Role> roles = userService.getUserRoles(userId);
            data.put("roles", roles);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新管理员信息
     */
    @PutMapping("/update/{userId}")
    public Result<String> update(@PathVariable Integer userId,
                                 @RequestBody Map<String, Object> params,
                                 @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 验证token
            if (token == null || token.isEmpty()) {
                return Result.error(401, "未授权，请先登录");
            }
            
            AdminUser currentUser = authService.getUserByToken(token);
            if (currentUser == null) {
                return Result.error(401, "Token无效或已过期，请重新登录");
            }
            
            // 检查是否是超级管理员
            if (!userService.isSuperAdmin(currentUser.getId())) {
                return Result.error(403, "只有超级管理员可以修改管理员信息");
            }
            
            AdminUser user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("管理员不存在");
            }
            
            // 更新字段
            if (params.containsKey("realName")) {
                user.setRealName((String) params.get("realName"));
            }
            if (params.containsKey("phone")) {
                user.setPhone((String) params.get("phone"));
            }
            if (params.containsKey("email")) {
                user.setEmail((String) params.get("email"));
            }
            if (params.containsKey("status")) {
                user.setStatus(Integer.parseInt(params.get("status").toString()));
            }
            if (params.containsKey("password")) {
                String password = (String) params.get("password");
                if (password != null && !password.isEmpty()) {
                    user.setPassword(password);
                }
            }
            
            // 更新角色
            if (params.containsKey("roleIds")) {
                @SuppressWarnings("unchecked")
                List<Integer> roleIds = (List<Integer>) params.get("roleIds");
                userService.assignRoles(userId, roleIds);
            }
            
            boolean success = userService.updateUser(user);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除管理员
     */
    @DeleteMapping("/delete/{userId}")
    public Result<String> delete(@PathVariable Integer userId,
                                 @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 验证token
            if (token == null || token.isEmpty()) {
                return Result.error(401, "未授权，请先登录");
            }
            
            AdminUser currentUser = authService.getUserByToken(token);
            if (currentUser == null) {
                return Result.error(401, "Token无效或已过期，请重新登录");
            }
            
            // 检查是否是超级管理员
            if (!userService.isSuperAdmin(currentUser.getId())) {
                return Result.error(403, "只有超级管理员可以删除管理员");
            }
            
            // 不能删除超级管理员
            if (userService.isSuperAdmin(userId)) {
                return Result.error("不能删除超级管理员");
            }
            
            // 不能删除自己
            if (userId.equals(currentUser.getId())) {
                return Result.error("不能删除自己");
            }
            
            boolean success = userService.deleteUser(userId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 禁用管理员
     */
    @PutMapping("/disable/{userId}")
    public Result<String> disable(@PathVariable Integer userId,
                                  @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 验证token
            if (token == null || token.isEmpty()) {
                return Result.error(401, "未授权，请先登录");
            }
            
            AdminUser currentUser = authService.getUserByToken(token);
            if (currentUser == null) {
                return Result.error(401, "Token无效或已过期，请重新登录");
            }
            
            // 检查是否是超级管理员
            if (!userService.isSuperAdmin(currentUser.getId())) {
                return Result.error(403, "只有超级管理员可以禁用管理员");
            }
            
            // 不能禁用超级管理员
            if (userService.isSuperAdmin(userId)) {
                return Result.error("不能禁用超级管理员");
            }
            
            // 不能禁用自己
            if (userId.equals(currentUser.getId())) {
                return Result.error("不能禁用自己");
            }
            
            AdminUser user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("管理员不存在");
            }
            
            user.setStatus(0); // 禁用
            boolean success = userService.updateUser(user);
            if (success) {
                return Result.success("禁用成功");
            } else {
                return Result.error("禁用失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("禁用失败：" + e.getMessage());
        }
    }
    
    /**
     * 启用管理员
     */
    @PutMapping("/enable/{userId}")
    public Result<String> enable(@PathVariable Integer userId,
                                  @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 验证token
            if (token == null || token.isEmpty()) {
                return Result.error(401, "未授权，请先登录");
            }
            
            AdminUser currentUser = authService.getUserByToken(token);
            if (currentUser == null) {
                return Result.error(401, "Token无效或已过期，请重新登录");
            }
            
            // 检查是否是超级管理员
            if (!userService.isSuperAdmin(currentUser.getId())) {
                return Result.error(403, "只有超级管理员可以启用管理员");
            }
            
            AdminUser user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("管理员不存在");
            }
            
            user.setStatus(1); // 启用
            boolean success = userService.updateUser(user);
            if (success) {
                return Result.success("启用成功");
            } else {
                return Result.error("启用失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("启用失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有角色列表（用于注册和编辑时选择角色）
     */
    @GetMapping("/roles")
    public Result<List<Role>> getRoles() {
        try {
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Role> rolePage = roleService.getRoleList(1, 100, null);
            return Result.success(rolePage.getRecords());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取角色列表失败：" + e.getMessage());
        }
    }
}

