package com.aircraft.modules.order.controller;

import com.aircraft.modules.order.domain.OrderDetail;
import com.aircraft.modules.order.domain.dto.*;
import com.aircraft.modules.order.service.IOrderDetailService;
import com.aircraft.modules.order.service.OrderDetailAnalysisService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

@Api(tags = "系统：子单任务分析")
@RestController
@RequestMapping("/fmsOdOrderDetailAnalysis")
//统一返回时间范围内任务总量，任务状态统计以及任务状态分布，景区路线任务分布
public class OrderDetailAnalysisController {

    private static final Logger LOG = LoggerFactory.getLogger(OrderDetailAnalysisController.class);

    @Autowired
    private OrderDetailAnalysisService orderDetailAnalysisService; // 子单分析服务层
    @Autowired
    private IOrderDetailService orderDetailService;

    // 日期格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final Pattern QUARTER_PATTERN = Pattern.compile("^\\d{4}-Q[1-4]$");


    @ApiOperation("全部子单任务分析统计")
    @GetMapping
    public ResponseEntity<OrderDetailAnalysisResult<T>> analyzeAllOrderDetails() {
        try {
            // 1. 获取所有子单数据
            List<OrderDetail> allDetails = orderDetailService.list();

            // 2. 校验数据
            if (CollectionUtils.isEmpty(allDetails)) {
                LOG.info("全部子单分析：未找到子单数据");
                return ResponseEntity.badRequest().body(null);
            }
            OrderDetailAnalysisResult<T> result = orderDetailAnalysisService.analyzeAllOrderDetails(allDetails);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("全部子单分析失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
    @ApiOperation("按日范围分析子单任务")
    @GetMapping("/day")
    // 额外返回：时间范围内任务列表
    public ResponseEntity<OrderDetailAnalysisResult<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-01-31")
            @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);
            }
            OrderDetailAnalysisResult<List<DailyStat>> result =
                    orderDetailAnalysisService.analyzeByDayRange(start, end);
            LOG.info("子单按日分析完成，时间范围：{}至{}", startDate, endDate);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("子单按日分析失败，参数：startDate={}, endDate={}", startDate, endDate, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    @ApiOperation("按月范围分析子单任务")
    @GetMapping("/month")
    // 额外返回：时间范围内任务列表
    public ResponseEntity<OrderDetailAnalysisResult<List<MonthlyStat>>> analyzeByMonthRange(
            @ApiParam(value = "开始月份（yyyy-MM）", required = true, example = "2025-01")
            @RequestParam("startDate") String startDate,
            @ApiParam(value = "结束月份（yyyy-MM）", required = true, example = "2025-03")
            @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);
            }

            OrderDetailAnalysisResult<List<MonthlyStat>> result =
                    orderDetailAnalysisService.analyzeByMonthRange(start, end);
            LOG.info("子单按月分析完成，时间范围：{}至{}", startDate, endDate);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("子单按月分析失败，参数：startDate={}, endDate={}", startDate, endDate, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    @ApiOperation("按季度范围分析子单任务")
    @GetMapping("/quarter")
    // 额外返回：时间范围内任务列表
    public ResponseEntity<OrderDetailAnalysisResult<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("子单按季度分析：格式错误，正确格式：yyyy-Q1~Q4");
                return ResponseEntity.badRequest().body(null);
            }

            // 解析季度为日期范围
            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);
            }

            // 调用服务层：按季度统计子单量、路线热度、操作员效率
            OrderDetailAnalysisResult<List<QuarterlyStat>> result =
                    orderDetailAnalysisService.analyzeByQuarterRange(start, end);
            LOG.info("子单按季度分析完成，时间范围：{}至{}", startDate, endDate);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("子单按季度分析失败，参数：startDate={}, endDate={}", startDate, endDate, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    @ApiOperation("按年范围分析子单任务")
    @GetMapping("/year")
    // 额外返回：时间范围内任务列表
    public ResponseEntity<OrderDetailAnalysisResult<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);
            }

            // 调用服务层：按年统计子单总量、设备/路线年度表现、载人特征变化
            OrderDetailAnalysisResult<List<YearlyStat>> result =
                    orderDetailAnalysisService.analyzeByYearRange(start, end);
            LOG.info("子单按年分析完成，时间范围：{}至{}", startDate, endDate);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            LOG.error("子单按年分析失败，参数：startDate={}, endDate={}", startDate, endDate, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    // 工具方法：复用原有季度日期转换逻辑
    private LocalDate getQuarterFirstDay(int year, int quarter) {
        int month = (quarter - 1) * 3 + 1;
        return LocalDate.of(year, month, 1);
    }

    private LocalDate getQuarterLastDay(int year, int quarter) {
        int month = quarter * 3;
        return LocalDate.of(year, month, 1).withDayOfMonth(LocalDate.of(year, month, 1).lengthOfMonth());
    }
}