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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.interfaces.paychannel.IPayOrderCloseService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.thirdparty.channel.yspay.utils.YspayKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 关闭订单接口实现类
 *
 * @author xiaoyu
 *
 * @date 2022/5/16 9:09
 */
@Slf4j
@Service
public class YspayPayOrderCloseService implements IPayOrderCloseService {

    @Override
    public ChannelRetMsg close(PayOrder payOrder, MchAppConfigContext mchAppConfigContext){
        try {
            JSONObject bizContent = new JSONObject();

            // 商户订单号
            bizContent.put("out_trade_no", payOrder.getPayOrderId());
            // 订单交易日期
            bizContent.put("shopdate", DateUtil.format(payOrder.getCreatedAt(), DatePattern.PURE_DATE_PATTERN));

            String result = YspayKit.payRequest("ysepay.online.trade.close", mchAppConfigContext, bizContent, null, payOrder.getIfCode());
            JSONObject resJson = JSONObject.parseObject(result);
            JSONObject response = resJson.getJSONObject("ysepay_online_trade_close_response");
            String code = response.getString("code");
            if (YspayKit.RES_CODE.equals(code)) {
                String transNo = response.getString("trade_no");
                return ChannelRetMsg.confirmSuccess(transNo);
            }
            return ChannelRetMsg.waiting();
        }catch (Exception e) {
            return ChannelRetMsg.sysError(e.getMessage());
        }

    }

}
