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.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.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/6/13 17:20
 */
@Service("yspayPaymentByAliJsapiService") //Service Name需保持全局唯一性
public class AliJsapi extends YspayPaymentService {

    @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 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("buyer_id", bizRQ.getBuyerUserId());
            // 交易结束时间
            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.alijsapi.pay", mchAppConfigContext, bizContent, getNotifyUrl(), payOrder.getIfCode());
            JSONObject resJson = JSONObject.parseObject(result);
            JSONObject response = resJson.getJSONObject("ysepay_online_alijsapi_pay_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");
                    JSONObject payInfo = response.getJSONObject("jsapi_pay_info");
                    String tradeNo = payInfo.getString("tradeNO");
                    //付款信息
                    channelRetMsg.setChannelOrderId(channelOrderNo);
                    // 获取payInfo
                    res.setAlipayTradeNo(tradeNo);
                    res.setPayData(JSONObject.toJSONString(new ChannelJsapiMsg(tradeNo)));
                    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;
    }

}
