package beilv.system.service.impl;

import beilv.common.enums.LoginTypeEnum;
import beilv.common.utils.rsa.RsaUtil;
import beilv.system.domain.SysMember;
import beilv.system.domain.vo.AppAuthLoginRespVO;
import beilv.system.domain.vo.AppAuthWeixinMiniAppLoginReqVO;
import beilv.system.mapper.SysMemberMapper;
import beilv.system.service.IAppAuthService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static beilv.common.enums.ErrorCodeConstants.AUTH_WEIXIN_MINI_APP_PHONE_CODE_ERROR;
import static beilv.common.enums.ErrorCodeConstants.MINI_AUTH_LOGIN_BAD;
import static beilv.common.servlet.ServletUtils.getClientIP;
import static beilv.common.utils.ExceptionUtil.exception;


/**
 * 会员的认证 Service 接口
 *
 * @author yshop
 */
@Service
@Slf4j
public class AppAuthServiceImpl implements IAppAuthService {

    @Resource
    private WxMaService wxMaService;
    @Autowired
    private SysMemberMapper sysMemberMapper;
    @Value("${rsa.publicKey}")
    private String publicKey;


    @Override
    public AppAuthLoginRespVO weixinMiniAppLogin(AppAuthWeixinMiniAppLoginReqVO reqVO) throws Exception {
        // 获得对应的手机号信息
        WxMaPhoneNumberInfo phoneNumberInfo;
        try {
            phoneNumberInfo = wxMaService.getUserService().getNewPhoneNoInfo(reqVO.getPhoneCode());
        } catch (Exception exception) {
            log.error(exception.getMessage());
            throw exception(AUTH_WEIXIN_MINI_APP_PHONE_CODE_ERROR);
        }
        WxMaJscode2SessionResult session;
        try {
            session = wxMaService.getUserService().getSessionInfo(reqVO.getLoginCode());
        } catch (WxErrorException e) {
            log.error(e.getMessage());
            throw exception(MINI_AUTH_LOGIN_BAD);
        }
        // 用户已经存在
        SysMember memberUserDO = sysMemberMapper.selectByMobile(phoneNumberInfo.getPhoneNumber());
        if (memberUserDO == null) {
            // 获得获得注册用户
            memberUserDO = sysMemberMapper.createUserIfAbsent(phoneNumberInfo.getPhoneNumber(), getClientIP(),
                    LoginTypeEnum.WXAPP.getValue());
            memberUserDO.setRealName("用户_" + memberUserDO.getId());

        }
        // 使用 sessionKey 和 openid 进行用户登录
        String openId = session.getOpenid();
        String sessionKey = session.getSessionKey();

        memberUserDO.setOpenId(session.getOpenid());
        sysMemberMapper.updateSysMember(memberUserDO);

        //加密
        String accessToken = RsaUtil.encrypt(memberUserDO.getId().toString(), publicKey);

        AppAuthLoginRespVO userInfo = new AppAuthLoginRespVO();
        userInfo.setAccessToken(accessToken);
        userInfo.setOpenId(openId);
        return userInfo;
    }

}
