package com.boman.wechat.utils;


import com.alibaba.fastjson.JSONObject;
import com.boman.domain.AppletLoginForm;
import com.boman.domain.dto.AppletSessionDTO;
import com.boman.domain.utils.AppletDecryptDataUtil;
import com.boman.domain.utils.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

/**
 *
 */
@Component
@Slf4j
@RefreshScope
public class WxCodeSessionUtil {


    /**
     * 根据code获取小程序openid和unionid
     */
    private static final String JSCODE_SESSION_API = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

    /**
     * 小程序appId
     */
    @Value("${wx.appId}")
    private String appId;

    /**
     * 小程序密钥
     */
    @Value("${wx.appSecret}")
    private String appSecret;


    /**
     * 根据code获取小程序openid和unionid
     *
     * @param form
     * @return
     */
    public AppletSessionDTO jscode2Session(AppletLoginForm form) {
        // 获取openId和sessionKey
        JSONObject result;
        try {
            String requestUrl = JSCODE_SESSION_API.replace("APPID", this.appId)
                    .replace("SECRET", this.appSecret)
                    .replace("JSCODE", form.getCode().trim());

            String jsonStr = HttpClientUtils.doGet1(requestUrl);
            result = JSONObject.parseObject(jsonStr);
            if (StringUtils.isEmpty(result.toString())) {
                throw new RuntimeException("错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("错误");
        }

        int errcode = result.getIntValue("errcode");
        if (errcode != 0) {
            String errmsg = result.getString("errmsg");
            throw new RuntimeException("获取小程序授权错误信息, " + errmsg);
        }
        // 获取openId,unionId,sessionKey
        AppletSessionDTO appletSession = new AppletSessionDTO();
        appletSession.setOpenId(result.getString("openid"));
        // unionId有可能是空
        appletSession.setUnionId(result.getString("unionid"));
        appletSession.setSessionKey(result.getString("session_key"));

        System.out.println();
        String phoneNumber = getPhoneNumber(form, appletSession);
        appletSession.setPhoneNumber(phoneNumber);
        return appletSession;
    }

    /**
     * 手机号解密
     */
    private String getPhoneNumber(AppletLoginForm form, AppletSessionDTO appletSession) {

        // 解密文件
        String encryptedData = form.getEncryptedData();
        // 解密向量
        String iv = form.getIv();
        // 加密秘钥
        byte[] dataByte = Base64.decode(encryptedData);
        // session_key
        byte[] keyByte = Base64.decode(appletSession.getSessionKey());
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        JSONObject result;
        try {
            result = AppletDecryptDataUtil.decryptData(keyByte, ivByte, dataByte);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        assert result != null;
        String purePhoneNumber = result.getString("purePhoneNumber");
        if (null == purePhoneNumber || purePhoneNumber.isEmpty()) {
            throw new RuntimeException("获取手机号失败");
        }
        return purePhoneNumber;
    }


}
