package com.liquidnet.service.sweet.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Objects;

/**
 * <p>
 * 小程序登陆 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-07-27
 */
@Slf4j
@Service
public class SweetWechatLoginServiceImpl {

    @Autowired
    private SweetWechatService sweetWechatService;

    @Value("${liquidnet.service.adam.url}")
    private String adamUrl;

    public ResponseDto userInfo(String code, String encryptedData, String iv, Integer type) {
        log.info("\n参数code：[{}] ", code);
        log.info("\n参数encryptedData：[{}] ", encryptedData);
        log.info("\n参数iv：[{}] ", iv);
        log.info("\n参数type：[{}] ", type);
        try {
            WxMaJscode2SessionResult sessionInfo = sweetWechatService.sessionInfo(code, type);
            log.info("\nWxMaJscode2SessionResult：[{}] ", JsonUtils.toJson(sessionInfo));
            if (null == sessionInfo) {
                return ResponseDto.failure("login handler error");
            }

            // 解密手机号码信息
            WxMaPhoneNumberInfo wxMaPhoneNumberInfo = sweetWechatService.phoneNumberInfo(sessionInfo.getSessionKey(), encryptedData, iv, type);
            log.info("\nWxMaPhoneNumberInfo：[{}] ", wxMaPhoneNumberInfo.toString());
            if (Objects.isNull(wxMaPhoneNumberInfo) || StringUtils.isBlank(wxMaPhoneNumberInfo.getPhoneNumber())) {
                return ResponseDto.failure("解密手机号码信息错误");
            }

            registerByMobile(wxMaPhoneNumberInfo.getPurePhoneNumber());

            String unionId = sessionInfo.getUnionid();
            String openId = sessionInfo.getOpenid();

            HashMap<String, Object> userInfo = CollectionUtil.mapStringObject();
            userInfo.put("unionId", unionId);
            userInfo.put("openId", openId);
            userInfo.put("getPhoneNumber", wxMaPhoneNumberInfo.getPhoneNumber());
            userInfo.put("getPurePhoneNumber", wxMaPhoneNumberInfo.getPurePhoneNumber());
            userInfo.put("getCountryCode", wxMaPhoneNumberInfo.getCountryCode());

            return ResponseDto.success(userInfo);
        } catch (Exception e) {
            log.error("WechatUserInfoError", e);
            return ResponseDto.failure();
        }
    }

    @Async
    public void registerByMobile(String mobile) {
        try {
            MultiValueMap<String, String> params = new LinkedMultiValueMap();
            params.add("mobile", mobile);
            HttpUtil.post(adamUrl.concat("/adam/rsc/reg/mobile"), params);
        } catch (Exception e) {
            log.error("registerByMobile失败", e);
        }
    }

    public ResponseDto<String> wxaCode2Session(String jsCode, Integer type) {
        try {
            WxMaJscode2SessionResult wxMaJscode2SessionResult = sweetWechatService.sessionInfo(jsCode, type);
            return ResponseDto.success(wxMaJscode2SessionResult.getOpenid());
        } catch (Exception e) {
            log.error("wxaCode2SessionError", e);
            return ResponseDto.failure();
        }
    }

    public ResponseDto<String> wxOauth2AccessToken(String code, Integer type) {
        try {
            WxOAuth2AccessToken wxOAuth2AccessToken = sweetWechatService.wxOauth2AccessToken(code, type);
            return ResponseDto.success(wxOAuth2AccessToken.getOpenId());
        } catch (Exception e) {
            log.error("wxaCode2SessionError", e);
            return ResponseDto.failure();
        }
    }
}
