package com.sundot.airport.web.controller.quality;

import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.statistics.TimeDimensionParams;
import com.sundot.airport.common.utils.DeptUtils;
import com.sundot.airport.item.domain.*;
import com.sundot.airport.item.domain.ItemLargeScreenInfoDto;
import com.sundot.airport.item.domain.ItemLargeScreenTimeSpanDto;
import com.sundot.airport.item.domain.dto.ChannelRankingStatsDTO;
import com.sundot.airport.item.domain.dto.ConcealmentPositionStatsDTO;
import com.sundot.airport.item.domain.dto.ItemCategoryStatsDTO;
import com.sundot.airport.item.domain.dto.PostCategoryStatsDTO;
import com.sundot.airport.item.domain.home.SeizureReportDTO;
import com.sundot.airport.item.service.IItemCategoryStatsService;
import com.sundot.airport.item.service.ItemLargeScreenService;
import com.sundot.airport.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 物品分类统计Controller
 * 提供物品分类统计相关接口
 *
 * @author wangxx
 * @date 2024-07-23
 */
@Slf4j
@RestController
@RequestMapping("/quality/item-category-stats")
@Api(tags = "物品分类统计")
public class ItemCategoryStatsController extends BaseController {

    @Autowired
    private ISysDeptService sysDeptService;


    @Autowired
    private IItemCategoryStatsService iItemCategoryStatsService;

    @Autowired
    private ItemLargeScreenService itemLargeScreenService;


    /**
     * 获取物品分类统计（全站整体数据）
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("获取物品分类统计")
    @GetMapping("/category-stats")
    public AjaxResult getItemCategoryStats(TimeDimensionParams params) {
        try {
            // 获取当前用户所在站点ID
            Long topSiteId = DeptUtils.getTopSiteId(sysDeptService.selectDeptById(getDeptId()));
            if (topSiteId == null) {
                return AjaxResult.error("无法找到有效的站点信息");
            }

            ItemCategoryStatsDTO stationCategoryStats = iItemCategoryStatsService.getStationCategoryStats(params, topSiteId);

            return AjaxResult.success("获取成功", stationCategoryStats);

        } catch (Exception e) {
            log.error("获取物品分类统计失败", e);
            return AjaxResult.error("获取物品分类统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取查获时段趋势图
     */
    @ApiOperation("获取查获时段趋势图")
    @GetMapping("/seizure-time-trend")
    public AjaxResult getSeizureTimeTrend(TimeDimensionParams params) {
        try {
            // 获取当前用户所在站点ID
            Long topSiteId = DeptUtils.getTopSiteId(sysDeptService.selectDeptById(getDeptId()));
            if (topSiteId == null) {
                return AjaxResult.error("无法找到有效的站点信息");
            }

            // 计算时间范围
            TimeDimensionParams timeParams = calculateTimeRange(params);
            BaseLargeScreenQueryParamDto dto = new BaseLargeScreenQueryParamDto();
            dto.setStartDate(timeParams.getStartTime());
            dto.setEndDate(timeParams.getEndTime());
            dto.setInspectStationId(topSiteId);
            // 设置大队、科室、班、人员筛选条件
            dto.setInspectBrigadeId(params.getBrigadeId());
            dto.setInspectDepartmentId(params.getDepartmentId());
            dto.setInspectTeamId(params.getTeamId());
            dto.setUserId(params.getUserId());
            List<ItemLargeScreenTimeSpanDto> result = itemLargeScreenService.appTimeSpan(dto);
            return AjaxResult.success("获取成功", result);

        } catch (Exception e) {
            log.error("获取查获时段趋势失败", e);
            return AjaxResult.error("获取查获时段趋势失败: " + e.getMessage());
        }
    }

