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.AliJsapiOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.AliJsapiOrderRS;
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;

/**
 * 斗拱 支付宝 jsapi
 *
 * @author xiaoyu
 *
 * @date 2022/6/13 17:20
 */
@Slf4j
@Service("dgpayPaymentByAliJsapiService") //Service Name需保持全局唯一性
public class AliJsapi extends DgpayPaymentService {

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

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

        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext){
        AliJsapiOrderRS res = ApiResBuilder.buildSuccess(AliJsapiOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        res.setChannelRetMsg(channelRetMsg);
        try {
            AliJsapiOrderRQ bizRQ = (AliJsapiOrderRQ) rq;
            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");
            channelRetMsg.setChannelBizData(resData);
            String code = resData.getString("resp_code");
            if(DgPayKit.STATE_ING.equals(code)){
                String channelOrderNo = resData.get("hf_seq_id").toString();
                //付款信息
                JSONObject aliResJson = resData.getJSONObject("pay_info");
                channelRetMsg.setChannelOrderId(channelOrderNo);
                // 获取payInfo
                String tradeNo = aliResJson.getString("tradeNO");
                res.setAlipayTradeNo(tradeNo);
                res.setPayData(JSON.toJSONString(new ChannelJsapiMsg(tradeNo)));
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
            }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;
    }

}
