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

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.interfaces.paychannel.IChannelUserService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.lklspay.LklspayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelUserInfoMsg;
import com.jeequan.jeepay.thirdparty.channel.lklspay.model.LklPayMethod;
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 LklspayChannelUserService implements IChannelUserService {

    @Autowired
    protected ConfigContextQueryService configContextQueryService;

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

    @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");
            log.info("{} userAuthCode={}, appUpIdentifier={}", logPrefix, userAuthCode, appUpIdentifier);
            JSONObject bizContent = new JSONObject();
            // 用户授权码
            bizContent.put("authCode", userAuthCode);
            // 银联支付标识
            bizContent.put("appUpIdentifier", appUpIdentifier);

            MchApplyment mchApplyment = mchAppConfigContext.getMchApplyment();
            LklspayIsvParams isvParams = (LklspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);

            JSONObject respBizData = LklspayKit.reqMch(LklPayMethod.Api.USERID_QUERY, isvParams, bizContent);
            return respBizData.getString("userId");
        } catch (Exception e) {
            log.error("{}异常", logPrefix, e);
            return null;
        }
    }

}
