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

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.ChannelRetMsg;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.AutoPosOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.AutoPosOrderRS;
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;

/**
* 斗拱 智能POS
*
* @author zx
*
* @date 2022/8/2 18:11
*/
@Slf4j
@Service("dgpayPaymentByAutoPosService") //Service Name需保持全局唯一性
public class AutoPos extends DgpayPaymentService {

    @Override
    public String preCheck(UnifiedOrderRQ rq, PayOrder payOrder) {
        if(StringUtils.isEmpty(payOrder.getDeviceNo())){
            throw new BizException("智能POS[deviceNo]不可为空");
        }
        return null;
    }

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

        String logPrefix = "【斗拱 智能POS支付】";
        AutoPosOrderRS res = ApiResBuilder.buildSuccess(AutoPosOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        res.setChannelRetMsg(channelRetMsg);

        AutoPosOrderRQ bizRQ = (AutoPosOrderRQ) rq;

        try {

            // 请求数据data
            JSONObject dataParams = new JSONObject();
            dataParams.put("device_id", payOrder.getDeviceNo());

            // 交易信息
            JSONObject tradeJSON = new JSONObject();
            tradeJSON.put("interfaceType", "payment");
            tradeJSON.put("channelId", DgPayKit.covertChannelId(bizRQ.getChannelType()));
            tradeJSON.put("mobilePayType", DgPayKit.covertMobilePayType(bizRQ.getPayType()));
            tradeJSON.put("ordAmt", payOrder.getFindAmt().toString());
            tradeJSON.put("outOrdId", payOrder.getPayOrderId());
            tradeJSON.put("goodsDesc", payOrder.getBody());
            tradeJSON.put("bgRetUrl", "virgo://" + getPosNotifyUrl());
            tradeJSON.put("ordRemark", payOrder.getSellerRemark());

            // 设置订单是否需要分账
            if(isDivisionOrder(payOrder)) {
                tradeJSON.put("isDelayAcct", isDivisionOrder(payOrder) ? "1" : "0");
            }

            dataParams.put("json_data", tradeJSON.toJSONString());

            JSONObject response = DgPayKit.request(mchAppConfigContext, dataParams, "/trade/cloudmis/device/information", payOrder.getIfCode());
            JSONObject resData = response.getJSONObject("data");
            channelRetMsg.setChannelBizData(resData);
            String code = resData.getString("resp_code");
            if(!DgPayKit.STATE_SUCCESS.equals(code)){
                log.error("{}推送订单失败，错误码：{}，错误信息：{}", logPrefix, code, resData.getString("resp_desc"));
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                channelRetMsg.setChannelErrCode(resData.getString("result_code"));
                channelRetMsg.setChannelErrMsg(resData.getString("result_msg"));
                return res;
            }

            channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING); // 调用成功，改为支付中

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

}
