package ink.wgink.module.wechat.pay.service.v3.order.impl;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.exceptions.ParamsException;
import ink.wgink.module.wechat.pay.enums.PayAuthorizationTypeEnum;
import ink.wgink.module.wechat.pay.pojo.v3.order.OrderClose;
import ink.wgink.module.wechat.pay.remote.v3.IOrderPayRemoteService;
import ink.wgink.module.wechat.pay.service.BasePayService;
import ink.wgink.module.wechat.pay.service.v3.order.IOrderCloseService;
import ink.wgink.properties.wechat.pay.v3.PayProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @ClassName: OrderCloseServiceImpl
 * @Description: 订单关闭
 * @Author: wanggeng
 * @Date: 2021/8/30 5:30 下午
 * @Version: 1.0
 */
@Service
public class OrderCloseServiceImpl extends BasePayService implements IOrderCloseService {

    @Autowired
    private PayProperties payProperties;
    @Autowired
    private IOrderPayRemoteService orderPayRemoteService;

    @Override
    public void closeOrder(String businessOrderId) throws Exception {
        if (StringUtils.isBlank(businessOrderId)) {
            throw new ParamsException("订单不能为空");
        }
        OrderClose orderClose = new OrderClose();
        orderClose.setMchid(payProperties.getMchid());

        String urlSuffix = "/v3/pay/transactions/out-trade-no/" + businessOrderId + "/close";
        String serialNumber = getSerialNumber();
        JSONObject body = bodyJson(orderClose);
        String authorization = getAuthorization(RequestMethod.POST, urlSuffix, serialNumber, payProperties, body.toString(), PayAuthorizationTypeEnum.WECHATPAY2_SHA256_RSA2048);
        orderPayRemoteService.closePlaceOrder(getPayBaseUrl(), businessOrderId, authorization, serialNumber, body);
    }

    private JSONObject bodyJson(OrderClose orderClose) {
        JSONObject bodyJsonObject = new JSONObject();
        bodyJsonObject.put("mchid", orderClose.getMchid());
        return bodyJsonObject;
    }

}
