package com.erp.tenant.controller.report;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.erp.common.core.model.ApiResponse;
import com.erp.common.core.model.PageResponse;
import com.erp.tenant.config.TenantContext;
import com.erp.tenant.dto.report.ReportPageResponse;
import com.erp.tenant.service.report.ReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Map;

/**
 * 租户端数据统计控制器
 * 功能：订单统计/销售统计/库存统计/API调用统计
 */
@Slf4j
@RestController
@RequestMapping("/api/tenant/reports")
@RequiredArgsConstructor
public class ReportController {

    private final ReportService reportService;

    /**
     * 订单统计
     * GET /api/tenant/reports/orders
     */
    @GetMapping("/orders")
    public ApiResponse<PageResponse<Map<String, Object>>> getOrderReport(
            @RequestParam(required = false) String platform,
            @RequestParam(required = false) Long shopId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false, defaultValue = "platform") String groupBy,
            @RequestParam(required = false, defaultValue = "desc") String trend,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {

        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.<PageResponse<Map<String, Object>>>error(401, "未获取到租户信息");
        }

        IPage<Map<String, Object>> reportPage = reportService.getOrderReport(
                tenantId, platform, shopId, startDate, endDate, groupBy, trend, page, pageSize);

        PageResponse<Map<String, Object>> response = PageResponse.<Map<String, Object>>builder()
                .list(reportPage.getRecords())
                .total(reportPage.getTotal())
                .page(reportPage.getCurrent())
                .pageSize(reportPage.getSize())
                .totalPages(reportPage.getPages())
                .build();

        return ApiResponse.success(response);
    }

    /**
     * 销售统计
     * GET /api/tenant/reports/sales
     */
    @GetMapping("/sales")
    public ApiResponse<?> getSalesReport(
            @RequestParam(required = false) String platform,
            @RequestParam(required = false) Long shopId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false, defaultValue = "day") String period,
            @RequestParam(required = false, defaultValue = "asc") String trend,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "30") Integer pageSize) {

        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.<Object>error(401, "未获取到租户信息");
        }

        ReportPageResponse.SalesReportDTO summary = reportService.getSalesSummary(
                tenantId, platform, shopId, startDate, endDate, period);

        IPage<Map<String, Object>> reportPage = reportService.getSalesReport(
                tenantId, platform, shopId, startDate, endDate, period, trend, page, pageSize);

        PageResponse<Map<String, Object>> response = PageResponse.<Map<String, Object>>builder()
                .list(reportPage.getRecords())
                .total(reportPage.getTotal())
                .page(reportPage.getCurrent())
                .pageSize(reportPage.getSize())
                .totalPages(reportPage.getPages())
                .build();

        return ApiResponse.success(Map.of(
                "period", period,
                "summary", summary,
                "list", response
        ));
    }

    /**
     * 库存统计
     * GET /api/tenant/reports/stock
     */
    @GetMapping("/stock")
    public ApiResponse<?> getStockReport(
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false, defaultValue = "overview") String type,
            @RequestParam(required = false, defaultValue = "30") Integer slowDays,
            @RequestParam(required = false, defaultValue = "quantity") String sort,
            @RequestParam(required = false, defaultValue = "desc") String trend,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {

        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.<Object>error(401, "未获取到租户信息");
        }

        if ("overview".equals(type)) {
            ReportPageResponse.StockReportDTO overview = reportService.getStockOverview(tenantId, warehouseId, slowDays);
            return ApiResponse.success(overview);
        }

        if ("slow_moving".equals(type)) {
            IPage<Map<String, Object>> reportPage = reportService.getSlowMovingReport(
                    tenantId, warehouseId, slowDays, page, pageSize);
            PageResponse<Map<String, Object>> response = PageResponse.<Map<String, Object>>builder()
                    .list(reportPage.getRecords())
                    .total(reportPage.getTotal())
                    .page(reportPage.getCurrent())
                    .pageSize(reportPage.getSize())
                    .totalPages(reportPage.getPages())
                    .build();
            return ApiResponse.success(Map.of("type", type, "slowDays", slowDays, "list", response));
        }

        if ("turnover".equals(type)) {
            IPage<Map<String, Object>> reportPage = reportService.getTurnoverReport(
                    tenantId, warehouseId, page, pageSize);
            PageResponse<Map<String, Object>> response = PageResponse.<Map<String, Object>>builder()
                    .list(reportPage.getRecords())
                    .total(reportPage.getTotal())
                    .page(reportPage.getCurrent())
                    .pageSize(reportPage.getSize())
                    .totalPages(reportPage.getPages())
                    .build();
            return ApiResponse.success(Map.of("type", type, "list", response));
        }

        return ApiResponse.<Object>error(400, "未知的统计类型");
    }

    /**
     * API调用统计
     * GET /api/tenant/reports/api-usage
     */
    @GetMapping("/api-usage")
    public ApiResponse<?> getApiUsageReport(
            @RequestParam(required = false) String platform,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false, defaultValue = "day") String period,
            @RequestParam(required = false, defaultValue = "desc") String trend,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "30") Integer pageSize) {

        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.<Object>error(401, "未获取到租户信息");
        }

        IPage<Map<String, Object>> reportPage = reportService.getApiUsageReport(
                tenantId, platform, startDate, endDate, period, trend, page, pageSize);

        PageResponse<Map<String, Object>> response = PageResponse.<Map<String, Object>>builder()
                .list(reportPage.getRecords())
                .total(reportPage.getTotal())
                .page(reportPage.getCurrent())
                .pageSize(reportPage.getSize())
                .totalPages(reportPage.getPages())
                .build();

        return ApiResponse.success(Map.of("period", period, "list", response));
    }
}
