package com.czg.service.account.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.czg.account.dto.auth.GetPhoneDTO;
import com.czg.account.dto.auth.LoginTokenDTO;
import com.czg.account.dto.auth.UserAuthorizationLoginDTO;
import com.czg.account.entity.UserInfo;
import com.czg.account.service.UserAuthorizationService;
import com.czg.account.service.UserInfoService;
import com.czg.constants.ParamCodeCst;
import com.czg.constants.SystemConstants;
import com.czg.enums.UserAuthSourceEnum;
import com.czg.exception.CzgException;
import com.czg.sa.MyStpLogic;
import com.czg.sa.StpKit;
import com.czg.service.account.util.AlipayUtil;
import com.czg.service.account.util.WechatAuthUtil;
import com.czg.system.service.SysParamsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class UserAuthorizationServiceImpl implements UserAuthorizationService {
    @Resource
    private WechatAuthUtil wechatAuthUtil;
    @Resource
    private AlipayUtil alipayUtil;
    @Resource
    private UserInfoService userInfoService;
    @DubboReference
    private SysParamsService paramsService;

    @Override
    public String getOpenId(String code, String source) {
        log.info(code);
        String openId;
        if (UserAuthSourceEnum.WECHAT.getValue().equals(source)) {
            openId = wechatAuthUtil.getAccountOpenId(code);
        } else {
            openId = alipayUtil.getOpenId(code, true);
        }
        return openId;
    }

    @Override
    public String getPhone(GetPhoneDTO phoneDTO) {
        String mobile;
        String openId;
        UserInfo userInfo = null;
        if (UserAuthSourceEnum.ALIPAY.getValue().equals(phoneDTO.getSource())) {
            openId = alipayUtil.getOpenId(phoneDTO.getCode(), true);
            mobile = alipayUtil.getMobile(phoneDTO.getEncryptedData());
            if (StrUtil.isNotBlank(openId)) {
                userInfo = userInfoService.queryChain().eq(UserInfo::getWechatOpenId, openId).one();
            }
        } else {
            JSONObject session = wechatAuthUtil.getSession(phoneDTO.getCode());
            String sessionKey = session.getString("session_key");
            openId = session.getString("openid");
            if (StrUtil.isNotBlank(openId)) {
                userInfo = userInfoService.queryChain().eq(UserInfo::getAlipayOpenId, openId).one();
            }
            String data = WechatAuthUtil.decrypt(sessionKey, phoneDTO.getEncryptedData(), phoneDTO.getIv());
            JSONObject jsonObject = JSONObject.parseObject(data);
            if (jsonObject.containsKey("phoneNumber")) {
                mobile = jsonObject.getString("phoneNumber");
            } else {
                throw new CzgException("手机号获取失败");
            }
        }

        if (userInfo != null) {
            userInfo.setPhone(mobile);
            userInfoService.updateById(userInfo);
        }
        return mobile;
    }

    @Override
    public LoginTokenDTO login(UserAuthorizationLoginDTO userAuthorizationLoginDTO) {

        UserInfo userInfo;
        String openId;
        if (UserAuthSourceEnum.WECHAT.getValue().equals(userAuthorizationLoginDTO.getSource())) {
            openId = wechatAuthUtil.getSessionKeyOrOpenId(userAuthorizationLoginDTO.getCode(), false);
            userInfo = userInfoService.queryChain().eq(UserInfo::getWechatOpenId, openId).one();
            userInfo = userInfo == null ? new UserInfo() : userInfo;
            userInfo.setNickName(StrUtil.isNotBlank(userInfo.getNickName()) ? userInfo.getNickName() : "微信用户");
            userInfo.setWechatOpenId(openId);
        } else {
            openId = alipayUtil.getOpenId(userAuthorizationLoginDTO.getCode(), false);
            userInfo = userInfoService.queryChain().eq(UserInfo::getAlipayOpenId, openId).one();
            userInfo = userInfo == null ? new UserInfo() : userInfo;
            userInfo.setNickName(StrUtil.isNotBlank(userInfo.getNickName()) ? userInfo.getNickName() : "支付宝用户");
            userInfo.setAlipayOpenId(openId);
        }

        if (userInfo.getStatus() != null && SystemConstants.OneZero.ZERO == userInfo.getStatus()) {
            throw new CzgException("账号已禁用");
        }

        userInfo.setLastLoginTime(DateUtil.date().toLocalDateTime());
        userInfoService.saveOrUpdate(userInfo);
        userInfoService.initAc(userInfo);
//        StpKit.USER.login(userInfo.getId());
        StpKit.USER.login(userInfo.getId(), openId, null, null, null, MyStpLogic.LoginType.USER, false, "userMini", false);
        String followIndex = paramsService.getSysParamValue(ParamCodeCst.System.FOLLOW_INDEX);
        return new LoginTokenDTO(StpKit.USER.getTokenValue(), followIndex, userInfo);
    }
}
