package com.rj.controller.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.CpaBrandScoreStatistics;
import com.rj.scheduler.CpaBrandCoreScheduler;
import com.rj.service.biz.ICpaBrandScoreStatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 经销商品牌得分统计表 前端控制器
 * 
 * @author 李中华
 * @date 2025/1/15
 */
@Slf4j
@RestController
@RequestMapping("/api/cpa-brand-score-statistics")
@Tag(name = "经销商品牌得分统计", description = "经销商品牌得分统计相关接口")
public class CpaBrandScoreStatisticsController {

    @Autowired
    private ICpaBrandScoreStatisticsService cpaBrandScoreStatisticsService;

    @Autowired
    private CpaBrandCoreScheduler cpaBrandCoreScheduler;

    /**
     * 分页查询统计数据
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询统计数据", description = "根据条件分页查询经销商品牌得分统计数据")
    public ResponseEntity<Map<String, Object>> getStatisticsList(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "经销商编码（模糊查询）") @RequestParam(required = false) String dealerCode,
            @Parameter(description = "经销商名称（模糊查询）") @RequestParam(required = false) String dealerName,
            @Parameter(description = "大区") @RequestParam(required = false) String bigArea,
            @Parameter(description = "统计类型") @RequestParam(required = false) String statisticsType,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        log.info("分页查询统计数据，经销商编码={},经销商名称={},大区={},统计类型={},开始日期={},结束日期={}", 
                dealerCode, dealerName, bigArea, statisticsType, startDate, endDate);

        Map<String,Object> result = new HashMap<>();
        try {
            Page<CpaBrandScoreStatistics> page = new Page<>(current, size);
            LambdaQueryWrapper<CpaBrandScoreStatistics> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (dealerCode != null && !dealerCode.trim().isEmpty()) {
                queryWrapper.like(CpaBrandScoreStatistics::getDealerCode, dealerCode);
            }
            if (dealerName != null && !dealerName.trim().isEmpty()) {
                queryWrapper.like(CpaBrandScoreStatistics::getDealerName, dealerName);
            }
            if (bigArea != null && !bigArea.trim().isEmpty()) {
                queryWrapper.eq(CpaBrandScoreStatistics::getBigArea, bigArea);
            }
            if (statisticsType != null && !statisticsType.trim().isEmpty()) {
                queryWrapper.eq(CpaBrandScoreStatistics::getStatisticsType, statisticsType);
            }
            if (startDate != null) {
                queryWrapper.ge(CpaBrandScoreStatistics::getStatisticsDate, startDate);
            }
            if (endDate != null) {
                queryWrapper.le(CpaBrandScoreStatistics::getStatisticsDate, endDate);
            }
            
            // 只查询未删除的记录
            queryWrapper.eq(CpaBrandScoreStatistics::getIsDeleted, 0);
            
            // 按平均得分百分比和总得分倒序排列
            queryWrapper.orderByDesc(CpaBrandScoreStatistics::getAverageScorePercentage)
                       .orderByDesc(CpaBrandScoreStatistics::getTotalScore);
            
            Page<CpaBrandScoreStatistics> statisticsPage = cpaBrandScoreStatisticsService.page(page, queryWrapper);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", statisticsPage.getRecords());
            result.put("total", statisticsPage.getTotal());
            result.put("current", statisticsPage.getCurrent());
            result.put("size", statisticsPage.getSize());
            result.put("pages", statisticsPage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("分页查询统计数据失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据条件查询统计数据（不分页）
     */
    @GetMapping("/query")
    @Operation(summary = "根据条件查询统计数据", description = "根据经销商编码、大区、统计类型等条件查询统计数据（不分页）")
    public ResponseEntity<Map<String, Object>> getList(
            @Parameter(description = "经销商编码") @RequestParam(required = false) String dealerCode,
            @Parameter(description = "大区") @RequestParam(required = false) String bigArea,
            @Parameter(description = "统计类型") @RequestParam(required = false) String statisticsType,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            List<CpaBrandScoreStatistics> statisticsList = cpaBrandScoreStatisticsService.getByCondition(
                    dealerCode, bigArea, statisticsType, startDate, endDate);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", statisticsList);
            result.put("total", statisticsList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("根据条件查询统计数据失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID查询统计数据
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询统计数据", description = "根据主键ID查询单条统计数据")
    public ResponseEntity<Map<String, Object>> getById(
            @Parameter(description = "主键ID", required = true) @PathVariable String id) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            CpaBrandScoreStatistics statistics = cpaBrandScoreStatisticsService.getById(id);
            if (statistics != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", statistics);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "数据不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据ID查询统计数据失败", e);
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 新增统计数据
     */
    @PostMapping("/add")
    @Operation(summary = "新增统计数据", description = "新增一条经销商品牌得分统计数据")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "统计数据", required = true) @Valid @RequestBody CpaBrandScoreStatistics statistics) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = cpaBrandScoreStatisticsService.save(statistics);
            if (success) {
                result.put("success", true);
                result.put("message", "新增成功");
                result.put("data", statistics);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "新增失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("新增统计数据失败", e);
            result.put("success", false);
            result.put("message", "新增失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 修改统计数据
     */
    @PutMapping("/update")
    @Operation(summary = "修改统计数据", description = "修改经销商品牌得分统计数据")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "统计数据", required = true) @Valid @RequestBody CpaBrandScoreStatistics statistics) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = cpaBrandScoreStatisticsService.updateById(statistics);
            if (success) {
                result.put("success", true);
                result.put("message", "修改成功");
                result.put("data", statistics);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "修改失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("修改统计数据失败", e);
            result.put("success", false);
            result.put("message", "修改失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 删除统计数据
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除统计数据", description = "根据ID删除经销商品牌得分统计数据")
    public ResponseEntity<Map<String, Object>> delete(
            @Parameter(description = "主键ID", required = true) @PathVariable String id) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = cpaBrandScoreStatisticsService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("删除统计数据失败", e);
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取经销商排名
     */
    @GetMapping("/ranking/dealer")
    @Operation(summary = "获取经销商排名", description = "获取经销商品牌得分排名统计")
    public ResponseEntity<Map<String, Object>> getDealerRanking(
            @Parameter(description = "统计类型") @RequestParam(required = false) String statisticsType,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            List<Map<String, Object>> rankingList = cpaBrandScoreStatisticsService.getDealerRanking(statisticsType, limit);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", rankingList);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取经销商排名失败", e);
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取大区排名
     */
    @GetMapping("/ranking/big-area")
    @Operation(summary = "获取大区排名", description = "获取大区品牌得分排名统计")
    public ResponseEntity<Map<String, Object>> getBigAreaRanking(
            @Parameter(description = "统计类型") @RequestParam(required = false) String statisticsType) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            List<Map<String, Object>> rankingList = cpaBrandScoreStatisticsService.getBigAreaRanking(statisticsType);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", rankingList);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取大区排名失败", e);
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取统计概览
     */
    @GetMapping("/overview")
    @Operation(summary = "获取统计概览", description = "获取经销商品牌得分统计概览数据")
    public ResponseEntity<Map<String, Object>> getOverview(
            @Parameter(description = "统计类型") @RequestParam(required = false) String statisticsType,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> overview = cpaBrandScoreStatisticsService.getStatisticsOverview(statisticsType, startDate, endDate);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", overview);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取统计概览失败", e);
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 生成统计数据
     * # 触发日统计
     * POST /api/cpa-brand-score-statistics/trigger-scheduler?statisticsType=daily&date=2025-01-14
     *
     * # 触发周统计
     * POST /api/cpa-brand-score-statistics/trigger-scheduler?statisticsType=weekly&startDate=2025-01-06&endDate=2025-01-12
     *
     * # 触发月统计
     * POST /api/cpa-brand-score-statistics/trigger-scheduler?statisticsType=monthly&startDate=2024-12-01&endDate=2024-12-31
     *
     * # 触发总计统计
     * POST /api/cpa-brand-score-statistics/trigger-scheduler?statisticsType=total
     */
    @PostMapping("/generate")
    @Operation(summary = "生成统计数据", description = "根据指定条件生成经销商品牌得分统计数据")
    public ResponseEntity<Map<String, Object>> generateStatistics(
            @Parameter(description = "统计类型", required = true) @RequestParam String statisticsType,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "创建人") @RequestParam(defaultValue = "system") String createdBy) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            int count = cpaBrandScoreStatisticsService.generateAndSaveStatistics(statisticsType, startDate, endDate, createdBy);
            
            result.put("success", true);
            result.put("message", "生成统计数据成功");
            result.put("data", Map.of("generatedCount", count));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("生成统计数据失败", e);
            result.put("success", false);
            result.put("message", "生成失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 手动触发调度器统计任务
     * 
     * @param statisticsType 统计类型：daily, weekly, monthly, total
     * @param date 统计日期（可选，用于daily类型）
     * @param startDate 开始日期（可选，用于weekly/monthly类型）
     * @param endDate 结束日期（可选，用于weekly/monthly类型）
     * @return 执行结果
     */
    @PostMapping("/trigger-scheduler")
    @Operation(summary = "手动触发调度器统计任务", description = "手动触发调度器执行统计任务，支持daily、weekly、monthly、total类型")
    public ResponseEntity<Map<String, Object>> triggerScheduler(
            @RequestParam String statisticsType,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("手动触发调度器统计任务，类型：{}，日期：{}，范围：{} - {}", statisticsType, date, startDate, endDate);
            
            int count = 0;
            
            if ("daily".equals(statisticsType)) {
                if (date == null) {
                    date = LocalDate.now().minusDays(1);
                }
                count = cpaBrandCoreScheduler.manualGenerateStatistics(date, statisticsType);
            } else if ("weekly".equals(statisticsType) || "monthly".equals(statisticsType)) {
                if (startDate == null || endDate == null) {
                    throw new IllegalArgumentException("周统计或月统计需要提供开始日期和结束日期");
                }
                count = cpaBrandCoreScheduler.manualGenerateStatisticsByRange(startDate, endDate, statisticsType);
            } else if ("total".equals(statisticsType)) {
                count = cpaBrandCoreScheduler.manualGenerateStatisticsByRange(null, null, statisticsType);
            } else {
                throw new IllegalArgumentException("不支持的统计类型：" + statisticsType);
            }
            
            result.put("success", true);
            result.put("message", "调度器统计任务执行成功");
            Map<String, Object> reMap = new HashMap<>();
            reMap.put("statisticsType", statisticsType);
            reMap.put("generatedCount", count);
            reMap.put("date", date);
            reMap.put("startDate", startDate);
            reMap.put("endDate", endDate);
            result.put("data", reMap);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("手动触发调度器统计任务失败", e);
            result.put("success", false);
            result.put("message", "执行失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
}
