package com.erp.report.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.report.dto.*;
import com.erp.report.service.ReportService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 报表统计控制器
 * 
 * 提供以下报表接口：
 * - 订单统计（GET /tenant/reports/orders）
 * - 销售统计（GET /tenant/reports/sales）
 * - 库存统计（GET /tenant/reports/stock）
 * - API调用统计（GET /tenant/reports/api-usage）
 * - 采购报表（GET /tenant/reports/purchases）
 * - 资金报表（GET /tenant/reports/finances）
 */
@Slf4j
@RestController
@RequestMapping("/tenant/reports")
@RequiredArgsConstructor
@Validated
public class ReportController {

    private final ReportService reportService;

    /**
     * 订单统计
     * 
     * 支持按平台/店铺/日期/月份分组统计订单数量和金额
     * 
     * @param request 查询参数
     * @return 订单统计数据
     */
    @GetMapping("/orders")
    public ResponseEntity<ApiResponse<OrderReportResponse>> getOrderReport(
            @Valid OrderReportRequest request) {
        log.info("订单统计请求, groupBy={}, platform={}, shopId={}", 
                request.getGroupBy(), request.getPlatform(), request.getShopId());
        OrderReportResponse result = reportService.getOrderReport(request);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 销售统计
     * 
     * 按日/周/月统计销售收入、订单数量、平均订单金额
     * 
     * @param request 查询参数
     * @return 销售统计数据
     */
    @GetMapping("/sales")
    public ResponseEntity<ApiResponse<SalesReportResponse>> getSalesReport(
            @Valid SalesReportRequest request) {
        log.info("销售统计请求, period={}, platform={}, shopId={}", 
                request.getPeriod(), request.getPlatform(), request.getShopId());
        SalesReportResponse result = reportService.getSalesReport(request);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 库存统计
     * 
     * 支持三种模式：
     * - overview: 库存概览（总量、可用量、低库存、呆滞等）
     * - slow_moving: 呆滞库存（指定天数内无变动的库存）
     * - turnover: 库存周转率（30天出库/库存计算周转率）
     * 
     * @param request 查询参数
     * @return 库存统计数据
     */
    @GetMapping("/stock")
    public ResponseEntity<ApiResponse<StockReportResponse>> getStockReport(
            @Valid StockReportRequest request) {
        log.info("库存统计请求, type={}, warehouseId={}", 
                request.getType(), request.getWarehouseId());
        StockReportResponse result = reportService.getStockReport(request);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * API调用统计
     * 
     * 统计各平台拉取订单的次数、成功/失败数
     * 支持按日期/平台/拉取类型分组
     * 
     * @param request 查询参数
     * @return API调用统计数据
     */
    @GetMapping("/api-usage")
    public ResponseEntity<ApiResponse<ApiUsageReportResponse>> getApiUsageReport(
            @Valid ApiUsageReportRequest request) {
        log.info("API调用统计请求, period={}, platform={}", 
                request.getPeriod(), request.getPlatform());
        ApiUsageReportResponse result = reportService.getApiUsageReport(request);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 采购报表
     * 
     * 统计采购订单的数量、金额、按状态分类
     * 
     * @param request 查询参数
     * @return 采购报表数据
     */
    @GetMapping("/purchases")
    public ResponseEntity<ApiResponse<PurchaseReportResponse>> getPurchaseReport(
            @Valid PurchaseReportRequest request) {
        log.info("采购报表请求, platform={}, shopId={}, warehouseId={}, status={}", 
                request.getPlatform(), request.getShopId(), request.getWarehouseId(), request.getStatus());
        PurchaseReportResponse result = reportService.getPurchaseReport(request);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 资金报表
     * 
     * 统计收入（已完成订单）、支出（已完成采购单）、净利润
     * 支持按日期查看每日收支明细
     * 
     * @param request 查询参数
     * @return 资金报表数据
     */
    @GetMapping("/finances")
    public ResponseEntity<ApiResponse<FinanceReportResponse>> getFinanceReport(
            @Valid FinanceReportRequest request) {
        log.info("资金报表请求, platform={}, shopId={}", 
                request.getPlatform(), request.getShopId());
        FinanceReportResponse result = reportService.getFinanceReport(request);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    // ==================== 数据可视化支持接口 ====================

    /**
     * 仪表盘汇总数据
     * 
     * 提供给前端仪表盘使用的一站式汇总数据接口
     * 包含今日订单、本月销售、库存状态、资金概览等
     * 
     * @param platform 可选平台过滤
     * @param shopId 可选店铺过滤
     * @return 仪表盘汇总数据
     */
    @GetMapping("/dashboard-summary")
    public ResponseEntity<ApiResponse<DashboardSummary>> getDashboardSummary(
            @RequestParam(required = false) String platform,
            @RequestParam(required = false) Long shopId) {
        log.info("仪表盘汇总请求, platform={}, shopId={}", platform, shopId);
        
        // 今日订单统计
        OrderReportRequest orderReq = OrderReportRequest.builder()
                .platform(platform)
                .shopId(shopId)
                .startDate(java.time.LocalDate.now().toString())
                .endDate(java.time.LocalDate.now().toString())
                .groupBy("platform")
                .build();
        OrderReportResponse todayOrders = reportService.getOrderReport(orderReq);
        
        // 本月销售统计
        SalesReportRequest salesReq = SalesReportRequest.builder()
                .platform(platform)
                .shopId(shopId)
                .startDate(java.time.LocalDate.now().withDayOfMonth(1).toString())
                .endDate(java.time.LocalDate.now().toString())
                .period("day")
                .build();
        SalesReportResponse monthSales = reportService.getSalesReport(salesReq);
        
        // 库存概览
        StockReportRequest stockReq = StockReportRequest.builder()
                .type("overview")
                .build();
        StockReportResponse stockOverview = reportService.getStockReport(stockReq);
        
        // 资金概览
        FinanceReportRequest financeReq = FinanceReportRequest.builder()
                .platform(platform)
                .shopId(shopId)
                .startDate(java.time.LocalDate.now().withDayOfMonth(1).toString())
                .endDate(java.time.LocalDate.now().toString())
                .build();
        FinanceReportResponse financeOverview = reportService.getFinanceReport(financeReq);
        
        DashboardSummary summary = DashboardSummary.builder()
                .todayOrderCount(todayOrders.getList().stream()
                        .mapToLong(com.erp.report.dto.OrderReportResponse.OrderStatItem::getOrderCount)
                        .sum())
                .todaySalesAmount(todayOrders.getList().stream()
                        .map(com.erp.report.dto.OrderReportResponse.OrderStatItem::getTotalAmount)
                        .reduce(java.math.BigDecimal.ZERO, java.math.BigDecimal::add))
                .monthOrderCount(monthSales.getSummary() != null ? monthSales.getSummary().getTotalOrders() : 0L)
                .monthSalesAmount(monthSales.getSummary() != null ? monthSales.getSummary().getTotalSales() : java.math.BigDecimal.ZERO)
                .totalStocks(stockOverview.getTotalStocks() != null ? stockOverview.getTotalStocks() : 0L)
                .lowStockCount(stockOverview.getLowStockCount() != null ? stockOverview.getLowStockCount() : 0L)
                .outOfStockCount(stockOverview.getOutOfStockCount() != null ? stockOverview.getOutOfStockCount() : 0L)
                .monthIncome(financeOverview.getSummary() != null ? financeOverview.getSummary().getTotalIncome() : java.math.BigDecimal.ZERO)
                .monthExpense(financeOverview.getSummary() != null ? financeOverview.getSummary().getTotalExpense() : java.math.BigDecimal.ZERO)
                .monthProfit(financeOverview.getSummary() != null ? financeOverview.getSummary().getNetProfit() : java.math.BigDecimal.ZERO)
                .build();
        
        return ResponseEntity.ok(ApiResponse.success(summary));
    }

    /**
     * 仪表盘汇总数据DTO
     */
    @lombok.Data
    @lombok.Builder
    @lombok.NoArgsConstructor
    @lombok.AllArgsConstructor
    public static class DashboardSummary {
        private Long todayOrderCount;
        private java.math.BigDecimal todaySalesAmount;
        private Long monthOrderCount;
        private java.math.BigDecimal monthSalesAmount;
        private Long totalStocks;
        private Long lowStockCount;
        private Long outOfStockCount;
        private java.math.BigDecimal monthIncome;
        private java.math.BigDecimal monthExpense;
        private java.math.BigDecimal monthProfit;
    }
}
