package com.koobietech.eas.service.impl;

import com.koobietech.eas.common.exception.EasException;
import com.koobietech.eas.common.pojo.JwtUserPojo;
import com.koobietech.eas.common.utils.JwtManager;
import com.koobietech.eas.common.utils.PasswordManager;
import com.koobietech.eas.dao.constant.UserType;
import com.koobietech.eas.dao.dto.LoginTokenDto;
import com.koobietech.eas.dao.pojo.UserDetailPojo;
import com.koobietech.eas.dao.mapper.AdminLoginMapper;
import com.koobietech.eas.dao.pojo.AdminPojo;
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.EasSysUserLoginRedisService;
import com.koobietech.eas.service.EasSysStudentLoginService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

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

/**
 * @author lc
 */
@Service
public class EasSysStudentLoginServiceImpl implements EasSysStudentLoginService {


    @Resource
    EasSysStudentMapper easSysStudentMapper;

    @Resource
    PasswordManager passwordManager;

    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    AdminLoginMapper adminLoginMapper;

    @Resource
    EasSysUserLoginRedisService studentLoginRedisService;

    @Resource
    JwtManager jwtManager;

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

    private final Integer refreshToken_expires = 48 * 60 * 60;

    @Override
    public LoginTokenDto 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里面
        UserDetailPojo userDetailPojo = adminLoginMapper.getStudentDetailById(adminId);
        userDetailPojo.setDepartments(adminLoginMapper.getStudentDepartmentsById(adminId));
        userDetailPojo.setPermissionPojos(adminLoginMapper.getStudentPermissionsById(adminId));

        userDetailPojo.setUserType(UserType.MEMBER);
        // 生成token
        JwtUserPojo jwtUserPojo = new JwtUserPojo(userDetailPojo.getUsername(), userDetailPojo.getId(), UserType.MEMBER);

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

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

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

        String jwtRefreshTokenKey = studentLoginRedisService.createJwtRefreshTokenKey(jwtUserPojo);

        // 将token存入redis
        studentLoginRedisService.loginSaveCache(jwtTokenKey, userDetailPojo, token_expires);

        studentLoginRedisService.loginSaveCache(jwtRefreshTokenKey, userDetailPojo, refreshToken_expires);

        // 登录成功
        return new LoginTokenDto(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);
        }
    }
}
