package com.sundot.airport.ledger.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.enums.DeptTypeEnum;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.ledger.domain.LedgerSeizureStats;
import com.sundot.airport.ledger.domain.vo.*;
import com.sundot.airport.ledger.mapper.LedgerSeizureStatsMapper;
import com.sundot.airport.ledger.service.ILedgerSeizureStatsService;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 查获违规品统计Service实现
 */
@Slf4j
@Service
public class LedgerSeizureStatsServiceImpl extends ServiceImpl<LedgerSeizureStatsMapper, LedgerSeizureStats> implements ILedgerSeizureStatsService {

    @Autowired
    private LedgerSeizureStatsMapper mapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;



    @Override
    public List<LedgerSeizureStats> selectList(LedgerSeizureStats query) {
        return mapper.selectList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchInsert(List<LedgerSeizureStats> list) {
        list.forEach(item -> item.setCreateTime(DateUtils.getNowDate()));
        saveBatch(list);
        return list.size();
    }

    /**
     * 功能描述：近30天查获数量（总表）
     *
     * @param countQueryReq 查询参数
     * @return List<CountSeizureQuantityResVO>
     * @method countSeizureTotalQuantity
     * @author PanHu Sun
     * @date 2026/5/20 10:43
     */
    @Override
    public List<CountSeizureTotalQuantityResVO> countSeizureTotalQuantity(CountQueryReqVO countQueryReq) {
        List<CountSeizureTotalQuantityResVO> seizureQuantityResList = this.baseMapper.countSeizureTotalQuantity(countQueryReq);
        seizureQuantityResList = CollUtil.emptyIfNull(seizureQuantityResList);

        log.info("SQL查询返回数据条数: {}", seizureQuantityResList.size());

        // 生成近30天的日期列表
        List<Date> last30Days = DateUtils.generateLast30Days();

        // 将查询结果按日期建立映射（只比较日期部分，忽略时间）
        Map<String, CountSeizureTotalQuantityResVO> dataMap = seizureQuantityResList.stream()
                .collect(Collectors.toMap(
                        vo -> DateUtils.formatDateKey(vo.getRecordDate()),
                        vo -> vo,
                        (existing, replacement) -> existing
                ));

        log.info("数据Map中的日期键: {}", dataMap.keySet());

        // 获取小组名称
        String groupName = "";
        if (CollUtil.isNotEmpty(seizureQuantityResList)) {
            groupName = seizureQuantityResList.get(0).getGroupName();
        }

        // 补齐缺失的日期数据
        List<CountSeizureTotalQuantityResVO> resultList = Lists.newArrayList();
        for (Date date : last30Days) {
            String dateKey = DateUtils.formatDateKey(date);
            if (dataMap.containsKey(dateKey)) {
                // 存在的日期，使用查询结果
                resultList.add(dataMap.get(dateKey));
            } else {
                // 缺失的日期，补充0数据
                CountSeizureTotalQuantityResVO countSeizureTotalQuantity = new CountSeizureTotalQuantityResVO(date, groupName);
                resultList.add(countSeizureTotalQuantity);
            }
        }
        return resultList;
    }

    /**
     * 功能描述：近30天查获数量（员工/小组/班组/部门）
     *
     * @param countQueryReq 查询参数
     * @return List<CountSeizureSingleQuantityResVO>
     * @method countSeizureSingleQuantity
     * @author PanHu Sun
     * @date 2026/5/20 10:43
     */
    @Override
    public List<CountSeizureSingleQuantityDateResVO> countSeizureSingleQuantity(CountQueryReqVO countQueryReq) {
        List<CountSeizureSingleQuantityResVO> allData =  Lists.newArrayList();;
        List<Date> dateRange = generateDateRange(countQueryReq.getStartDate(), countQueryReq.getEndDate());
        
        if (countQueryReq.getGroupId() != null) {
            allData = handleGroupLevelQuery(countQueryReq, dateRange);
        } else if (countQueryReq.getTeamId() != null) {
            allData = handleTeamLevelQuery(countQueryReq, dateRange);
        } else if (countQueryReq.getDeptId() != null) {
            allData = handleDeptLevelQuery(countQueryReq, dateRange);
        } else {
            allData = handleStationLevelQuery(countQueryReq, dateRange);
        }

        // 按日期分组
        Map<String, List<CountSeizureSingleQuantityResVO>> groupedByDate = allData.stream()
                .collect(Collectors.groupingBy(vo -> DateUtils.formatDateKey(vo.getRecordDate())));

        // 构建返回结果：每个日期对应一个对象，包含该日期下所有维度的查获数量
        List<CountSeizureSingleQuantityDateResVO> resultList = Lists.newArrayList();
        for (Date date : dateRange) {
            String dateKey = DateUtils.formatDateKey(date);
            CountSeizureSingleQuantityDateResVO dateResult = new CountSeizureSingleQuantityDateResVO();
            dateResult.setRecordDate(date);

            List<CountSeizureSingleQuantityResVO> dayData = groupedByDate.get(dateKey);
            if (CollUtil.isNotEmpty(dayData)) {
                List<CountSeizureSingleQuantityDateResVO.SeizureItem> items = dayData.stream()
                        .map(vo -> new CountSeizureSingleQuantityDateResVO.SeizureItem(vo.getGroupName(), vo.getSeizeQuantity()))
                        .collect(Collectors.toList());
                dateResult.setItems(items);
            } else {
                dateResult.setItems(Lists.newArrayList());
            }
            resultList.add(dateResult);
        }

        return resultList;
    }
    
    /**
     * 小组级别查询：获取小组下的人，按时间返回人的查获数
     */
    private List<CountSeizureSingleQuantityResVO> handleGroupLevelQuery(CountQueryReqVO countQueryReq, List<Date> dateRange) {
        List<CountSeizureSingleQuantityResVO> resultList = Lists.newArrayList();
        
        SysDept groupDept = sysDeptService.selectDeptById(countQueryReq.getGroupId());
        String groupName = (groupDept != null) ? groupDept.getDeptName() : "小组" + countQueryReq.getGroupId();
        
        List<SysUser> members = sysUserService.selectUserByDeptId(countQueryReq.getGroupId());
        if (CollUtil.isEmpty(members)) {
            for (Date date : dateRange) {
                resultList.add(new CountSeizureSingleQuantityResVO(date, groupName));
            }
            return resultList;
        }

        CountQueryReqVO queryReq = new CountQueryReqVO();
        queryReq.setStartDate(countQueryReq.getStartDate());
        queryReq.setEndDate(countQueryReq.getEndDate());
        queryReq.setGroupId(countQueryReq.getGroupId());
        List<CountSeizureSingleQuantityResVO> memberData = this.baseMapper.countSeizureSingleQuantity(queryReq);
        Map<String, CountSeizureSingleQuantityResVO> dataMap = memberData.stream()
                .collect(Collectors.toMap(
                        vo -> (DateUtils.formatDateKey(vo.getRecordDate())+"_"+vo.getGroupName()),
                        vo -> vo,
                        (existing, replacement) -> existing
                ));
        for (SysUser member : members) {
            memberData = CollUtil.emptyIfNull(memberData);
            for (Date date : dateRange) {
                String dateKey = DateUtils.formatDateKey(date)+"_"+member.getNickName();
                if (dataMap.containsKey(dateKey)) {
                    CountSeizureSingleQuantityResVO vo = dataMap.get(dateKey);
                    vo.setGroupName(member.getNickName());
                    resultList.add(vo);
                } else {
                    resultList.add(new CountSeizureSingleQuantityResVO(date, member.getNickName()));
                }
            }
        }
        
        return resultList;
    }
    
    /**
     * 班组级别查询：获取班组下的小组，按时间返回小组的查获数
     */
    private List<CountSeizureSingleQuantityResVO> handleTeamLevelQuery(CountQueryReqVO countQueryReq, List<Date> dateRange) {
        List<CountSeizureSingleQuantityResVO> resultList = Lists.newArrayList();
        
        SysDept teamDept = sysDeptService.selectDeptById(countQueryReq.getTeamId());
        String teamName = (teamDept != null) ? teamDept.getDeptName() : "班组" + countQueryReq.getTeamId();
        
        List<SysDept> groups = sysDeptService.selectChildrenDeptById(countQueryReq.getTeamId());
        if (CollUtil.isEmpty(groups)) {
            for (Date date : dateRange) {
                resultList.add(new CountSeizureSingleQuantityResVO(date, teamName));
            }
            return resultList;
        }
        groups = groups.stream().filter(team -> DeptTypeEnum.TEAMS.getCode().equals(team.getDeptType())).collect(Collectors.toList());

        CountQueryReqVO queryReq = new CountQueryReqVO();
        queryReq.setStartDate(countQueryReq.getStartDate());
        queryReq.setEndDate(countQueryReq.getEndDate());
        queryReq.setTeamId(countQueryReq.getTeamId());
        List<CountSeizureSingleQuantityResVO> groupData = this.baseMapper.countSeizureSingleQuantity(queryReq);
        groupData = CollUtil.emptyIfNull(groupData);
        Map<String, CountSeizureSingleQuantityResVO> dataMap = groupData.stream()
                .collect(Collectors.toMap(
                        vo -> (DateUtils.formatDateKey(vo.getRecordDate())+"_"+vo.getGroupName()),
                        vo -> vo,
                        (existing, replacement) -> existing
                ));
        
        for (SysDept group : groups) {
            for (Date date : dateRange) {
                String dateKey = DateUtils.formatDateKey(date)+"_"+group.getDeptName();
                if (dataMap.containsKey(dateKey)) {
                    CountSeizureSingleQuantityResVO vo = dataMap.get(dateKey);
                    vo.setGroupName(group.getDeptName());
                    resultList.add(vo);
                } else {
                    resultList.add(new CountSeizureSingleQuantityResVO(date, group.getDeptName()));
                }
            }
        }
        
        return resultList;
    }
    
    /**
     * 部门级别查询：获取部门下的班组，按时间返回班组的查获数
     */
    private List<CountSeizureSingleQuantityResVO> handleDeptLevelQuery(CountQueryReqVO countQueryReq, List<Date> dateRange) {
        List<CountSeizureSingleQuantityResVO> resultList = Lists.newArrayList();
        
        SysDept dept = sysDeptService.selectDeptById(countQueryReq.getDeptId());
        String deptName = (dept != null) ? dept.getDeptName() : "部门" + countQueryReq.getDeptId();
        
        List<SysDept> teams = sysDeptService.selectChildrenDeptById(countQueryReq.getDeptId());
        if (CollUtil.isEmpty(teams)) {
            for (Date date : dateRange) {
                resultList.add(new CountSeizureSingleQuantityResVO(date, deptName));
            }
            return resultList;
        }
        //部门只要班组的
        teams = teams.stream().filter(team -> DeptTypeEnum.MANAGER.getCode().equals(team.getDeptType())).collect(Collectors.toList());
        CountQueryReqVO queryReq = new CountQueryReqVO();
        queryReq.setStartDate(countQueryReq.getStartDate());
        queryReq.setEndDate(countQueryReq.getEndDate());
        queryReq.setDeptId(countQueryReq.getDeptId());
        List<CountSeizureSingleQuantityResVO> teamData = this.baseMapper.countSeizureSingleQuantity(queryReq);
        for (SysDept team : teams) {
            teamData = CollUtil.emptyIfNull(teamData);
            Map<String, CountSeizureSingleQuantityResVO> dataMap = teamData.stream()
                    .collect(Collectors.toMap(
                            vo -> (DateUtils.formatDateKey(vo.getRecordDate())+"_"+vo.getGroupName()),
                            vo -> vo,
                            (existing, replacement) -> existing
                    ));
            
            for (Date date : dateRange) {
                String dateKey = DateUtils.formatDateKey(date)+"_"+team.getDeptName();
                if (dataMap.containsKey(dateKey)) {
                    CountSeizureSingleQuantityResVO vo = dataMap.get(dateKey);
                    vo.setGroupName(team.getDeptName());
                    resultList.add(vo);
                } else {
                    resultList.add(new CountSeizureSingleQuantityResVO(date, team.getDeptName()));
                }
            }
        }
        
        return resultList;
    }
    
    /**
     * 站级别查询：获取站下的大队，按时间返回大队的查获数
     */
    private List<CountSeizureSingleQuantityResVO> handleStationLevelQuery(CountQueryReqVO countQueryReq, List<Date> dateRange) {
        List<CountSeizureSingleQuantityResVO> resultList = Lists.newArrayList();
        
        SysDept stationDept = new SysDept();
        stationDept.setStatus("0");
        stationDept.setDeptType("STATION");
        List<SysDept> stationList = sysDeptService.selectDeptList(stationDept);
        
        if (CollUtil.isEmpty(stationList)) {
            return resultList;
        }
        
        SysDept station = stationList.get(0);
        
        SysDept brigadeDept = new SysDept();
        brigadeDept.setStatus("0");
        brigadeDept.setDeptType("BRIGADE");
        List<SysDept> allBrigades = sysDeptService.selectDeptList(brigadeDept);
        
        List<SysDept> brigades = allBrigades.stream()
                .filter(b -> b.getParentId() != null && b.getParentId().equals(station.getDeptId()))
                .collect(Collectors.toList());
        
        if (CollUtil.isEmpty(brigades)) {
            for (Date date : dateRange) {
                resultList.add(new CountSeizureSingleQuantityResVO(date, "站"));
            }
            return resultList;
        }

        CountQueryReqVO queryReq = new CountQueryReqVO();
        queryReq.setStartDate(countQueryReq.getStartDate());
        queryReq.setEndDate(countQueryReq.getEndDate());
        List<CountSeizureSingleQuantityResVO> brigadeData = this.baseMapper.countSeizureSingleQuantity(queryReq);
        brigadeData = CollUtil.emptyIfNull(brigadeData);

        Map<String, CountSeizureSingleQuantityResVO> dataMap = brigadeData.stream()
                .collect(Collectors.toMap(
                        vo -> DateUtils.formatDateKey(vo.getRecordDate()) + "_" + vo.getGroupName(),
                        vo -> vo,
                        (existing, replacement) -> existing
                ));
        
        for (SysDept brigade : brigades) {
            for (Date date : dateRange) {
                String dateKey = DateUtils.formatDateKey(date) + "_" + brigade.getDeptName();
                if (dataMap.containsKey(dateKey)) {
                    CountSeizureSingleQuantityResVO vo = dataMap.get(dateKey);
                    vo.setGroupName(brigade.getDeptName());
                    resultList.add(vo);
                } else {
                    resultList.add(new CountSeizureSingleQuantityResVO(date, brigade.getDeptName()));
                }
            }
        }
        
        return resultList;
    }

    /**
     * 功能描述：查获信息展示
     *
     * @param countQueryReq 查询参数
     * @return SeizeTotalAndItemVO
     * @method getTimeRangeStats
     * @author PanHu Sun
     * @date 2026/5/20 13:43
     */
    @Override
    public SeizeTotalAndItemVO getTimeRangeStats(CountQueryReqVO countQueryReq) {
        SeizeTotalAndItemVO result = new SeizeTotalAndItemVO();
        // 总查获数
        Integer total = this.baseMapper.statsTimeRangeTotal(countQueryReq);
        result.setTotalSeizeNum(total);
        // 柱状明细
        List<SeizeItemVO> itemList = this.baseMapper.statsTimeRangeItem(countQueryReq);
        result.setItemList(itemList);
        return result;
    }


    /**
     * 生成日期范围列表
     */
    private List<Date> generateDateRange(Date startDate, Date endDate) {
        List<Date> dateList = Lists.newArrayList();

        Calendar startCal = Calendar.getInstance();
        startCal.setTime(startDate);

        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endDate);

        while (!startCal.getTime().after(endCal.getTime())) {
            dateList.add(startCal.getTime());
            startCal.add(Calendar.DAY_OF_MONTH, 1);
        }

        return dateList;
    }

