package com.ruoyi.api.controller.pay;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.api.controller.common.AbstractApiController;
import com.ruoyi.common.exception.ServicePayException;
import com.ruoyi.common.utils.redis.RedisLock;
import com.ruoyi.newwxpay.pay.PayNotifyResult;
import com.ruoyi.newwxpay.service.NewWxPayService;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Api(value = "小程序回调通知控制器", tags = {"小程序回调通知控制器"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/wx")
@Slf4j
public class ApiNotifyController extends AbstractApiController {

    private final NewWxPayService newWxPayService;

    @Resource
    private RedisLock redisLock;

    /**
     * 支付回调地址
     */
    @ApiOperation("支付回调")
    @PostMapping("/pay/notify")
    public void payNotify(HttpServletRequest request) {
        try {
            PayNotifyResult notifyResult = newWxPayService.payNotify(request);
            if(ObjectUtil.isNotNull(notifyResult) && ObjectUtil.isNotNull(notifyResult.getTradeState())) {
//                // 票据订单回调
//                BusinessProductOrder order = businessProductOrderService.orderPayCallback(notifyResult);
//                // 回调成功
//                if (ObjectUtil.isNotNull(order)) {
//                    // 生成票据码信息
//                    Long businessId = order.getBusinessId();
//                    Long businessProductId = order.getBusinessProductId();
//                    String key = "MP_ORDER_BACK=shop:" + businessId +"=goods:"+ businessProductId;
//                    RLock lock = redisLock.getRLock(key);
//                    try {
//                        if (lock.tryLock(3, 5, TimeUnit.SECONDS)) {
//                            businessProductOrderCouponService.createBusinessProductCoupon(order);
//                        }
//                    } catch (Exception e) {
//                        log.error("支付成功创建门票券码失败，失败原因："+ e.getMessage());
//                        e.printStackTrace();
//                    } finally {
//                        lock.unlock();
//                    }
//                } else {
//                    throw new ServicePayException("FAIL", "失败");
//                }
            }

        }
        catch (Exception e)
        {
            log.error("微信支付回调异常", e);
            throw new ServicePayException("FAIL", "失败");
        }

    }

    /**
     * 退款回调
     */
    @ApiOperation("退款回调")
    @PostMapping("/refund/notify")
    public void refundNotify(HttpServletRequest request) {
        try {
            RefundNotification refundNotification = newWxPayService.refundNotify(request);
            if(ObjectUtil.isNotNull(refundNotification) && ObjectUtil.isNotNull(refundNotification.getRefundStatus())) {
//                BusinessProductRefund productRefund = businessProductRefundService.orderRefundCallback(refundNotification);
//
//                // 退款成功 发送延迟队列 计算分销和奖金池
//                if(OrderRefundAuditStatus.AUDIT_PASS.equals(productRefund.getAuditStatus())
//                    && OrderRefundStatus.YET_REFUND.equals(productRefund.getRefundStatus())) {
//
//                    BaseMap map = new BaseMap();
//                    map.add("orderNumber", productRefund.getRefundOrderNumber());
//                    rabbitMqClient.send(DelayedConstant.TicketRefundOrderFinishDelayedConstant.TICKET_REFUND_ORDER_FINISH_DELAYED_EXCHANGE,
//                        DelayedConstant.TicketRefundOrderFinishDelayedConstant.TICKET_REFUND_ORDER_FINISH_DELAYED_ROUTING,
//                        map, 10 * 1000);
//                }
            }
        }
        catch (Exception e)
        {
            log.error("微信退款回调异常", e);
            throw new ServicePayException("FAIL", "失败");
        }

    }

}
