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

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IChannelUserService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.ruipay.RyxpayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelUserInfoMsg;
import com.jeequan.jeepay.thirdparty.channel.ryxpay.model.PayRespEntity;
import com.jeequan.jeepay.thirdparty.channel.ryxpay.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 RyxpayChannelUserService implements IChannelUserService {

    @Autowired protected ConfigContextQueryService configContextQueryService;

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

    @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("redirectUrl={}", 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");
            JSONObject bizContent = new JSONObject();
            bizContent.put("merchantCode",mchAppConfigContext.getMchApplyment().getChannelMchNo());
            bizContent.put("payWay","UPZF");
            // 用户授权码
            bizContent.put("userAuthCode", userAuthCode);
            // 银联支付标识
            bizContent.put("appUpIdentifier", appUpIdentifier);
            RyxpayIsvParams isvParams = (RyxpayIsvParams) configContextQueryService.queryIsvParams(mchAppConfigContext.getMchApplyment().getIsvNo(),getIfCode());
            PayRespEntity response = RyxpayKit.payReqApi(ReqMethod.ServiceCode.SMZF019, isvParams, bizContent, null, null);
            String respType = response.getRespType();
            if(!RyxpayKit.RESP_BIZ_SUCCESS.equals(respType)){
                throw new BizException(response.getRespMsg());
            }
            return response.getData().getString("userId");
        } catch (Exception e) {
            log.error("{}异常", logPrefix, e);
            return null;
        }
    }
}
