package com.das.modules.auth.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.das.common.captcha.CaptchaUtil;
import com.das.common.exceptions.ServiceException;
import com.das.common.result.R;
import com.das.common.result.ResultCode;
import com.das.common.utils.AESUtil;
import com.das.common.utils.AdminRedisTemplate;
import com.das.modules.auth.domain.LoginUserDetails;
import com.das.modules.auth.domain.request.LoginRequest;
import com.das.modules.auth.domain.vo.SysUserVo;
import com.das.modules.auth.entity.SysUser;
import com.das.modules.auth.mapper.SysUserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.das.modules.auth.domain.vo.LoginVO;
import com.das.modules.auth.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenhaojie
 * @Description
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private AdminRedisTemplate adminRedisTemplate;

    @Resource
    private AESUtil aesUtil;

    @Value("${aesKey}")
    private String key;

//    @Override
//    public String login(LoginRequest loginRequest) {
//        String captcha = loginRequest.getUsername();
//        String account = loginRequest.getUsername();
//        String password = loginRequest.getPassword();
//        String uuid = loginRequest.getPassword();
//
//        // 验证码验证逻辑（这里省略，需根据实际情况实现）
//        if (CaptchaUtil.checkVerificationCode(uuid, captcha, adminRedisTemplate)) {
//            return "验证码错误";
//        }
//        // 用户名密码验证
////        if (isValidUser(account, password)) {
//            // 登录成功，使用Sa-Token生成Token
//            StpUtil.login(account);
//            // 返回Token给客户端
//            return StpUtil.getTokenValue();
////        } else {
////            return "用户名或密码错误";
//
//    }

    @Override
    public LoginUserDetails login(String param, HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {
        String iv = request.getHeader("v");
        System.out.println("iv:" + iv);
        param = aesUtil.decrypt(key, param, iv);
        ObjectMapper objectMapper = new ObjectMapper();
        LoginRequest loginRequest = objectMapper.readValue(param, LoginRequest.class);
        String name = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        String code = loginRequest.getCode();
        String uuid = loginRequest.getUuid();


        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysUser::getAccount, loginRequest.getUsername());
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (sysUser == null) {
            throw new ServiceException("无账号信息");
        }
        if (!CaptchaUtil.checkVerificationCode(uuid, code, adminRedisTemplate)) {
            throw new ServiceException("验证码不正确");
        }
        StpUtil.login(sysUser.getId()); // 执行登录，这里username为用户唯一标识
        SysUserVo sysUserVo = new SysUserVo();
        sysUserVo.setId(sysUser.getId());
        sysUserVo.setAccount(sysUser.getAccount());
        sysUserVo.setUserName(sysUser.getUserName());
        sysUserVo.setPhone(sysUser.getPhone());
        sysUserVo.setEmail(sysUser.getEmail());
        sysUserVo.setOrgId(sysUser.getOrgId());
        LoginUserDetails loginInfo = new LoginUserDetails();
        loginInfo.setSysUser(sysUserVo); // 存储用户信息到会话
        loginInfo.setToken(StpUtil.getTokenValue());
        return loginInfo;
    }


    @Override
    public boolean logout(HttpServletRequest request) {
        String iv = request.getHeader("v");
        String token = request.getHeader("token");
        System.out.println("iv:" + iv);
        token = aesUtil.decrypt(key, token, iv);
        StpUtil.logoutByTokenValue(token);
        return true;
    }

    @Override
    public LoginVO refreshToken(String refreshToken) {
//        Claims claim = tokenService.getClaim(refreshToken);
//        String uuid = (String) claim.get("uuid");
//        String username = (String) claim.get("username");
//        String refresh = (String) claim.get("refresh");
//        if (StrUtil.isEmpty(refresh)) {
//            throw new BusinessException("非法token");
//        }
//        LoginUserDetails loginUserDetails = adminRedisTemplate.get(username + ":refresh:" + uuid);
//        if (loginUserDetails == null) {
//            throw new BusinessException("token过期，请重新登录");
//        }
//        String token = tokenService.createToken(loginUserDetails);
//        String newRefreshToken = tokenService.createRefreshToken(loginUserDetails);
//        String tokenPrefix = jwtProperties.getTokenPrefix();
//        // 删除原有刷新token
//        adminRedisTemplate.del(username + ":refresh:" + uuid);
//        return new LoginVO(tokenPrefix + " " + token, newRefreshToken, jwtProperties.getExpireTime());
        return new LoginVO();
    }

}
