package com.kexue.skills.controller;

import com.kexue.skills.annotation.RequireAuth;
import com.kexue.skills.entity.SysUser;
import com.kexue.skills.entity.dto.SysUserDto;
import com.kexue.skills.entity.request.*;
import com.kexue.skills.exception.BizException;
import com.kexue.skills.service.SysUserService;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import javax.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import com.kexue.skills.common.CacheManager;
import com.github.pagehelper.PageInfo;
import com.kexue.skills.common.CommonResult;
import com.kexue.skills.entity.base.IdDto;
import org.redisson.api.RedissonClient;

/**
 * (SysUser)表控制层
 *
 * @author 王志维
 * @since 2025-02-21 23:01:48
 */
@RestController
@RequestMapping("api/sysUser")
@Tag(name = "用户管理 Api")
@CrossOrigin(origins = "*")
public class SysUserController {
    /**
     * 服务对象
     */
    @Resource
    private SysUserService sysUserService;
    
    /**
     * Redisson客户端
     */
    @Resource
    private RedissonClient redissonClient;
    /**
     * 分页查询
     *
     * @param queryDto 筛选条件
     * @return 查询结果
     */
    @PostMapping("/getPageList")
    @Operation(summary = "查询分页列表", description = "查询分页列表")
    public CommonResult<PageInfo<SysUser>> getPageList(@RequestBody SysUserDto queryDto) {
        return CommonResult.success(sysUserService.getPageList(queryDto));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @PostMapping("queryById/{id}")
    @Operation(summary = "通过ID查询用户", description = "通过ID查询用户")
    public CommonResult<SysUser> queryById(@PathVariable("id") Long id) {
        return CommonResult.success(sysUserService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param SysUser 实体
     * @return 新增结果
     */
    @PostMapping("/insert")
    @Operation(summary = "新增用户", description = "新增用户")
    public CommonResult<SysUser> insert(@RequestBody SysUser SysUser) {
        return CommonResult.success(sysUserService.insert(SysUser));
    }

    /**
     * 编辑数据
     *
     * @param SysUser 实体
     * @return 编辑结果
     */
    @PostMapping("/update")
    @Operation(summary = "更新用户", description = "更新用户")
    public CommonResult<SysUser> update(@RequestBody SysUserUpdateDto SysUser) {
        return CommonResult.success(sysUserService.update(SysUser));
    }

    /**
     * 删除数据
     *
     * @param id
     * @return 删除数据
     */
    @PostMapping("deleteById/{id}")
    @Operation(summary = "通过ID删除用户", description = "通过ID删除用户")
    public CommonResult<Boolean> deleteById(@PathVariable("id") Long id) {
        return CommonResult.success(sysUserService.deleteById(id));
    }

    @PostMapping("deleteByIdDto")
    @Operation(summary = "通过ID删除用户", description = "通过ID删除用户")
    public CommonResult<Boolean> deleteByIdDto(@RequestBody IdDto idDto) {
        return CommonResult.success(sysUserService.deleteById(idDto.getId()));
    }

    @PostMapping("/resetPassword")
    @Operation(summary = "管理员帮助用户重置密码", description = "管理员帮助用户重置密码")
    @RequireAuth
    public CommonResult<Boolean> resetPassword(@RequestBody ResetPwdDto resetPasswordDto) {
        boolean result = sysUserService.resetPassword(resetPasswordDto);
        return CommonResult.success(result);
    }

    /**
     * 重置密码（管理员专用，通过用户ID）
     *
     * @param resetPwdDto 重置密码请求参数
     * @param request HTTP请求
     * @return 重置结果
     */
    @PostMapping("/resetPwd")
    @Operation(summary = "重置密码（管理员专用，通过用户ID）", description = "重置密码（管理员专用，通过用户ID）")
    @RequireAuth
    public CommonResult<Boolean> resetPwd(@RequestBody ResetPwdDto resetPwdDto, HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new BizException("请先登录认证后操作");
        }

        // 从缓存中获取当前登录用户
        String username = CacheManager.getUsernameFromToken(token);
        if (username == null) {
            throw new BizException("无效的token，请重新登录");
        }

        SysUser adminUser = sysUserService.getByUsername(username);
        if (adminUser == null) {
            throw new BizException("管理员不存在");
        }

        // 调用服务层方法重置密码
        boolean result = sysUserService.resetPwd(resetPwdDto.getUserId(), resetPwdDto.getNewPassword(), username);
        return CommonResult.success(result);
    }
    
    /**
     * 重置密码（管理员专用，通过用户名或手机号）
     *
     * @param resetPasswordDto 重置密码请求参数
     * @param request HTTP请求
     * @return 重置结果
     */
    @PostMapping("/resetPasswordByUsernameOrPhone")
    @Operation(summary = "重置密码（管理员专用，通过用户名或手机号）", description = "重置密码（管理员专用，通过用户名或手机号，无需旧密码）")
    @RequireAuth
    public CommonResult<Boolean> resetPasswordByUsernameOrPhone(@RequestBody AdminResetPasswordDto resetPasswordDto, HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new BizException("请先登录认证后操作");
        }

        // 从缓存中获取当前登录用户
        String username = CacheManager.getUsernameFromToken(token);
        if (username == null) {
            throw new BizException("无效的token，请重新登录");
        }

        SysUser adminUser = sysUserService.getByUsername(username);
        if (adminUser == null) {
            throw new BizException("管理员不存在");
        }

        // 调用服务层方法重置密码
        boolean result = sysUserService.resetPasswordByUsernameOrPhone(resetPasswordDto.getUsernameOrPhone(), resetPasswordDto.getNewPassword(), username);
        return CommonResult.success(result);
    }

    /**
     * 获取当前登录用户信息
     *
     * @param request HTTP请求
     * @return 当前登录用户信息
     */
    @GetMapping("/currentUser")
    @Operation(summary = "获取当前登录用户信息", description = "获取当前登录用户信息")
    @RequireAuth
    public CommonResult<LoginUserDto> currentUser(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new BizException("请先登录认证后操作");
        }

        // 使用Sa-Token检查token是否有效
        try {
            cn.dev33.satoken.stp.StpUtil.checkLogin();
        } catch (Exception e) {
            throw new BizException("无效的token，请重新登录");
        }

        // 从Redis缓存中获取LoginUser对象
        String loginUserJson = (String)redissonClient.getBucket("loginUser:" + token).get();
        if (loginUserJson == null || loginUserJson.isEmpty()) {
            throw new BizException("无效的token，请重新登录");
        }
        
        // 解析JSON字符串为LoginUser对象
        com.kexue.skills.entity.request.LoginUser loginUser = cn.hutool.json.JSONUtil.toBean(loginUserJson, com.kexue.skills.entity.request.LoginUser.class);
        
        // 转换为LoginUserDto
        LoginUserDto loginUserDto = new LoginUserDto();
        loginUserDto.setToken(loginUser.getToken());
        loginUserDto.setUserInfo(loginUser.getUserInfo());
        loginUserDto.setFavorites(loginUser.getFavorites());
        loginUserDto.setHistory(loginUser.getHistory());
        loginUserDto.setCreate(loginUser.getCreate());
        loginUserDto.setHas(loginUser.getHas());
        
        return CommonResult.success(loginUserDto);
    }
}
