package beilv.wx.pay.controller;

import beilv.common.core.controller.BaseController;
import beilv.common.core.domain.AjaxResult;
import beilv.order.domain.StoreOrder;
import beilv.order.mapper.StoreOrderMapper;
import beilv.wx.pay.domain.vo.AppPayParam;
import beilv.wx.pay.domain.vo.AppRefundParam;
import beilv.wx.pay.service.IWxPayService;
import com.github.binarywang.wxpay.bean.result.WxPayRefundV3Result;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api("微信支付V3部分接口示例")
@RestController
@RequestMapping("/")
public class WxPayController extends BaseController {

    @Autowired
    private IWxPayService wxPayService;
    
    @Autowired
    private StoreOrderMapper storeOrderMapper;

    /**
     * 调用统一下单接口(JSAPI)
     * 详见：https://pay.weixin.qq.com/doc/v3/merchant/4012791856
     * 
     * @deprecated 已整合到 CardAppController.addOrderLog 接口中，建议前端直接调用 /app-api/cardApp/addOrderLog
     * 该接口保留用于内部调用和兼容性
     */
    @Deprecated
    @ApiOperation(value = "统一下单，并组装所需支付参数（已废弃，建议使用 addOrderLog）")
    @PostMapping("app-api/pay/unifiedOrder")
    public AjaxResult unifiedOrder(@RequestBody AppPayParam param) throws Exception {
        log.info("收到统一下单请求，订单号: {}", param.getOrderId());
        try {
            return AjaxResult.success(wxPayService.unifiedOrder(param));
        } catch (Exception e) {
            log.error("统一下单处理失败，订单号: {}", param.getOrderId(), e);
            throw e;
        }
    }


    /**
     * <pre>
     * 支付成功回调
     * 详见 https://pay.weixin.qq.com/doc/v3/merchant/4012791861
     * </pre>
     *
     * @param notifyData
     * @param request
     * @return
     * @throws WxPayException
     */
    @ApiOperation(value = "支付回调通知处理")
    @PostMapping("app/pay/notify")
    public AjaxResult parseOrderNotifyResult(@RequestBody String notifyData, HttpServletRequest request) {
        return wxPayService.handleNotify(notifyData, request);
    }

    /**
     * 取消订单
     *
     * @param orderId 订单ID
     * @return 处理结果
     */
    @ApiOperation(value = "取消订单")
    @GetMapping("app-api/pay/cancel")
    public AjaxResult cancelOrder(@RequestBody String orderId) {
        return toAjax(wxPayService.cancelOrder(orderId));
    }

    /**
     * <pre>
     * 微信支付-申请退款
     * 详见 https://pay.weixin.qq.com/doc/v3/merchant/4012791862
     * </pre>
     *
     * @return 退款操作结果
     */
    @ApiOperation(value = "退款")
    @PostMapping("app-api/pay/refund")
    public WxPayRefundV3Result refund(@RequestBody AppRefundParam param) throws WxPayException {
        log.info("收到退款请求，订单号: {}", param.getOrderId());
        try {
            WxPayRefundV3Result result = wxPayService.refund(param);
            log.info("退款处理完成，订单号: {}", param.getOrderId());
            return result;
        } catch (WxPayException e) {
            log.error("退款处理失败，订单号: {}", param.getOrderId(), e);
            throw e;
        }
    }

    /**
     * <pre>
     * 退款成功回调
     * 详见 https://pay.weixin.qq.com/doc/v3/merchant/4012791865
     * </pre>
     *
     * @param notifyData
     * @param request
     * @return
     * @throws WxPayException
     */
    @ApiOperation(value = "退款回调通知处理")
    @PostMapping("app/notify/refund")
    public AjaxResult parseRefundNotifyResult(@RequestBody String notifyData, HttpServletRequest request) {
        return wxPayService.parseRefundNotify(notifyData, request);
    }
    
    /**
     * 查询待支付订单信息
     * 用于小程序在5分钟内重新拉取待支付订单的信息
     *
     * @param param 
     * @return 订单信息
     */
    @ApiOperation(value = "查询待支付订单信息")
    @GetMapping("app-api/pay/pending-order")
    public AjaxResult getPendingOrder(@RequestBody AppPayParam param) throws Exception {
        StoreOrder order = storeOrderMapper.selectStoreOrderByOrderId(param.getOrderId());
        log.info("收到查询待支付订单请求，订单号: {}", param);
        if (order == null) {
            log.warn("订单不存在，订单号: {}", param.getOrderId());
            return AjaxResult.error("订单不存在");
        }
        // 检查订单是否为待支付状态
        if (order.getPaid() != null && order.getPaid() == 1) {
            log.info("订单已支付，订单号: {}", param.getOrderId());
            return AjaxResult.error("订单已支付");
        }
        // 检查订单是否已超时取消
        if (order.getStatus() != null && order.getStatus() == 3) {
            log.info("订单已取消，订单号: {}", param.getOrderId());
            return AjaxResult.error("订单已取消");
        }
        // 返回订单信息和重新支付所需参数
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        // 如果需要重新支付，可以在这里调用统一下单接口生成新的支付参数
        return AjaxResult.success(wxPayService.unifiedOrder(param));
    }

}