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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.exception.BizException;
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.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;

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

    @Override
    public String preCheck(UnifiedOrderRQ rq, PayOrder payOrder) {

        WxLiteOrderRQ bizRQ = (WxLiteOrderRQ) rq;
        if(StringUtils.isEmpty(bizRQ.getOpenid())){
            throw new BizException("[openid]不可为空");
        }
        return null;
    }

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

        WxLiteOrderRQ bizRQ = (WxLiteOrderRQ) rq;

        WxPayUnifiedOrderRequest req = buildUnifiedOrderRequest(payOrder, mchAppConfigContext);
        req.setTradeType(WxPayConstants.TradeType.JSAPI);

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

        // 调起上游接口：
        // 1. 如果抛异常，则订单状态为： 生成状态，此时没有查单处理操作。 订单将超时关闭
        // 2. 接口调用成功， 后续异常需进行捕捉， 如果 逻辑代码出现异常则需要走完正常流程，此时订单状态为： 支付中， 需要查单处理。
        WxServiceWrapper wxServiceWrapper = configContextQueryService.getWxServiceWrapper(mchAppConfigContext);
        WxPayService wxPayService = wxServiceWrapper.getWxPayService();

        // 特约商户
        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());
                req.setSubAppId(isvsubMchParams.getSubMchLiteAppId());
                req.setSubOpenid(bizRQ.getOpenid());

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

                req.setSubAppId(bizRQ.getSubAppid());
                req.setSubOpenid(bizRQ.getOpenid());

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

                req.setSubAppId(wxServiceWrapper.getWxMaService().getWxMaConfig().getAppid());
                req.setSubOpenid(bizRQ.getOpenid());
            }

        }else{ // 普通商户

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

                // 没有配置小程序的appId， 那么默认使用的 支付配置的appId
            }

            //openId
            req.setOpenid(bizRQ.getOpenid());
        }

        try {
            WxPayMpOrderResult payResult = wxPayService.createOrder(req);
            JSONObject resJSON = (JSONObject) JSON.toJSON(payResult);
            resJSON.put("package", payResult.getPackageValue());

            res.setPayInfo(resJSON.toJSONString());

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

        } catch (WxPayException e) {
            channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            WxpayKit.commonSetErrInfo(channelRetMsg, e);
        }

        return res;
    }

}
