package beilv.pay.controller;

import beilv.common.core.domain.AjaxResult;
import beilv.pay.service.WxUserPayService;
import cn.hutool.core.util.IdUtil;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.model.Refund;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping
public class WxUserPayController {
    @Resource
    private WxUserPayService wxUserPayService;

    /**
     * JSAPI 下单
     */
    @GetMapping("/create/IndentPayment")
    public AjaxResult creationIndentPayment(String openId) {
        PrepayWithRequestPaymentResponse paymentResponse = wxUserPayService.creationIndentPayment(IdUtil.simpleUUID(), openId, 0.01);
        return AjaxResult.success(paymentResponse);
    }

    /**
     * JSAPI 下单回调
     */
    @PostMapping("/end/IndentPayment")
    @Transactional(rollbackFor = Exception.class)
    public synchronized AjaxResult endIndentPayment(HttpServletRequest request) {
        // 获取下单信息
        Transaction transaction = wxUserPayService.getTransaction(request);
        // 修改订单状态
        boolean result = wxUserPayService.indentPaymentBlack(transaction);
//        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "修改订单失败");
        return AjaxResult.success(result);
    }

    /**
     * 退款
     */
    @GetMapping("/refund/IndentPayment")
    public AjaxResult refundIndentPayment(@RequestParam String orderId, @RequestParam Double amount) {
        Refund refund = wxUserPayService.refundIndentPayment(orderId, amount);
        return AjaxResult.success(refund);
    }

    /**
     * 退款回调
     */
    @PostMapping("/refund/black")
    public AjaxResult endRefundIndent(HttpServletRequest request) {
        // 获取退款信息
        RefundNotification refundNotification = wxUserPayService.getRefundNotification(request);
        // 修改订单状态
        boolean result = wxUserPayService.refundIndentBlack(refundNotification);
        return AjaxResult.success(result);
    }
}
