package com.zhentao.controller;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.zhentao.common.Result;
import com.zhentao.dto.ActivityCreateOrderDto;
import com.zhentao.service.ActivityOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 活动订单控制器
 */
@RestController
@RequestMapping("/api/activity-order")
public class ActivityOrderController {

    @Autowired
    private ActivityOrderService activityOrderService;

    @PostMapping("/create")
    public Result createOrder(@RequestBody ActivityCreateOrderDto dto) throws WxPayException {
        return Result.success(activityOrderService.createOrderAndGetPayParams(dto.getUserId(), dto.getActivityId(), dto.getActivityName(), dto.getPrice()));
    }

    @PostMapping("/notify")
    public String handlePayNotify(@RequestBody(required = true) String notifyData) throws WxPayException {
        if (notifyData == null || notifyData.trim().isEmpty()) {
            // 记录日志 + 返回微信要求的XML格式失败响应
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[请求体为空]]></return_msg></xml>";
        }

        return activityOrderService.handlePayNotify(notifyData);
    }

    @GetMapping("/status/{orderNo}")
    public Map<String, Object> getOrderStatus(@PathVariable String orderNo) {
        Map<String, Object> result = new HashMap<>();
        result.put("orderNo", orderNo);
        result.put("status", activityOrderService.getOrderByOrderNo(orderNo).getStatus());
        return result;
    }
}