    /**
     * 获取隐匿夹带部位分布统计（饼状图数据）
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("获取隐匿夹带部位分布统计")
    @GetMapping("/concealment-position-stats")
    public AjaxResult getConcealmentPositionStats(TimeDimensionParams params) {
        try {
            // 获取当前用户所在站点ID
            Long topSiteId = DeptUtils.getTopSiteId(sysDeptService.selectDeptById(getDeptId()));
            if (topSiteId == null) {
                return AjaxResult.error("无法找到有效的站点信息");
            }

            ConcealmentPositionStatsDTO stationConcealmentPositionStats =
                    iItemCategoryStatsService.getStationConcealmentPositionStats(params, topSiteId);

            return AjaxResult.success("获取成功", stationConcealmentPositionStats);

        } catch (Exception e) {
            log.error("获取隐匿夹带部位分布统计失败", e);
            return AjaxResult.error("获取隐匿夹带部位分布统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取岗位分类统计（饼状图数据）
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("获取岗位分类统计")
    @GetMapping("/post-category-stats")
    public AjaxResult getPostCategoryStats(TimeDimensionParams params) {
        try {
            // 获取当前用户所在站点ID
            Long topSiteId = DeptUtils.getTopSiteId(sysDeptService.selectDeptById(getDeptId()));
            if (topSiteId == null) {
                return AjaxResult.error("无法找到有效的站点信息");
            }

            PostCategoryStatsDTO stationPostCategoryStats =
                    iItemCategoryStatsService.getStationPostCategoryStats(params, topSiteId);

            return AjaxResult.success("获取成功", stationPostCategoryStats);

        } catch (Exception e) {
            log.error("获取岗位分类统计失败", e);
            return AjaxResult.error("获取岗位分类统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取通道排名统计（表格数据）
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("获取通道排名统计")
    @GetMapping("/channel-ranking-stats")
    public AjaxResult getChannelRankingStats(TimeDimensionParams params) {
        try {
            // 获取当前用户所在站点ID
            Long topSiteId = DeptUtils.getTopSiteId(sysDeptService.selectDeptById(getDeptId()));
            if (topSiteId == null) {
                return AjaxResult.error("无法找到有效的站点信息");
            }

            ChannelRankingStatsDTO stationChannelRankingStats =
                    iItemCategoryStatsService.getStationChannelRankingStats(params, topSiteId);

            return AjaxResult.success("获取成功", stationChannelRankingStats);

        } catch (Exception e) {
            log.error("获取通道排名统计失败", e);
            return AjaxResult.error("获取通道排名统计失败: " + e.getMessage());
        }
    }


    /**
     * 各大队查获排名
     */
    @ApiOperation("获取各大队查获排名")
    @GetMapping("/brigade-ranking")
    public AjaxResult getBrigadeRanking(TimeDimensionParams params) {
        List<SeizureReportDTO.BrigadeRankingItem> brigadeRankings = new ArrayList<>();
        try {
            // 获取当前用户所在站点ID
            Long topSiteId = DeptUtils.getTopSiteId(sysDeptService.selectDeptById(getDeptId()));
            if (topSiteId == null) {
                return AjaxResult.error("无法找到有效的站点信息");
            }
            brigadeRankings = iItemCategoryStatsService.getBrigadeRanking(topSiteId, params);
        } catch (Exception e) {
            log.error("获取各科室查获排名失败", e);
            return AjaxResult.error("获取各科室查获排名失败: " + e.getMessage());
        }
        return AjaxResult.success("获取成功", brigadeRankings);
    }


    /**
     * 计算时间范围
     */
    private TimeDimensionParams calculateTimeRange(TimeDimensionParams params) {
        TimeDimensionParams result = new TimeDimensionParams();

        if (params.getYear() != null) {
            // 按年、季度、月计算时间范围
            int year = params.getYear();
            int startMonth = 1;
            int endMonth = 12;

            if (params.getQuarter() != null) {
                // 按季度
                startMonth = (params.getQuarter() - 1) * 3 + 1;
                endMonth = startMonth + 2;
            } else if (params.getMonth() != null) {
                // 按月
                startMonth = params.getMonth();
                endMonth = params.getMonth();
            }

            Calendar cal = Calendar.getInstance();
            cal.set(year, startMonth - 1, 1, 0, 0, 0);
            result.setStartTime(cal.getTime());

            cal.set(year, endMonth - 1, cal.getActualMaximum(Calendar.DAY_OF_MONTH), 0, 0, 0);
            result.setEndTime(cal.getTime());
        } else {
            // 使用传入的时间范围
            result.setStartTime(params.getStartTime());
            result.setEndTime(params.getEndTime());
        }

        return result;
    }

    /**
     * 获取当前用户所在站点 ID
     */
    private Long getCurrentTopSiteId() {
        return DeptUtils.getTopSiteId(sysDeptService.selectDeptById(getDeptId()));
    }

    /**
     * 将 TimeDimensionParams 转换为 BaseLargeScreenQueryParamDto
     */
    private BaseLargeScreenQueryParamDto convertToQueryParamDto(TimeDimensionParams params) {
        BaseLargeScreenQueryParamDto dto = new BaseLargeScreenQueryParamDto();

        // 获取当前用户所在站点 ID
        Long topSiteId = getCurrentTopSiteId();
        if (topSiteId != null) {
            dto.setInspectStationId(topSiteId);
        }

        // 计算时间范围
        TimeDimensionParams timeParams = calculateTimeRange(params);
        dto.setStartDate(timeParams.getStartTime());
        dto.setEndDate(timeParams.getEndTime());

        // 设置大队、科室、班、人员筛选条件
        dto.setInspectBrigadeId(params.getBrigadeId());
        dto.setInspectDepartmentId(params.getDepartmentId());
        dto.setInspectTeamId(params.getTeamId());
        dto.setUserId(params.getUserId());

        return dto;
    }

