package com.njyunzhi.pet_identity.common;

import com.github.binarywang.wxpay.bean.request.WxPayRefundV3Request;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayRefundV3Result;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.njyunzhi.pet_identity.config.WeixinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Component
public class WxPayUtils {
    @Autowired
    WeixinConfig config;

    @Autowired
    WxUtils wxUtils;

    @Value("${yz.default.servBase}")
    String servBase;

    /**
     * 下单
     * @param request
     * @return
     * @throws Exception
     */
    public WxPayUnifiedOrderV3Result.JsapiResult createOrder(WxPayUnifiedOrderV3Request request) throws WxPayException {
        // 北京时间
        LocalDateTime now = LocalDateTime.now(ZoneOffset.ofHours(8));
        WxPayService payService = wxUtils.getPayService();

        request.setNotifyUrl(servBase + "/wxpay/notify/order");

        WxPayUnifiedOrderV3Result wxPayUnifiedOrderV3Result = payService.unifiedOrderV3(TradeTypeEnum.JSAPI, request);
        return wxPayUnifiedOrderV3Result.getPayInfo(TradeTypeEnum.JSAPI, request.getAppid(), request.getMchid(), payService.getConfig().getPrivateKey());
    }

    /**
     * 订单退款
     * @param request
     * @return
     * @throws Exception
     */
    public WxPayRefundV3Result refund(WxPayRefundV3Request request) throws Exception {
        WxPayService payService = wxUtils.getPayService();

        request.setNotifyUrl(servBase + "/wxpay/notify/refund");
        WxPayRefundV3Result result = payService.refundV3(request);

        if ("ABNORMAL".equals(result.getStatus())) {
            throw new Exception("退款异常");
        }
        if ("CLOSED".equals(result.getStatus())) {
            throw new Exception("退款关闭");
        }

        return result;
    }

}
