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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
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.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.YsfBarOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.YsfBarOrderRS;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.thirdparty.channel.yspay.YspayPaymentService;
import com.jeequan.jeepay.thirdparty.channel.yspay.model.YsCardType;
import com.jeequan.jeepay.thirdparty.channel.yspay.utils.YspayKit;
import com.jeequan.jeepay.thirdparty.util.ApiResBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 云闪付条码支付
 *
 * @author xiaoyu
 *
 * @date 2022/10/13 9:17
 */
@Service("yspayPaymentByYsfBarService") //Service Name需保持全局唯一性
public class YsfBar extends YspayPaymentService {

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

        YsfBarOrderRQ bizRQ = (YsfBarOrderRQ) rq;
        if(StringUtils.isEmpty(bizRQ.getAuthCode())){
            throw new BizException("用户支付条码[authCode]不可为空");
        }

        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        String logPrefix = "【云闪付条码(unionpay)支付】";

        YsfBarOrderRQ bizRQ = (YsfBarOrderRQ) rq;
        YsfBarOrderRS res = ApiResBuilder.buildSuccess(YsfBarOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        res.setChannelRetMsg(channelRetMsg);

        JSONObject bizContent = new JSONObject();
        // 默认支付参数
        YspayKit.setPayParams(mchAppConfigContext, bizContent, "2", payOrder.getIfCode());

        // 商户订单号
        bizContent.put("out_trade_no", payOrder.getPayOrderId());
        // 订单交易日期
        bizContent.put("shopdate", DateUtil.format(payOrder.getCreatedAt(), DatePattern.PURE_DATE_PATTERN));
        // 订单备注
        bizContent.put("subject", payOrder.getSubject());
        // 金额 元
        bizContent.put("total_amount", AmountUtil.convertCent2Dollar(payOrder.getFindAmt()));
        // 支付授权码
        bizContent.put("auth_code", bizRQ.getAuthCode());
        // 二维码行别 微信-1902000 ，支付宝-1903000，中国银联-9001002，招商银行:-3085840
        bizContent.put("bank_type", "9001002");

        // 渠道终端号 20220429 添加
        String channelTrmNo = queryStoreTerminalChannelTrmNo(rq.getMchTrmNo(), payOrder);
        if(StringUtils.isNotEmpty(channelTrmNo)){
            bizContent.put("device_info", channelTrmNo);               // 终端设备编号
        }
        // 支付场景
        bizContent.put("scene", "bar_code");
        // 交易结束时间
        String expiredTime = DateUtil.formatBetween(DateUtil.between(payOrder.getCreatedAt(), payOrder.getExpiredTime(), DateUnit.MINUTE)).replace("毫秒", "");
        bizContent.put("timeout_express", expiredTime+"m");

        String result = YspayKit.payRequest("ysepay.online.barcodepay", mchAppConfigContext, bizContent, getNotifyUrl(), payOrder.getIfCode());
        JSONObject resJson = JSONObject.parseObject(result);
        JSONObject response = resJson.getJSONObject("ysepay_online_barcodepay_response");
        String code = response.getString("code");
        if (YspayKit.RES_CODE.equals(code)) {
            // 分账登记接口调用
            payOrderDivision(mchAppConfigContext, payOrder);

            String tradeStatus = response.getString("trade_status");
            if(YspayKit.TRADE_SUCCESS.equals(tradeStatus)){ // 支付成功

                String transNo = response.getString("trade_no");
                channelRetMsg.setChannelOrderId(transNo);
                // 支付中
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                // 开启轮询查单
                channelRetMsg.setNeedQuery(true);
                // 卡类型
                String cardType = response.getString("card_type");
                YsCardType val = YsCardType.getVal(cardType);
                String drType = CS.DrType.OTHER.getType();
                if(val != null){
                    switch (val){
                        case CREDIT:
                            drType = CS.DrType.CREDIT.getType();
                            break;
                        case DEBIT:
                            drType = CS.DrType.DEBIT.getType();
                            break;
                    }
                }
                channelRetMsg.setDrType(drType);
            }else if (YspayKit.TRADE_FAILED.equals(tradeStatus)){  // 失败
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                channelRetMsg.setChannelErrCode(response.getString("code"));
                channelRetMsg.setChannelErrMsg(response.getString("sub_msg"));
            }else {  //其他状态, 表示支付中
                String transNo = response.getString("trade_no");
                channelRetMsg.setChannelOrderId(transNo);
                // 开启轮询查单
                channelRetMsg.setNeedQuery(true);
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
            }
        }else {
            channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            channelRetMsg.setChannelErrCode(response.getString("code"));
            channelRetMsg.setChannelErrMsg(response.getString("sub_msg"));
        }
        return res;
    }

}