    /**
     * 移交公安数据
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("移交公安数据")
    @GetMapping("/police-data")
    public AjaxResult getPoliceData(TimeDimensionParams params) {
        try {
            BaseLargeScreenQueryParamDto dto = convertToQueryParamDto(params);
            List<ItemLargeScreenInfoDto> result = itemLargeScreenService.police(dto);

            List<ItemLargeScreenPoliceGroupDto> tableData = result.stream().map(item -> {
                ItemLargeScreenPoliceGroupDto groupDto = new ItemLargeScreenPoliceGroupDto();
                groupDto.setBrigadeName(item.getInspectBrigadeName());
                groupDto.setDepartmentName(item.getInspectDepartmentName());
                groupDto.setTeamName(item.getInspectTeamName());
                groupDto.setUserName(item.getInspectUserName());
                groupDto.setItemName(item.getCategoryNameTwo());
                groupDto.setQuantity(item.getQuantity());

                // 查获部位拼接
                StringBuilder position = new StringBuilder();
                if (item.getCheckPositionNameOne() != null && !item.getCheckPositionNameOne().isEmpty()) {
                    position.append(item.getCheckPositionNameOne());
                }
                if (item.getCheckPositionNameTwo() != null && !item.getCheckPositionNameTwo().isEmpty()) {
                    if (position.length() > 0) {
                        position.append("/");
                    }
                    position.append(item.getCheckPositionNameTwo());
                }
                if (item.getCheckPositionSpecific() != null && !item.getCheckPositionSpecific().isEmpty()) {
                    if (position.length() > 0) {
                        position.append("/");
                    }
                    position.append(item.getCheckPositionSpecific());
                }
                groupDto.setPositionName(position.toString());
                groupDto.setSeizureTime(item.getSeizureTime());
                groupDto.setChannelName(item.getChannelName());
                return groupDto;
            }).collect(Collectors.toList());

            return AjaxResult.success("获取成功", tableData);
        } catch (Exception e) {
            log.error("获取移交公安数据失败", e);
            return AjaxResult.error("获取移交公安数据失败：" + e.getMessage());
        }
    }

    /**
     * 移交公安数据统计
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("移交公安数据统计")
    @GetMapping("/police-stats")
    public AjaxResult getPoliceStats(TimeDimensionParams params) {
        try {
            BaseLargeScreenQueryParamDto dto = convertToQueryParamDto(params);
            ItemLargeScreenPoliceStatsDto result = itemLargeScreenService.getPoliceStats(dto);
            return AjaxResult.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取移交公安数据统计失败", e);
            return AjaxResult.error("获取移交公安数据统计失败：" + e.getMessage());
        }
    }

    /**
     * X 光机漏检数据
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("X 光机漏检数据")
    @GetMapping("/xray-miss-check")
    public AjaxResult getXRayMissCheck(TimeDimensionParams params) {
        try {
            BaseLargeScreenQueryParamDto dto = convertToQueryParamDto(params);
            List<ItemXRayMissCheckDto> result = itemLargeScreenService.xRayMissCheck(dto);
            return AjaxResult.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取 X 光机漏检数据失败", e);
            return AjaxResult.error("获取 X 光机漏检数据失败：" + e.getMessage());
        }
    }

    /**
     * X 光机漏检人员统计 TOP3
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("X 光机漏检人员统计 TOP3")
    @GetMapping("/xray-miss-check-top3")
    public AjaxResult getXRayMissCheckTop3(TimeDimensionParams params) {
        try {
            BaseLargeScreenQueryParamDto dto = convertToQueryParamDto(params);
            List<ItemXRayMissCheckUserStatsDto> result = itemLargeScreenService.xRayMissCheckUserStatsTop3(dto);
            return AjaxResult.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取 X 光机漏检人员统计 TOP3 失败", e);
            return AjaxResult.error("获取 X 光机漏检人员统计 TOP3 失败：" + e.getMessage());
        }
    }

    /**
     * 异常查获数据
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("异常查获数据")
    @GetMapping("/abnormal-seizure-data")
    public AjaxResult getAbnormalSeizureData(TimeDimensionParams params) {
        try {
            BaseLargeScreenQueryParamDto dto = convertToQueryParamDto(params);
            List<ItemAbnormalSeizureDto> result = itemLargeScreenService.getAbnormalSeizureData(dto);
            return AjaxResult.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取异常查获数据失败", e);
            return AjaxResult.error("获取异常查获数据失败：" + e.getMessage());
        }
    }

    /**
     * 异常查获数据 TOP3（3 个高于 +3 个低于）
     * 支持按年、季度、月维度统计
     */
    @ApiOperation("异常查获数据 TOP3")
    @GetMapping("/abnormal-seizure-data-top3")
    public AjaxResult getAbnormalSeizureDataTop3(TimeDimensionParams params) {
        try {
            BaseLargeScreenQueryParamDto dto = convertToQueryParamDto(params);
            ItemAbnormalSeizureRankDto result = itemLargeScreenService.getAbnormalSeizureDataTop3(dto);
            return AjaxResult.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取异常查获数据 TOP3 失败", e);
            return AjaxResult.error("获取异常查获数据 TOP3 失败：" + e.getMessage());
        }
    }

}