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.utils.DateUtils;
import com.sundot.airport.ledger.domain.LedgerSeizureStats;
import com.sundot.airport.ledger.domain.vo.CountQueryReqVO;
import com.sundot.airport.ledger.domain.vo.CountSeizureSingleQuantityResVO;
import com.sundot.airport.ledger.domain.vo.CountSeizureTotalQuantityResVO;
import com.sundot.airport.ledger.domain.vo.LaneThroughputResVO;
import com.sundot.airport.ledger.domain.vo.SeizeCategoryQuantityVO;
import com.sundot.airport.ledger.domain.vo.SeizeItemVO;
import com.sundot.airport.ledger.domain.vo.SeizeTotalAndItemVO;
import com.sundot.airport.ledger.domain.vo.SeizureAreaVO;
import com.sundot.airport.ledger.mapper.LedgerSeizureStatsMapper;
import com.sundot.airport.ledger.service.ILedgerSeizureStatsService;
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.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;

    @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<CountSeizureSingleQuantityResVO> countSeizureSingleQuantity(CountQueryReqVO countQueryReq) {
        List<CountSeizureSingleQuantityResVO> seizureQuantityResList = this.baseMapper.countSeizureSingleQuantity(countQueryReq);
        seizureQuantityResList = CollUtil.emptyIfNull(seizureQuantityResList);

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

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

        // 将查询结果按日期建立映射（只比较日期部分，忽略时间）
        Map<String, CountSeizureSingleQuantityResVO> 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<CountSeizureSingleQuantityResVO> resultList = Lists.newArrayList();
        for (Date date : last30Days) {
            String dateKey = DateUtils.formatDateKey(date);
            if (dataMap.containsKey(dateKey)) {
                // 存在的日期，使用查询结果
                resultList.add(dataMap.get(dateKey));
            } else {
                // 缺失的日期，补充0数据
                CountSeizureSingleQuantityResVO countSeizureTotalQuantity = new CountSeizureSingleQuantityResVO(date, groupName);
                resultList.add(countSeizureTotalQuantity);
            }
        }
        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;
    }

    /**
     * 功能描述：查获物品分布
     *
     * @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);
    }
}
