package com.jeequan.jeepay.thirdparty.oauth2;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.exception.ChannelException;
import com.jeequan.jeepay.core.interfaces.paychannel.IChannelUserService;
import com.jeequan.jeepay.core.model.QRCodeParams;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.oauth2.AlipayOauth2Params;
import com.jeequan.jeepay.core.model.params.alipay.AlipayConfig;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelUserInfoMsg;
import com.jeequan.jeepay.thirdparty.model.AlipayClientEntry;
import com.jeequan.jeepay.thirdparty.model.AlipayClientWrapper;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/*
* 支付宝： 获取用户ID实现类
*
* @author terrfly
*
* @date 2021/6/8 17:21
*/
@Service
@Slf4j
public class AlipayChannelUserService implements IChannelUserService {

    @Autowired private ConfigContextQueryService configContextQueryService;

    @Override
    public String getIfCode() {
        return CS.IF_CODE.ALIPAY;
    }

    @Override
    public ChannelUserInfoMsg buildUserRedirectUrl(String callbackUrlEncode, MchAppConfigContext mchAppConfigContext) {

        String oauthUrl = AlipayConfig.PROD_OAUTH_URL;
        String appId = null;

        if(mchAppConfigContext.isIsvsubMch()){

            // 查询商户 配置 的oauth2配置 ( 支付参数配置 )    selectOauth2InfoId: 配置的oauth2参数
            String ifCode = configContextQueryService.queryIfCodeByPageType(mchAppConfigContext, QRCodeParams.PAGE_TYPE_ALIPAY_H5);
            String selectOauth2InfoId = configContextQueryService.queryAgentOrIsvSelectOauth2InfoId(mchAppConfigContext.getMchApplyment(), ifCode);

            AlipayOauth2Params isvParams = (AlipayOauth2Params) configContextQueryService
                    .queryIsvOauth2ParamsByAutoSelectOauth2InfoId(mchAppConfigContext.getMchApplyment().getIsvNo(), getIfCode(), selectOauth2InfoId);
            if(isvParams == null) {
                throw new BizException("服务商支付宝oauth2参数没有配置！");
            }
            appId = isvParams.getAppId();
            if(isvParams.getSandbox() != null && isvParams.getSandbox() == CS.YES){
                oauthUrl = AlipayConfig.SANDBOX_OAUTH_URL;
            }
        }else{
            //获取商户配置信息
            AlipayOauth2Params normalMchParams = (AlipayOauth2Params) configContextQueryService.queryNormalOauth2Params(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), getIfCode());
            if(normalMchParams == null) {
                throw new BizException("商户应用支付宝oauth2参数没有配置！");
            }
            appId = normalMchParams.getAppId();
            if(normalMchParams.getSandbox() != null && normalMchParams.getSandbox() == CS.YES){
                oauthUrl = AlipayConfig.SANDBOX_OAUTH_URL;
            }
        }
        String alipayUserRedirectUrl = String.format(oauthUrl, appId, callbackUrlEncode);
        log.info("alipayUserRedirectUrl={}", alipayUserRedirectUrl);
        return ChannelUserInfoMsg.gen(alipayUserRedirectUrl, appId); // 支付宝不区分appId, alipayUserId 全局通用。 但是也需要区分沙箱和正式， 需要设置appID
    }

    @Override
    public String getChannelUserId(String pageType, JSONObject reqParams, MchAppConfigContext mchAppConfigContext, String ifCode) {

        Byte isUseSubmchAccount = reqParams.getByte("isUseSubmchAccount");
        if(isUseSubmchAccount == null){
            isUseSubmchAccount = CS.NO; // 默认使用 服务商账号
        }

        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(reqParams.getString("auth_code")); request.setGrantType("authorization_code");

//        ifCode = configContextQueryService.queryIfCodeByPageType(mchAppConfigContext, pageType);
        AlipayClientWrapper alipayClientWrapper = configContextQueryService.getAlipayClientWrapperByAutoOauth2(mchAppConfigContext, getIfCode());

        try {


            // 获取商户自己的小程序 openId
            if(QRCodeParams.PAGE_TYPE_ALIPAY_LITE.equals(pageType) && isUseSubmchAccount == CS.YES){
                return getOpenIdByIsvSubmchAccount(request, mchAppConfigContext);
            }


            // 小程序  && 服务商小程序配置不为空
            if(QRCodeParams.PAGE_TYPE_ALIPAY_LITE.equals(pageType) && alipayClientWrapper.getAlipayClientByOauth2Lite() != null){
                return alipayClientWrapper.getAlipayClientByOauth2Lite().execute(request).getUserId();
            }

            // 默认方式
            return alipayClientWrapper.getAlipayClientByOauth2().execute(request).getUserId();
        } catch (ChannelException e) {
            e.printStackTrace();
            return null;
        }
    }

    /** 获取商户自己的小程序 openId  **/
    private String getOpenIdByIsvSubmchAccount(AlipaySystemOauthTokenRequest req, MchAppConfigContext mchAppConfigContext) {

        AlipayOauth2Params alipayOauth2ParamsByMch = (AlipayOauth2Params) configContextQueryService.queryNormalOauth2Params
                (mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), CS.IF_CODE.ALIPAY);

        // 小程序的配置信息
        AlipayOauth2Params alipayOauth2Params = alipayOauth2ParamsByMch.getLiteParams();

        AlipayClientEntry clientByOauth2 = AlipayClientWrapper.buildAlipayClientWrapper(
                alipayOauth2Params.getUseCert(), alipayOauth2Params.getSandbox(), alipayOauth2Params.getAppId(), alipayOauth2Params.getPrivateKey(),
                alipayOauth2Params.getAlipayPublicKey(), alipayOauth2Params.getSignType(), alipayOauth2Params.getAppPublicCert(),
                alipayOauth2Params.getAlipayPublicCert(), alipayOauth2Params.getAlipayRootCert()
        );

        return clientByOauth2.execute(req).getUserId();
    }


}
