package com.yupi.project.controller;

import com.yupi.project.annotation.AuthCheck;
import com.yupi.project.common.BaseResponse;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.model.dto.user.UserLoginRequest;
import com.yupi.project.model.dto.user.UserRegisterRequest;
import com.yupi.project.model.entity.User;
import com.yupi.project.model.enums.UserRoleEnum;
import com.yupi.project.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    // --- 登录注册相关 --- //

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String username = userRegisterRequest.getUsername();
        String password = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(username, password, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        long result = userService.userRegister(username, password, checkPassword);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String username = userLoginRequest.getUsername();
        String password = userLoginRequest.getPassword();
        if (StringUtils.isAnyBlank(username, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        User user = userService.userLogin(username, password, request);
        return ResultUtils.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        User currentUser = userService.getCurrentUser(request);
        // getCurrentUser 内部已处理未登录情况，并返回脱敏用户
        return ResultUtils.success(currentUser);
    }

    @ApiOperation("获取当前登录用户的统计信息")
    @GetMapping("/stats/mine")
    @AuthCheck // 需要登录
    public BaseResponse<Map<String, Object>> getMyStats(HttpServletRequest request) {
        User loginUser = userService.getCurrentUser(request);
        Map<String, Object> stats = userService.getUserDashboardStats(loginUser.getId());
        return ResultUtils.success(stats);
    }

    // --- 管理员功能 --- //

    @GetMapping("/list")
    public BaseResponse<List<User>> listUsers(HttpServletRequest request) {
        // 权限校验 (在 SecurityConfig 中配置，这里可以简化或移除，但保留显式检查作为双重保险)
        User currentUser = userService.getCurrentUser(request); // 获取当前用户以检查角色
        if (currentUser == null || !UserRoleEnum.ADMIN.getValue().equals(currentUser.getRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无管理员权限");
        }
        List<User> userList = userService.listUsers(); // 调用新的 service 方法，它已经处理了脱敏
        return ResultUtils.success(userList);
    }

    // 新增管理员删除用户接口
    @DeleteMapping("/delete/{userId}")
    public BaseResponse<Boolean> adminDeleteUser(@PathVariable Long userId, HttpServletRequest request) {
        // 权限校验 (虽然 SecurityConfig 会拦截，但 Controller 层再校验一次更安全)
        User currentUser = userService.getCurrentUser(request);
        if (currentUser == null || !UserRoleEnum.ADMIN.getValue().equals(currentUser.getRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无管理员权限");
        }

        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID参数错误");
        }
        
        // 防止管理员误删自己 (可选逻辑)
        if (currentUser.getId().equals(userId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "不能删除当前登录的管理员账户");
        }

        boolean result = userService.adminDeleteUser(userId);
        return ResultUtils.success(result);
    }

    // 新增管理员添加用户接口
    @PostMapping("/admin/add")
    public BaseResponse<Long> adminAddUser(@RequestBody com.yupi.project.model.dto.user.UserAdminAddRequest addRequest, HttpServletRequest request) {
        // 权限校验
        User currentUser = userService.getCurrentUser(request);
        if (currentUser == null || !UserRoleEnum.ADMIN.getValue().equals(currentUser.getRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无管理员权限");
        }

        if (addRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }

        long newUserId = userService.adminAddUser(addRequest);
        return ResultUtils.success(newUserId);
    }

    // 新增管理员更新用户接口
    @PutMapping("/admin/update")
    public BaseResponse<Boolean> adminUpdateUser(@RequestBody com.yupi.project.model.dto.user.UserAdminUpdateRequest updateRequest, HttpServletRequest request) {
        // 权限校验
        User currentUser = userService.getCurrentUser(request);
        if (currentUser == null || !UserRoleEnum.ADMIN.getValue().equals(currentUser.getRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无管理员权限");
        }

        if (updateRequest == null || updateRequest.getId() == null || updateRequest.getId() <=0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误，必须提供用户ID");
        }
        
        // 防止管理员通过此接口修改自己的角色把自己改成普通用户，或修改关键的ADMIN账户 (可选)
        // 如果要更新的用户是当前登录的管理员，并且尝试修改角色为非admin，则拒绝
        if (currentUser.getId().equals(updateRequest.getId()) && 
            StringUtils.isNotBlank(updateRequest.getRole()) && 
            !UserRoleEnum.ADMIN.getValue().equals(updateRequest.getRole())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "管理员不能将自己的角色修改为非管理员");
        }

        boolean result = userService.adminUpdateUser(updateRequest);
        return ResultUtils.success(result);
    }
} 