package com.changhu.enums.handler;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.changhu.common.db.enums.CheckStatus;
import com.changhu.common.db.enums.IsEnable;
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.UserUtil;
import com.changhu.common.utils.ValidatorUtil;
import com.changhu.module.miniProgram.pojo.entity.MiniProgramUser;
import com.changhu.pojo.params.MiniProgramUserLoginParams;
import me.chanjar.weixin.common.error.WxErrorException;

/**
 * @author 20252
 * @createTime 2024/9/10 上午10:00
 * @desc MiniProgramUserLogin...
 */
public class MiniProgramUserLogin extends AbstractLoginHandler {

    public static final MiniProgramUserLogin instance = new MiniProgramUserLogin();

    private MiniProgramUserLogin() {
    }

    @Override
    public TokenInfo login(JSONObject jsonObject) {
        MiniProgramUserLoginParams loginParams = jsonObject.to(MiniProgramUserLoginParams.class);
        ValidatorUtil.manual(loginParams);
        String code = loginParams.getCode();

        String openId;
        final WxMaService wxMaService = SpringUtil.getBean(WxMaService.class);

        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            throw new MessageException(e.getMessage());
        }

        MiniProgramUser miniProgramUser = Db.lambdaQuery(MiniProgramUser.class)
                .eq(MiniProgramUser::getOpenId, openId)
                .oneOpt()
                .orElseThrow(() -> new MessageException(ResultCode.USER_NOT_FOUND));

        if (CheckStatus.unChecked.equals(miniProgramUser.getCheckStatus())) {
            throw new MessageException("该账号还未审核");
        }

        if (IsEnable.FALSE.equals(miniProgramUser.getIsEnable())) {
            throw new MessageException(ResultCode.USER_IS_DISABLE);
        }

        UserType userType = switch (miniProgramUser.getIdentity()) {
            case POLICE -> UserType.MINI_PROGRAM_POLICE;
            case PROJECT_MANAGER -> UserType.MINI_PROGRAM_PROJECT_MANAGE;
        };

        //登录
        SaTokenInfo saTokenInfo = UserUtil.loginAndTokenInfo(
                miniProgramUser.getSnowFlakeId(),
                userType,
                miniProgramUser.getUnitId());
        //返回token
        return new TokenInfo(
                saTokenInfo.getTokenName(),
                saTokenInfo.getTokenValue(),
                Dict.of(LambdaUtil.getFieldName(MiniProgramUser::getIdentity), miniProgramUser.getIdentity())
        );
    }
}
