package ink.wgink.module.wechat.request.pay.v3.order;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.exceptions.base.SystemException;
import ink.wgink.module.wechat.pojo.pay.v3.PayErrorResponse;
import ink.wgink.module.wechat.pojo.pay.v3.order.OrderClose;
import ink.wgink.module.wechat.request.pay.v3.AbstractPayRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;

/**
 * @ClassName: OrderClosePayRequest
 * @Description: 订单关闭
 * @Author: wanggeng
 * @Date: 2021/8/30 5:19 下午
 * @Version: 1.0
 */
public class OrderClosePayRequestImpl extends AbstractPayRequest<OrderClose, JSONObject, String> {

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

    @Override
    public String response(ResponseEntity<String> responseEntity) {
        if (responseEntity.getStatusCodeValue() == HttpStatus.NO_CONTENT.value()) {
            return "";
        } else if (responseEntity.getStatusCodeValue() == HttpStatus.ACCEPTED.value()) {
            throw new SystemException("用户支付中，订单无法关闭，请等待5秒后查看支付结果");
        }
        return null;
    }

    @Override
    public void error(HttpClientErrorException e) {
        LOG.debug("Response error status code：{}", e.getStatusCode());
        PayErrorResponse payErrorResponse = JSONObject.parseObject(e.getResponseBodyAsString(), PayErrorResponse.class);
        LOG.debug("Response error detail: {}", payErrorResponse.getDetail());
        throw new SystemException(payErrorResponse.getMessage());
    }
}
