package com.njzscloud.supervisory.wxPay.service.impl;

import com.alibaba.fastjson2.JSON;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.njzscloud.supervisory.wxPay.config.WxPayProperties;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.njzscloud.supervisory.wxPay.service.WeChatPayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 微信支付服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WeChatPayServiceImpl implements WeChatPayService {

    private final WxPayService wxPayService;
    private final WxPayProperties wxPayProperties;

    @Override
    public Object createJsapiOrder(WxPayUnifiedOrderRequest request) throws WxPayException {
        log.info("开始创建微信支付JSAPI订单，入参为：{}", JSON.toJSONString(request));

        // 调用微信支付SDK创建订单
        Object result = wxPayService.createOrder(request);

        if (result == null) {
            throw new WxPayException("微信支付订单创建失败，返回结果为空");
        }
        return result;
    }

    /**
     * 查询订单状态
     *
     * @param outTradeNo 商户订单号
     * @return 订单查询结果
     * @throws WxPayException 微信支付异常
     */
    @Override
    public WxPayOrderQueryResult queryOrder(String outTradeNo) throws WxPayException {
        try {
            log.info("开始查询微信支付订单，商户订单号：{}", outTradeNo);
            return wxPayService.queryOrder(null, outTradeNo);
        } catch (WxPayException e) {
            log.error("查询微信支付订单失败，商户订单号：{}，错误信息：{}", outTradeNo, e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 关闭订单
     *
     * @param outTradeNo 商户订单号
     * @throws WxPayException 微信支付异常
     */
    @Override
    public void closeOrder(String outTradeNo) throws WxPayException {
        try {
            log.info("开始关闭微信支付订单，商户订单号：{}", outTradeNo);
            wxPayService.closeOrder(outTradeNo);
            log.info("微信支付订单关闭成功，商户订单号：{}", outTradeNo);
        } catch (WxPayException e) {
            log.error("关闭微信支付订单失败，商户订单号：{}，错误信息：{}", outTradeNo, e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 申请退款
     *
     * @param outTradeNo  商户订单号
     * @param outRefundNo 商户退款单号
     * @param totalFee    订单总金额（分）
     * @param refundFee   退款金额（分）
     * @param notifyUrl   退款描述
     * @return 退款结果
     * @throws WxPayException 微信支付异常
     */
    @Override
    public String refund(String outTradeNo, String outRefundNo, int totalFee, int refundFee, String notifyUrl) throws WxPayException {
        try {
            log.info("开始申请微信支付退款，商户订单号：{}，退款单号：{}，退款金额：{}，退款回调地址：{}", outTradeNo,
                    outRefundNo, refundFee, notifyUrl);

            WxPayRefundRequest refundRequest = WxPayRefundRequest.newBuilder()
                    .outTradeNo(outTradeNo)
                    .outRefundNo(outRefundNo)
                    .totalFee(totalFee)
                    .refundFee(refundFee)
                    .notifyUrl(notifyUrl)
                    .build();

            refundRequest.setSubMchId(wxPayProperties.getSubMchId());
            WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
            return refundResult.getRefundId();
        } catch (WxPayException e) {
            log.error("申请微信支付退款失败，商户订单号：{}，错误信息：{}", outTradeNo, e.getMessage(), e);
            throw e;
        }
    }

}
