package com.jeequan.jeepay.thirdparty.channel.sxfpay;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.interfaces.paychannel.IChannelUserService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.sxfpay.SxfpayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelUserInfoMsg;
import com.jeequan.jeepay.thirdparty.channel.sxfpay.model.ReqMethod;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* 银盛 获取银联userId实现类
*
* @author jmdhapy
*
* @date 2022/3/17 16:51
*/
@Service
@Slf4j
public class SxfpayChannelUserService implements IChannelUserService {

    @Autowired protected ConfigContextQueryService configContextQueryService;

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

    @Override
    public ChannelUserInfoMsg buildUserRedirectUrl(String callbackUrlEncode, MchAppConfigContext mchAppConfigContext) {
        //云闪付返回地址
        String ysfRedirectUrl = String.format("https://qr.95516.com/qrcGtwWeb-web/api/userAuth?version=1.0.0&redirectUrl=%s", callbackUrlEncode);
        log.info("ysRedirectUrl={}", ysfRedirectUrl);
        return ChannelUserInfoMsg.gen(ysfRedirectUrl, null);
    }

    @Override
    public String getChannelUserId(String pageType, JSONObject reqParams, MchAppConfigContext mchAppConfigContext, String ifCode) {
        String logPrefix = "【获取银联行业码用户ID】";
        try {
            String userAuthCode = reqParams.getString("userAuthCode");
            String appUpIdentifier = reqParams.getString("appUpIdentifier");
            log.info("{} userAuthCode={}, appUpIdentifier={}", logPrefix, userAuthCode, appUpIdentifier);
            JSONObject bizContent = new JSONObject();
            // 用户授权码
            bizContent.put("userAuthCode", userAuthCode);
            // 银联支付标识
            bizContent.put("paymentApp", appUpIdentifier);
            SxfpayIsvParams isvParams = (SxfpayIsvParams) configContextQueryService.queryIsvParams(mchAppConfigContext.getMchApplyment().getIsvNo(),getIfCode());
            JSONObject respBizData = SxfpayKit.reqApi(ReqMethod.Method.OTHER_GET_UNION_USERID, isvParams, bizContent);
            return respBizData.getString("data");
        } catch (Exception e) {
            log.error("{}异常", logPrefix, e);
            return null;
        }
    }

}
