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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.exception.ChannelException;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.rqrs.AbstractRS;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelJsapiMsg;
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.AliJsapiOrderRS;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.AliLiteOrderRQ;
import com.jeequan.jeepay.thirdparty.channel.dgpay.DgPayKit;
import com.jeequan.jeepay.thirdparty.channel.dgpay.DgpayPaymentService;
import com.jeequan.jeepay.thirdparty.util.ApiResBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 支付宝小程序
 *
 * @author xiaoyu
 *
 * @date 2023/1/6 16:53
 */
@Slf4j
@Service("dgpayPaymentByAliLiteService") //Service Name需保持全局唯一性
public class AliLite extends DgpayPaymentService {

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

        AliLiteOrderRQ bizRQ = (AliLiteOrderRQ) rq;
        if (StringUtils.isEmpty(bizRQ.getBuyerUserId())) {
            throw new BizException("[buyerUserId]不可为空");
        }

        return null;
    }

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

        AliLiteOrderRQ bizRQ = (AliLiteOrderRQ) rq;
        // 构造函数响应数据
        AliJsapiOrderRS res = ApiResBuilder.buildSuccess(AliJsapiOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        res.setChannelRetMsg(channelRetMsg);
        try {
            JSONObject dataParams = DgPayKit.dataParams(payOrder, getNotifyUrl());
            dataParams.put("trade_type", "A_JSAPI");

            JSONObject aliJson = new JSONObject();
            aliJson.put("buyer_id", bizRQ.getBuyerUserId());
            dataParams.put("alipay_data", aliJson.toJSONString());

            // 设置订单是否需要分账
            if(isDivisionOrder(payOrder)) {
                dataParams.put("delay_acct_flag", "Y");
            }
            JSONObject response = DgPayKit.payRequest(mchAppConfigContext, dataParams, "/trade/payment/jspay", payOrder.getIfCode());
            JSONObject resData = response.getJSONObject("data");
            String code = resData.getString("resp_code");
            channelRetMsg.setChannelBizData(resData);
            if(DgPayKit.STATE_ING.equals(code)){
                String channelOrderNo = resData.get("hf_seq_id").toString();
                //付款信息
                JSONObject aliResJson = resData.getJSONObject("pay_info");
                String tradeNo = aliResJson.getString("tradeNO");
                res.setAlipayTradeNo(tradeNo);
                res.setPayData(JSON.toJSONString(new ChannelJsapiMsg(tradeNo)));
                // 支付中
                channelRetMsg.setChannelOrderId(channelOrderNo);
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                // 开启轮询查单
                channelRetMsg.setNeedQuery(true);
            }else {
                DgPayKit.channelMsgError(resData, channelRetMsg);
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            }

        }catch (Exception e) {
            log.error(e.getMessage());
            throw ChannelException.sysError(e.getMessage());
        }
        return res;
    }

}