    /**
     * 功能描述：查获物品分布
     *
     * @param countQueryReq 查询参数
     * @return List<SeizeCategoryQuantityVO>
     * @method countSeizeSubjectItemQuantity
     * @author PanHu Sun
     * @date 2026/5/20 14:46
     */
    @Override
    public List<SeizeCategoryQuantityVO> countSeizeSubjectItemQuantity(CountQueryReqVO countQueryReq) {
        // 无数据自动返回空数组，符合需求
        List<SeizeCategoryQuantityVO> seizeCategoryQuantityList = this.baseMapper.countSeizeSubjectItemQuantity(countQueryReq);
        return CollUtil.emptyIfNull(seizeCategoryQuantityList);
    }

    /**
     * 功能描述：查获工作区域分布
     *
     * @param countQueryReq 查询参数
     * @return List<SeizureAreaVO>
     * @method countSeizeAreaQuantity
     * @author PanHu Sun
     * @date 2026/5/20 15:12
     */
    @Override
    public List<SeizureAreaVO> countSeizeAreaQuantity(CountQueryReqVO countQueryReq) {
        // 无数据自动返回空数组，符合需求
        List<SeizureAreaVO> seizureAreaList = this.baseMapper.countSeizeAreaQuantity(countQueryReq);
        return CollUtil.emptyIfNull(seizureAreaList);
    }
}