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.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.YsfJsapiOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.YsfJsapiOrderRS;
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 org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 银联jsapi
 *
 * @author xiaoyu
 *
 * @date 2022/10/13 9:17
 */
@Service("yspayPaymentByYsfJsapiService") //Service Name需保持全局唯一性
public class YsfJsapi extends YspayPaymentService {

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

        YsfJsapiOrderRQ bizRQ = (YsfJsapiOrderRQ) rq;
        if(StringUtils.isEmpty(bizRQ.getUserId())){
            throw new BizException("[userId]不可为空");
        }
        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        YsfJsapiOrderRS res = ApiResBuilder.buildSuccess(YsfJsapiOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        res.setChannelRetMsg(channelRetMsg);
        YsfJsapiOrderRQ bizRQ = (YsfJsapiOrderRQ) rq;
        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()));
            // 买家支付宝用户ID
            bizContent.put("userId", bizRQ.getUserId());
            // 是否允许多次支付,Y：允许;N：不允许
            bizContent.put("allow_repeat_pay", "Y");
            // 行别 9001002 银联
            bizContent.put("bank_type", "9001002");
            // IP地址
            bizContent.put("spbill_create_ip", payOrder.getClientIp());
            // 交易结束时间
            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.cupmulapp.qrcodepay", mchAppConfigContext, bizContent, getNotifyUrl(), payOrder.getIfCode());
            JSONObject resJson = JSONObject.parseObject(result);
            JSONObject response = resJson.getJSONObject("ysepay_online_cupmulapp_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 channelOrderNo = response.getString("trade_no");
                    String url = response.getString("web_url");
                    // 付款信息
                    channelRetMsg.setChannelOrderId(channelOrderNo);
                    // 获取payInfo
                    ChannelJsapiMsg jsapiMsg = new ChannelJsapiMsg();
                    jsapiMsg.setRedirectUrl(url);
                    res.setRedirectUrl(url);
                    res.setPayData(JSON.toJSONString(jsapiMsg));
                    channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                }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 {
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                channelRetMsg.setChannelErrCode(response.getString("code"));
                channelRetMsg.setChannelErrMsg(response.getString("sub_msg"));
            }
        }catch (Exception e) {
            throw ChannelException.sysError(e.getMessage());
        }
        return res;
    }

}
