package com.changhu.enums.handler;

import cn.dev33.satoken.stp.SaTokenInfo;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.changhu.common.db.enums.UserType;
import com.changhu.common.enums.ResultCode;
import com.changhu.common.exception.MessageException;
import com.changhu.common.pojo.vo.TokenInfo;
import com.changhu.common.utils.RsaUtil;
import com.changhu.common.utils.UserUtil;
import com.changhu.common.utils.ValidatorUtil;
import com.changhu.module.management.pojo.entity.ManagementSuperUser;
import com.changhu.pojo.params.ManagementSuperLoginParams;

/**
 * @author 20252
 * @createTime 2024/8/28 下午5:25
 * @desc ManagementSuperLogin...
 */
public class ManagementSuperLogin extends AbstractLoginHandler {

    public static final ManagementSuperLogin instance = new ManagementSuperLogin();

    private ManagementSuperLogin() {
    }

    @Override
    public TokenInfo login(JSONObject jsonObject) {
        ManagementSuperLoginParams loginParams = jsonObject.to(ManagementSuperLoginParams.class);
        ValidatorUtil.manual(loginParams);
        String telephone = loginParams.getTelephone();
        String password = RsaUtil.decrypt(loginParams.getPassword());

        //用户是否存在
        ManagementSuperUser user = Db.lambdaQuery(ManagementSuperUser.class)
                .eq(ManagementSuperUser::getTelephone, telephone)
                .oneOpt()
                .orElseThrow(() -> new MessageException(ResultCode.USER_NOT_FOUND));

        //判断密码是否正确
        if (!UserUtil.verifyPassWord(password, user.getSalt(), user.getPassword())) {
            throw new MessageException(ResultCode.PASSWORD_ERROR);
        }
        //登录
        SaTokenInfo saTokenInfo = UserUtil.loginAndTokenInfo(
                user.getSnowFlakeId(),
                UserType.MANAGEMENT_SUPER,
                null);
        //返回token
        return new TokenInfo(saTokenInfo.getTokenName(), saTokenInfo.getTokenValue());
    }
}
