package com.jeequan.jeepay.thirdparty.channel.wxpay.paywayV3;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.v3.util.PemUtils;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.wxpay.WxpayIsvsubMchParams;
import com.jeequan.jeepay.core.model.rqrs.AbstractRS;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.WxJsapiOrderRS;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.WxLiteOrderRQ;
import com.jeequan.jeepay.thirdparty.channel.wxpay.WxpayPaymentService;
import com.jeequan.jeepay.thirdparty.channel.wxpay.kits.WxpayKit;
import com.jeequan.jeepay.thirdparty.channel.wxpay.kits.WxpayV3Util;
import com.jeequan.jeepay.thirdparty.channel.wxpay.model.WxpayV3OrderRequestModel;
import com.jeequan.jeepay.thirdparty.model.WxServiceWrapper;
import com.jeequan.jeepay.thirdparty.util.ApiResBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
 * 微信 小程序
 *
 * @author zhuxiao
 *
 * @date 2021/6/8 18:08
 */
@Slf4j
@Service("wxpayPaymentByLiteV3Service") //Service Name需保持全局唯一性
public class WxLite extends WxpayPaymentService {

    @Override
    public String preCheck(UnifiedOrderRQ rq, PayOrder payOrder) {
        // 使用的是V2接口的预先校验
        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception{

        WxLiteOrderRQ bizRQ = (WxLiteOrderRQ) rq;

        // 获取微信service (V2可直接使用)
        WxServiceWrapper wxServiceWrapper = configContextQueryService.getWxServiceWrapper(mchAppConfigContext);
        WxPayService wxPayService = wxServiceWrapper.getWxPayService();


        // 构造请求数据 ( 通用 )
        WxpayV3OrderRequestModel wxpayV3OrderRequestModel = buildV3OrderRequestModel(payOrder, mchAppConfigContext);

        // 特约商户
        if(mchAppConfigContext.isIsvsubMch()) {

            // 注意： 服务商模式调用小程序支付： 无法获取到openId参数， 只能是subOpenId参数的传入

            // 明确使用的 subMchLiteAppId 获取到的openId
            if(bizRQ.getIsSubOpenId() != null && bizRQ.getIsSubOpenId() == CS.YES){

                WxpayIsvsubMchParams isvsubMchParams = (WxpayIsvsubMchParams) configContextQueryService.queryIsvsubMchParams(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), getIfCode());

                wxpayV3OrderRequestModel.setSubAppid(isvsubMchParams.getSubMchLiteAppId());
                wxpayV3OrderRequestModel.setPayer(new WxpayV3OrderRequestModel.Payer().setSubOpenid(bizRQ.getOpenid()));


            }else if(StringUtils.isNotEmpty(bizRQ.getSubAppid())){ // 使用参数传递的appID

                wxpayV3OrderRequestModel.setSubAppid(bizRQ.getSubAppid());
                wxpayV3OrderRequestModel.setPayer(new WxpayV3OrderRequestModel.Payer().setSubOpenid(bizRQ.getOpenid()));

            }else{ // 使用的服务商配置的小程序appId获取

                wxpayV3OrderRequestModel.setSubAppid(wxServiceWrapper.getWxMaService().getWxMaConfig().getAppid());
                wxpayV3OrderRequestModel.setPayer(new WxpayV3OrderRequestModel.Payer().setSubOpenid(bizRQ.getOpenid()));

            }

        }else{ // 普通商户

            // 如果配置了小程序的appId, 那么需要传入到这里
            if(wxServiceWrapper.getWxMaService() != null && wxServiceWrapper.getWxMaService().getWxMaConfig() != null && StringUtils.isNotBlank(wxServiceWrapper.getWxMaService().getWxMaConfig().getAppid())){
                wxpayV3OrderRequestModel.setNormalAppid(wxServiceWrapper.getWxMaService().getWxMaConfig().getAppid());
            }else{

                // 没有配置小程序的appId， 那么默认使用的 支付配置的appId
            }
            //openId
            wxpayV3OrderRequestModel.setPayer(new WxpayV3OrderRequestModel.Payer().setNormalOpenId(bizRQ.getOpenid()));
        }


        // 构造函数响应数据
        WxJsapiOrderRS res = ApiResBuilder.buildSuccess(WxJsapiOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        res.setChannelRetMsg(channelRetMsg);


        // 调起上游接口：
        try {

            // 调起接口  modify 20220425 by terrfly : 改为统一调用的方式， 将返回数据包放置在业务层进行处理 。
            String payInfo = WxpayV3Util.commonReqWx(wxpayV3OrderRequestModel, wxPayService, mchAppConfigContext.isIsvsubMch(), WxPayConstants.TradeType.JSAPI,
                    (JSONObject wxRes) -> {

                        // 普通商户
                        String resultAppId = wxpayV3OrderRequestModel.getNormalAppid();

                        // 特约商户
                        if(mchAppConfigContext.isIsvsubMch()){
                            resultAppId = StringUtils.defaultIfEmpty(wxpayV3OrderRequestModel.getSubAppid(), wxpayV3OrderRequestModel.getSpAppid());
                        }

                        // 使用wxjava公共函数，生成
                        WxPayUnifiedOrderV3Result wxPayUnifiedOrderV3Result = new WxPayUnifiedOrderV3Result();
                        wxPayUnifiedOrderV3Result.setPrepayId(wxRes.getString("prepay_id"));
                        try {

                            FileInputStream fis = new FileInputStream(wxPayService.getConfig().getPrivateKeyPath());

                            WxPayUnifiedOrderV3Result.JsapiResult jsapiResult =
                                    wxPayUnifiedOrderV3Result.getPayInfo(TradeTypeEnum.JSAPI, resultAppId, null,
                                            PemUtils.loadPrivateKey(fis));

                            JSONObject jsonRes = (JSONObject)JSON.toJSON(jsapiResult);
                            jsonRes.put("package", jsonRes.getString("packageValue"));
                            jsonRes.remove("packageValue");

                            try {
                                fis.close();
                            } catch (IOException e) {
                            }

                            return JSON.toJSONString(jsonRes);

                        } catch (FileNotFoundException e) {
                            return null;

                        }
                    }
            );

            // 返回包装数据
            res.setPayInfo(payInfo);

        } catch (WxPayException e) {
            //明确失败
            channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            WxpayKit.commonSetErrInfo(channelRetMsg, e);
            return res;
        }

        // 支付中
        channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
        return res;
    }

}
