package com.koobietech.eas.service.impl;

import com.anji.captcha.model.common.ResponseModel;
import com.koobietech.eas.common.constant.UserType;
import com.koobietech.eas.common.exception.EasException;
import com.koobietech.eas.common.pojo.JwtUserDto;
import com.koobietech.eas.common.result.JsonResult;
import com.koobietech.eas.common.utils.JwtManager;
import com.koobietech.eas.common.utils.PasswordManager;
import com.koobietech.eas.dao.Pojo.AdminPojo;
import com.koobietech.eas.dao.adminLoginPojo.UserDetail;
import com.koobietech.eas.dao.dto.LoginToken;
import com.koobietech.eas.dao.mapper.AdminLoginMapper;
import com.koobietech.eas.mbg.mapper.EasSysStudentMapper;
import com.koobietech.eas.mbg.model.EasSysStudent;
import com.koobietech.eas.mbg.model.EasSysStudentExample;
import com.koobietech.eas.service.StudentLoginRedisService;
import com.koobietech.eas.service.StudentLoginService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
public class StudentLoginServiceImpl implements StudentLoginService {


    @Resource
    EasSysStudentMapper easSysStudentMapper;

    @Resource
    PasswordManager passwordManager;

    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    AdminLoginMapper adminLoginMapper;

    @Resource
    StudentLoginRedisService studentLoginRedisService;

    @Resource
    JwtManager jwtManager;

    // token过期时间 单位：s
    private final Integer token_expires = 60 * 3;

    private final Integer refreshToken_expires = 60 * 7;

    @Override
    public LoginToken studentLogin(AdminPojo adminPojo) {
        if (adminPojo.getUsername() == null || adminPojo.getPasswd() == null
                || adminPojo.getUsername().equals("") || adminPojo.getPasswd().equals("")) {
            throw new EasException("用户不存在", 412);
        }
        EasSysStudent easSysStudent = findStudentByUsername(adminPojo.getUsername(), adminPojo.getPasswd());

        Long adminId = easSysStudent.getId();

        //先调用自定义sql查询detail类中的数据 最后把这个类封装到redis里面
        UserDetail userDetail = adminLoginMapper.getStudentDetailById(adminId);
        userDetail.setDepartments(adminLoginMapper.getStudentDepartmentsById(adminId));
        userDetail.setPermissions(adminLoginMapper.getStudentPermissionsById(adminId));

        UserType student = UserType.MEMBER;
        // 生成token
        JwtUserDto jwtUserDto = new JwtUserDto(userDetail.getUsername(), userDetail.getId(), student);

        String token = jwtManager.createJwt(jwtUserDto, token_expires);

        String refreshToken = jwtManager.createJwt(jwtUserDto, refreshToken_expires);

        // 生成redis key
        String jwtTokenKey = studentLoginRedisService.createJwtTokenKey(jwtUserDto);

        String jwtRefreshTokenKey = studentLoginRedisService.createJwtRefreshTokenKey(jwtUserDto);

        // 将token存入redis
        studentLoginRedisService.loginSavaCache(jwtTokenKey, userDetail, token_expires);

        studentLoginRedisService.loginSavaCache(jwtRefreshTokenKey, userDetail, refreshToken_expires);

        // 登录成功
        return new LoginToken(token, refreshToken);
    }

    private EasSysStudent findStudentByUsername(String username, String password) {
        EasSysStudentExample easSysStudentExample = new EasSysStudentExample();
        easSysStudentExample.createCriteria().andStudentNameEqualTo(username);
        List<EasSysStudent> studentList = easSysStudentMapper.selectByExample(easSysStudentExample);
        Optional<EasSysStudent> optionalStudent = studentList.stream().findFirst();

        if (optionalStudent.isEmpty()) {
            throw new EasException("用户不存在", 9902);
        }
        if (studentList.size() > 1) {
            throw new EasException("用户数据异常", 9902);
        }
        EasSysStudent easSysStudent = optionalStudent.get();
        // 验证密码 这个方法里面有解密 如果解密失败会抛出异常
        validatePassword(password, easSysStudent.getPasswd());
        return easSysStudent;
    }

    private void validatePassword(String inputPassword, String encryptedPassword) {
        String decryptedPassword = passwordManager.decryptPassword(inputPassword);
        if (!passwordEncoder.matches(decryptedPassword, encryptedPassword)) {
            throw new EasException("密码不正确", 9901);
        }
    }
}
