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.JSON;
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.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.UpQrOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.UpQrOrderRS;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.thirdparty.channel.yspay.YspayPaymentService;
import com.jeequan.jeepay.thirdparty.channel.yspay.utils.YspayKit;
import com.jeequan.jeepay.thirdparty.util.ApiResBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 银联扫码支付
 *
 * @author zx
 *
 * @date 2022/06/22 20:09
 */
@Service("yspayPaymentByUpQrService") //Service Name需保持全局唯一性
@Slf4j
public class UpQr extends YspayPaymentService {

    @Override
    public String preCheck(UnifiedOrderRQ rq, PayOrder payOrder) {
        return null;
    }

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

        UpQrOrderRQ bizRQ = (UpQrOrderRQ)rq;

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

        try {
            JSONObject bizContent = new JSONObject();
            // 默认支付参数
            YspayKit.setPayParams(mchAppConfigContext, bizContent, "1", 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()));
            // 二维码行别 微信-1902000 ，支付宝-1903000，中国银联-9001002，招商银行:-3085840
            bizContent.put("bank_type", "9001002");
            // 交易结束时间
            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.qrcodepay", mchAppConfigContext, bizContent, getNotifyUrl(), payOrder.getIfCode());
            JSONObject resJson = JSONObject.parseObject(result);
            JSONObject response = resJson.getJSONObject("ysepay_online_qrcodepay_response");
            String code = response.getString("code");
            channelRetMsg.setChannelBizData(response);
            if (YspayKit.RES_CODE.equals(code)) {
                // 分账登记接口调用
                payOrderDivision(mchAppConfigContext, payOrder);

                String tradeStatus = response.getString("trade_status");
                if(YspayKit.WAIT_BUYER_PAY.equals(tradeStatus)){ // 交易中

                    String transNo = response.getString("trade_no");
                    String qrCdLink = response.getString("source_qr_code_url");
                    channelRetMsg.setChannelOrderId(transNo);
                    ChannelJsapiMsg jsapiMsg = new ChannelJsapiMsg();
                    if(CS.PAY_DATA_TYPE.CODE_IMG_URL.equals(bizRQ.getPayDataType())){ //二维码地址
                        res.setCodeImgUrl(sysConfigService.getDBApplicationConfig().genScanImgUrl(qrCdLink));
                        jsapiMsg.setQrCodeUrl(sysConfigService.getDBApplicationConfig().genScanImgUrl(qrCdLink));
                    }else{ //默认都为跳转地址方式
                        res.setCodeUrl(qrCdLink);
                        jsapiMsg.setQrCodeUrl(qrCdLink);
                    }
                    res.setPayData(JSON.toJSONString(jsapiMsg));
                }else if (YspayKit.TRADE_FAILED.equals(tradeStatus)){  // 失败
                    channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                    channelRetMsg.setChannelErrCode(response.getString("code"));
                    channelRetMsg.setChannelErrMsg(response.getString("sub_msg"));
                    return res;
                }
            }else {
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                channelRetMsg.setChannelErrCode(response.getString("code"));
                channelRetMsg.setChannelErrMsg(response.getString("sub_msg"));
                return res;
            }

            channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
            return res;
        } catch (ChannelException e) {
            channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            channelRetMsg.setChannelErrCode(e.getChannelRetMsg().getChannelErrCode());
            channelRetMsg.setChannelErrMsg(e.getChannelRetMsg().getChannelErrMsg());
            return res;
        } catch (Exception e) {
            channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            channelRetMsg.setChannelErrMsg("系统异常");
            return res;
        }
    }

}
