package com.rj.controller;

import com.rj.common.Result;
import com.rj.entity.AudioManagementStatistics;
import com.rj.scheduler.AudioStatisticsScheduler;
import com.rj.service.IAudioManagementStatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 门店录音统计控制器
 * 
 * @author 李中华 ,spllzh
 * @since 2025-08-07
 */
@Tag(name = "门店录音统计", description = "门店录音统计相关接口")
@RestController
@RequestMapping("/api/audio-statistics")
public class AudioStatisticsController {

    @Autowired
    private IAudioManagementStatisticsService audioStatisticsService;

    @Autowired
    private AudioStatisticsScheduler audioStatisticsScheduler;

    /**
     * 手动生成指定日期的统计数据
     */
    @Operation(summary = "手动生成指定日期的统计数据", description = "手动触发指定日期的门店录音统计")
    @PostMapping("/generate")
    public Result<?> generateStatistics(
            @Parameter(description = "统计日期，格式：yyyy-MM-dd") 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        try {
            int count = audioStatisticsScheduler.manualGenerateStatistics(date);
            Result<?> result = Result.ok(count);
            result.setMsg("统计生成成功");
            return result;
        } catch (Exception e) {
            return Result.error("统计生成失败：" + e.getMessage());
        }
    }

    /**
     * 查询指定日期范围的统计数据
     */
    @Operation(summary = "查询指定日期范围的统计数据", description = "查询指定日期范围内的门店录音统计数据")
    @GetMapping("/range")
    public Result<?> getStatisticsByDateRange(
            @Parameter(description = "开始日期，格式：yyyy-MM-dd") 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期，格式：yyyy-MM-dd") 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        try {
            List<AudioManagementStatistics> statistics = audioStatisticsService.getStatisticsByDateRange(startDate, endDate);
            Result<?> result = Result.ok(statistics);
            result.setMsg("查询成功");
            return result;
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询指定门店的统计数据
     */
    @Operation(summary = "查询指定门店的统计数据", description = "查询指定门店在指定日期范围内的录音统计数据")
    @GetMapping("/dealership/{dealershipId}")
    public Result<?> getStatisticsByDealership(
            @Parameter(description = "门店ID") 
            @PathVariable Long dealershipId,
            @Parameter(description = "开始日期，格式：yyyy-MM-dd") 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期，格式：yyyy-MM-dd") 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        try {
            List<AudioManagementStatistics> statistics = audioStatisticsService.getStatisticsByDealership(dealershipId, startDate, endDate);
            Result<?> result = Result.ok(statistics);
            result.setMsg("查询成功");
            return result;
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询指定销售人员的统计数据
     */
    @Operation(summary = "查询指定销售人员的统计数据", description = "根据销售人员ID或电话号码查询指定日期范围内的录音统计数据")
    @PostMapping("/sales")
    public Result<?> getStatisticsBySales(
            @Parameter(description = "销售人员ID") 
            @RequestParam(required = false) String salesId,
            @Parameter(description = "销售人员电话号码") 
            @RequestParam(required = false) String salesPhone,
            @Parameter(description = "日期范围类型：1=1个月，2=3个月，3=6个月") 
            @RequestParam Integer dateRangeType) {
        try {
            // 验证参数：至少提供一个查询条件
            if ((salesId == null || salesId.trim().isEmpty()) && 
                (salesPhone == null || salesPhone.trim().isEmpty())) {
                return Result.error("销售人员ID和电话号码至少需要提供一个");
            }
            
            // 验证日期范围类型
            if (dateRangeType == null || (dateRangeType != 1 && dateRangeType != 2 && dateRangeType != 3)) {
                return Result.error("日期范围类型必须为1（1个月）、2（3个月）或3（6个月）");
            }
            
            // 根据日期范围类型计算开始和结束日期
            LocalDate endDate = LocalDate.now().minusDays(1); // 昨天
            LocalDate startDate;
            switch (dateRangeType) {
                case 1:
                    startDate = endDate.minusMonths(1); // 1个月前
                    break;
                case 2:
                    startDate = endDate.minusMonths(3); // 3个月前
                    break;
                case 3:
                    startDate = endDate.minusMonths(6); // 6个月前
                    break;
                default:
                    return Result.error("日期范围类型无效");
            }
            
            List<AudioManagementStatistics> statistics = audioStatisticsService.getStatisticsBySales(salesId, salesPhone, startDate, endDate);
            Result<?> result = Result.ok(statistics);
            result.setMsg("查询成功");
            return result;
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }



    /**
     * 查询指定日期的统计数据
     */
    @Operation(summary = "查询指定日期的统计数据", description = "查询指定日期的所有门店录音统计数据")
    @GetMapping("/date/{date}")
    public Result<?> getStatisticsByDate(
            @Parameter(description = "统计日期，格式：yyyy-MM-dd") 
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        try {
            List<AudioManagementStatistics> statistics = audioStatisticsService.getStatisticsByDateRange(date, date);
            Result<?> result = Result.ok(statistics);
            result.setMsg("查询成功");
            return result;
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取统计概览（最近7天）
     */
    @Operation(summary = "获取统计概览", description = "获取最近7天的门店录音统计概览")
    @GetMapping("/overview")
    public Result<?> getStatisticsOverview() {
        try {
            LocalDate endDate = LocalDate.now().minusDays(1); // 昨天
            LocalDate startDate = endDate.minusDays(6); // 7天前
            List<AudioManagementStatistics> statistics = audioStatisticsService.getStatisticsByDateRange(startDate, endDate);
            Result<?> result = Result.ok(statistics);
            result.setMsg("查询成功");
            return result;
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }
}