package com.dora.controller;

import com.dora.annotation.RequireAdminOrStaff;
import com.dora.dto.ApiResponse;
import com.dora.dto.AdminOrderDto;
import com.dora.service.AdminOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotNull;

/**
 * 管理员订单管理控制器
 */
@RestController
@RequestMapping("/admin/orders")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "管理员订单管理", description = "管理员订单和交易管理相关接口")
@RequireAdminOrStaff
public class AdminOrderController {

    private final AdminOrderService adminOrderService;

    @GetMapping("/list")
    @Operation(summary = "获取订单列表", description = "分页获取系统订单列表，支持多种筛选条件")
    public ApiResponse<AdminOrderDto.OrderListResponse> getOrderList(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size,
            @Parameter(description = "订单状态筛选（0待支付/1已支付/2已取消/3已退款）") @RequestParam(required = false) Integer status,
            @Parameter(description = "订单类型筛选") @RequestParam(required = false) String orderType,
            @Parameter(description = "搜索关键词（订单号、用户信息）") @RequestParam(required = false) String keyword,
            @Parameter(description = "开始时间", example = "2024-01-01T00:00:00") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束时间", example = "2024-01-31T23:59:59") @RequestParam(required = false) String endDate,
            @Parameter(description = "开始时间（兼容参数）", example = "2024-01-01T00:00:00") @RequestParam(required = false) String dateStart,
            @Parameter(description = "结束时间（兼容参数）", example = "2024-01-31T23:59:59") @RequestParam(required = false) String dateEnd,
            @Parameter(description = "排序字段", example = "create_time") @RequestParam(defaultValue = "create_time") String sortField,
            @Parameter(description = "排序方向", example = "desc") @RequestParam(defaultValue = "desc") String sortOrder) {
        
        log.info("收到获取订单列表请求，页码：{}，大小：{}，状态：{}，dateStart：{}，dateEnd：{}", 
                page, size, status, dateStart, dateEnd);
        
        // 参数兼容性处理：优先使用 dateStart/dateEnd，如果为空则使用 startDate/endDate
        String effectiveStartDate = (dateStart != null && !dateStart.isEmpty()) ? dateStart : startDate;
        String effectiveEndDate = (dateEnd != null && !dateEnd.isEmpty()) ? dateEnd : endDate;
        
        log.info("有效时间参数：startDate={}，endDate={}", effectiveStartDate, effectiveEndDate);
        
        AdminOrderDto.OrderListRequest request = new AdminOrderDto.OrderListRequest();
        request.setPage(page);
        request.setSize(size);
        request.setStatus(status);
        request.setOrderType(orderType);
        request.setKeyword(keyword);
        request.setStartDate(effectiveStartDate);
        request.setEndDate(effectiveEndDate);
        request.setSortField(sortField);
        request.setSortOrder(sortOrder);
        
        return adminOrderService.getOrderList(request);
    }

    @GetMapping("/summary")
    @Operation(summary = "获取订单汇总", description = "获取订单统计汇总数据")
    public ApiResponse<AdminOrderDto.OrderSummaryResponse> getOrderSummary(
            @Parameter(description = "统计周期（daily/weekly/monthly）") @RequestParam(defaultValue = "daily") String period,
            @Parameter(description = "开始日期", example = "2024-01-01") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期", example = "2024-01-31") @RequestParam(required = false) String endDate) {
        
        log.info("收到获取订单汇总请求，周期：{}", period);
        
        AdminOrderDto.OrderSummaryRequest request = new AdminOrderDto.OrderSummaryRequest();
        request.setPeriod(period);
        request.setStartDate(startDate);
        request.setEndDate(endDate);
        
        return adminOrderService.getOrderSummary(request);
    }

    @GetMapping("/{orderId}")
    @Operation(summary = "获取订单详情", description = "获取指定订单的详细信息")
    public ApiResponse<AdminOrderDto.OrderDetailResponse> getOrderDetail(
            @Parameter(description = "订单ID") @PathVariable Long orderId) {
        
        log.info("收到获取订单详情请求，订单ID：{}", orderId);
        return adminOrderService.getOrderDetail(orderId);
    }

    @PutMapping("/{orderId}/status")
    @Operation(summary = "更新订单状态", description = "管理员更新订单状态")
    public ApiResponse<String> updateOrderStatus(
            @Parameter(description = "订单ID") @PathVariable Long orderId,
            @Parameter(description = "新状态（0待支付/1已支付/2已取消/3已退款）") @RequestParam @NotNull Integer status,
            @Parameter(description = "备注信息") @RequestParam(required = false) String remark) {
        
        log.info("收到更新订单状态请求，订单ID：{}，新状态：{}", orderId, status);
        
        AdminOrderDto.OrderStatusUpdateRequest request = new AdminOrderDto.OrderStatusUpdateRequest();
        request.setOrderId(orderId);
        request.setStatus(status);
        request.setRemark(remark);
        
        return adminOrderService.updateOrderStatus(request);
    }



    @GetMapping("/transactions/statistics")
    @Operation(summary = "获取交易统计", description = "获取交易相关统计数据")
    public ApiResponse<AdminOrderDto.TransactionStatisticsResponse> getTransactionStatistics(
            @Parameter(description = "统计周期（daily/weekly/monthly）") @RequestParam(defaultValue = "daily") String period,
            @Parameter(description = "开始日期", example = "2024-01-01") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期", example = "2024-01-31") @RequestParam(required = false) String endDate) {
        
        log.info("收到获取交易统计请求，周期：{}", period);
        
        AdminOrderDto.TransactionStatisticsRequest request = new AdminOrderDto.TransactionStatisticsRequest();
        request.setPeriod(period);
        request.setStartDate(startDate);
        request.setEndDate(endDate);
        
        return adminOrderService.getTransactionStatistics(request);
    }
}
