package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.admin.dto.OrderQueryDTO;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.Order;
import com.haha.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 订单管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    /**
     * 分页查询订单列表
     * @param queryDTO 查询参数
     * @return 订单列表
     */
    @RequirePermission("order:read")
    @GetMapping("/list")
    public Result<PageResult<Order>> list(OrderQueryDTO queryDTO) {
        log.info("订单列表查询参数：page={}, pageSize={}, orderNo={}, deviceId={}", 
                queryDTO.getPage(), queryDTO.getPageSize(), 
                queryDTO.getOrderNo(), queryDTO.getDeviceId());
        
        queryDTO.validate();
        
        IPage<Order> orderPage = orderService.getPage(
                queryDTO.getPage(), 
                queryDTO.getPageSize(),
                queryDTO.getOrderNo(),
                queryDTO.getDeviceId(),
                queryDTO.getPayStatus(),
                queryDTO.getStatus(),
                queryDTO.getStartDate(),
                queryDTO.getEndDate()
        );

        return Result.success("查询成功", PageResult.of(orderPage));
    }

    /**
     * 获取订单详情
     * @param id 订单ID
     * @return 订单详情
     */
    @RequirePermission("order:read")
    @GetMapping("/{id}")
    public Result<Order> getById(@PathVariable Long id) {
        Order order = orderService.getDetailById(id);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        return Result.success("查询成功", order);
    }

    /**
     * 获取订单统计数据
     * @return 统计数据
     */
    @RequirePermission("order:read")
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        Map<String, Object> statistics = orderService.getStatistics();
        return Result.success("查询成功", statistics);
    }

    /**
     * 订单退款
     * @param id 订单ID
     * @param params 退款参数
     * @return 退款结果
     */
    @RequirePermission("order:update")
    @Log(module = "订单管理", operation = OperationType.UPDATE, summary = "订单退款")
    @PostMapping("/{id}/refund")
    public Result<Void> refund(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        String reason = (String) params.get("reason");
        boolean success = orderService.refund(id, reason);
        return success ? Result.success("退款成功", null) : Result.error(500, "退款失败");
    }
}
