package com.haha.miniapp.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.haha.common.constant.ResponseEnum;
import com.haha.common.vo.Result;
import com.haha.entity.dto.MiniappOrderQueryDTO;
import com.haha.entity.dto.OrderDetailDTO;
import com.haha.entity.dto.OrderCancelDTO;
import com.haha.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 订单相关接口
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/order")
public class OrderController {

    private final OrderService orderService;

    /**
     * 获取订单列表
     */
    @PostMapping("/list")
    public Result<List<Map<String, Object>>> getOrderList(@RequestBody(required = false) MiniappOrderQueryDTO queryDTO) {
        Long userId = StpUtil.getLoginIdAsLong();
        Integer status = queryDTO != null ? queryDTO.getStatus() : null;
        log.info("用户 {} 请求订单列表, status={}", userId, status);
        List<Map<String, Object>> orderList = orderService.getUserOrderListWithProducts(userId, status);
        log.info("用户 {} 查询到 {} 条订单", userId, orderList.size());
        return Result.success("查询成功", orderList);
    }

    /**
     * 获取订单详情
     */
    @PostMapping("/detail")
    public Result<Map<String, Object>> getOrderDetail(@RequestBody OrderDetailDTO dto) {
        Long userId = StpUtil.getLoginIdAsLong();
        Map<String, Object> orderDetail = orderService.getUserOrderDetail(userId, dto.getOrderId(), dto.getOrderNo(), dto.getOutTradeNo());
        if (orderDetail == null) {
            return ResponseEnum.PARAM_REQUIRED.toResult("参数错误：必须提供 orderId、orderNo 或 outTradeNo");
        }
        log.info("用户 {} 查询订单详情成功", userId);
        return Result.success("查询成功", orderDetail);
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel")
    public Result<Void> cancelOrder(@RequestBody OrderCancelDTO dto) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean success = orderService.cancelUserOrder(userId, dto.getOrderId());
        if (success) {
            log.info("用户 {} 取消订单成功", userId);
            return Result.success("订单已取消", null);
        } else {
            return Result.error("取消订单失败");
        }
    }
}
