package com.aircraft.modules.order.controller;

import com.aircraft.modules.order.domain.OrderMain;
import com.aircraft.modules.order.domain.dto.*;
import com.aircraft.modules.order.service.IOrderMainService;
import com.aircraft.modules.order.service.OrderAnalysisService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Pattern;

@Api(tags = "系统：订单分析")
@RestController
@RequestMapping("/fmsOdOrderAnalysis")
//每个接口都返回时间范围内的总订单量、订单总金额、进行中的订单量、完成的订单量、完成的订单率、
// 时间范围内的所有订单信息（分页管理）、无人机型号订单占比、不同区域的订单总量
public class OrderAnalysisController {

    private static final Logger LOG = LoggerFactory.getLogger(OrderAnalysisController.class);
    @Autowired
    private OrderAnalysisService orderAnalysisService;
    @Autowired
    private IOrderMainService iOrderMainService;

    // 日期格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM");
    private static final DateTimeFormatter YEAR_FORMATTER = DateTimeFormatter.ofPattern("yyyy");
    // 季度格式校验正则（yyyy-Q1~Q4）
    private static final Pattern QUARTER_PATTERN = Pattern.compile("^\\d{4}-Q[1-4]$");

    @ApiOperation("全部订单分析统计")
    @GetMapping
    public ResponseEntity<OrderAnalysisResult<T>> analyzeAllOrders() {
        try {
            // 1. 获取数据库中所有订单数据
            List<OrderMain> allOrders = iOrderMainService.queryAllOrders();

            // 2. 校验订单数据
            if (CollectionUtils.isEmpty(allOrders)) {
                LOG.info("全部订单分析：未找到订单数据");
                return ResponseEntity.badRequest().body(null);
            }
            OrderAnalysisResult<T> result = orderAnalysisService.analyzeAllOrders(allOrders);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("全部订单分析失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    @ApiOperation("按日范围分析订单")
    @GetMapping("/day")
    //额外返回传入时间范围内的每日订单总量
    public ResponseEntity<OrderAnalysisResult<List<DailyStat>>> analyzeByDayRange(
            @ApiParam(value = "开始日期（yyyy-MM-dd）", required = true, example = "2025-01-01")
            @RequestParam("startDate") String startDate,
            @ApiParam(value = "结束日期（yyyy-MM-dd）", required = true, example = "2025-11-01")
            @RequestParam("endDate") String endDate) {
        try {
            // 解析日期
            LocalDate start = LocalDate.parse(startDate, DATE_FORMATTER);
            LocalDate end = LocalDate.parse(endDate, DATE_FORMATTER);

            // 校验时间范围
            if (start.isAfter(end)) {
                LOG.warn("按日分析：开始日期[{}]晚于结束日期[{}]", startDate, endDate);
                return ResponseEntity.badRequest().body(null);
            }

            // 调用服务层
            OrderAnalysisResult<List<DailyStat>> result = orderAnalysisService.analyzeByDayRange(start, end);
            LOG.info("按日分析完成，时间范围：{}至{}", startDate, endDate);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("按日分析失败，参数：startDate={}, endDate={}", startDate, endDate, e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    @ApiOperation("按月范围分析订单")
    @GetMapping("/month")
    //传入的时间范围：某年的某月到某年的某月，额外返回时间范围内的每月总订单量
    public ResponseEntity<OrderAnalysisResult<List<MonthlyStat>>> analyzeByMonthRange(
            @ApiParam(value = "开始月份（yyyy-MM）", required = true, example = "2025-03")
            @RequestParam("startDate") String startDate,
            @ApiParam(value = "结束月份（yyyy-MM）", required = true, example = "2025-11")
            @RequestParam("endDate") String endDate) {
        try {
            // 解析月份为当月第一天
            LocalDate start = LocalDate.parse(startDate + "-01", DATE_FORMATTER);
            // 解析结束月份为当月最后一天（自动处理大小月和闰年）
            LocalDate end = LocalDate.parse(endDate + "-01", DATE_FORMATTER)
                    .withDayOfMonth(LocalDate.parse(endDate + "-01", DATE_FORMATTER).lengthOfMonth());

            // 校验时间范围
            if (start.isAfter(end)) {
                LOG.warn("按月分析：开始月份[{}]晚于结束月份[{}]", startDate, endDate);
                return ResponseEntity.badRequest().body(null);
            }

            // 调用服务层
            OrderAnalysisResult<List<MonthlyStat>> result = orderAnalysisService.analyzeByMonthRange(start, end);
            LOG.info("按月分析完成，时间范围：{}至{}", startDate, endDate);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("按月分析失败，参数：startDate={}, endDate={}", startDate, endDate, e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    @ApiOperation("按季度范围分析订单")
    @GetMapping("/quarter")
    //传入的时间范围：某年的某季到某年的某季，yyyy-Qn (例: 2025-Q1)，额外返回时间范围内的每季总订单量
    public ResponseEntity<OrderAnalysisResult<List<QuarterlyStat>>> analyzeByQuarterRange(
            @ApiParam(value = "开始季度（yyyy-Qn，例：2025-Q1）", required = true)
            @RequestParam("startDate") String startDate,
            @ApiParam(value = "结束季度（yyyy-Qn，例：2025-Q4）", required = true)
            @RequestParam("endDate") String endDate) {
        try {
            // 校验季度格式
            if (!QUARTER_PATTERN.matcher(startDate).matches() || !QUARTER_PATTERN.matcher(endDate).matches()) {
                LOG.warn("按季度分析：格式错误，startDate={}, endDate={}（正确格式：yyyy-Q1~Q4）", startDate, endDate);
                return ResponseEntity.badRequest().body(null);
            }

            // 解析季度（格式：yyyy-Qn → 年份和季度数）
            String[] startParts = startDate.split("-Q");
            int startYear = Integer.parseInt(startParts[0]);
            int startQuarter = Integer.parseInt(startParts[1]);

            String[] endParts = endDate.split("-Q");
            int endYear = Integer.parseInt(endParts[0]);
            int endQuarter = Integer.parseInt(endParts[1]);

            // 计算季度对应的日期范围（季度第一天至季度最后一天）
            LocalDate start = getQuarterFirstDay(startYear, startQuarter);
            LocalDate end = getQuarterLastDay(endYear, endQuarter);

            // 校验时间范围
            if (start.isAfter(end)) {
                LOG.warn("按季度分析：开始季度[{}]晚于结束季度[{}]", startDate, endDate);
                return ResponseEntity.badRequest().body(null);
            }

            // 调用服务层
            OrderAnalysisResult<List<QuarterlyStat>> result = orderAnalysisService.analyzeByQuarterRange(start, end);
            LOG.info("按季度分析完成，时间范围：{}至{}", startDate, endDate);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("按季度分析失败，参数：startDate={}, endDate={}", startDate, endDate, e);
            return ResponseEntity.badRequest().body(null);
        }
    }


    @ApiOperation("按年范围分析订单")
    @GetMapping("/year")
    //传入的时间范围；某年到某年，额外返回时间范围内的每年总订单量
    public ResponseEntity<OrderAnalysisResult<List<YearlyStat>>> analyzeByYearRange(
            @ApiParam(value = "开始年份（yyyy）", required = true, example = "2023")
            @RequestParam("startDate") String startDate,
            @ApiParam(value = "结束年份（yyyy）", required = true, example = "2025")
            @RequestParam("endDate") String endDate) {
        try {
            // 解析年份为当年第一天和最后一天
            LocalDate start = LocalDate.parse(startDate + "-01-01", DATE_FORMATTER);
            LocalDate end = LocalDate.parse(endDate + "-12-31", DATE_FORMATTER);

            // 校验时间范围
            if (start.isAfter(end)) {
                LOG.warn("按年分析：开始年份[{}]晚于结束年份[{}]", startDate, endDate);
                return ResponseEntity.badRequest().body(null);
            }

            // 调用服务层
            OrderAnalysisResult<List<YearlyStat>> result = orderAnalysisService.analyzeByYearRange(start, end);
            LOG.info("按年分析完成，时间范围：{}至{}", startDate, endDate);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("按年分析失败，参数：startDate={}, endDate={}", startDate, endDate, e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    // 工具方法：获取季度第一天（如2025-Q1 → 2025-01-01）
    private LocalDate getQuarterFirstDay(int year, int quarter) {
        int month = (quarter - 1) * 3 + 1;
        return LocalDate.of(year, month, 1);
    }

    // 工具方法：获取季度最后一天（如2025-Q1 → 2025-03-31）
    private LocalDate getQuarterLastDay(int year, int quarter) {
        int month = quarter * 3;
        return LocalDate.of(year, month, 1).withDayOfMonth(LocalDate.of(year, month, 1).lengthOfMonth());
    }
}
