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.OperationLanePeakThroughput;
import com.sundot.airport.ledger.domain.vo.CountQueryReqVO;
import com.sundot.airport.ledger.domain.vo.LaneThroughputResVO;
import com.sundot.airport.ledger.mapper.OperationLanePeakThroughputMapper;
import com.sundot.airport.ledger.service.IOperationLanePeakThroughputService;
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.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 通道日别高峰时段过检Service业务层处理
 */
@Slf4j
@Service
public class OperationLanePeakThroughputServiceImpl extends ServiceImpl<OperationLanePeakThroughputMapper, OperationLanePeakThroughput>
        implements IOperationLanePeakThroughputService {

    @Autowired
    private OperationLanePeakThroughputMapper operationLanePeakThroughputMapper;

    /**
     * 查询通道日别高峰时段过检列表
     *
     * @param operationLanePeakThroughput 通道日别高峰时段过检
     * @return 通道日别高峰时段过检
     */
    @Override
    public List<OperationLanePeakThroughput> selectOperationLanePeakThroughputList(OperationLanePeakThroughput operationLanePeakThroughput) {
        return operationLanePeakThroughputMapper.selectOperationLanePeakThroughputList(operationLanePeakThroughput);
    }

    /**
     * 新增通道日别高峰时段过检
     *
     * @param operationLanePeakThroughput 通道日别高峰时段过检
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertOperationLanePeakThroughput(OperationLanePeakThroughput operationLanePeakThroughput) {
        operationLanePeakThroughput.setCreateTime(DateUtils.getNowDate());
        return operationLanePeakThroughputMapper.insert(operationLanePeakThroughput);
    }

    /**
     * 修改通道日别高峰时段过检
     *
     * @param operationLanePeakThroughput 通道日别高峰时段过检
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOperationLanePeakThroughput(OperationLanePeakThroughput operationLanePeakThroughput) {
        operationLanePeakThroughput.setUpdateTime(DateUtils.getNowDate());
        return operationLanePeakThroughputMapper.updateById(operationLanePeakThroughput);
    }

    /**
     * 批量删除通道日别高峰时段过检
     *
     * @param ids 需要删除的通道日别高峰时段过检主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOperationLanePeakThroughputByIds(Long[] ids) {
        return operationLanePeakThroughputMapper.deleteBatchIds(java.util.Arrays.asList(ids));
    }

    /**
     * 删除通道日别高峰时段过检信息
     *
     * @param id 通道日别高峰时段过检主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOperationLanePeakThroughputById(Long id) {
        return operationLanePeakThroughputMapper.deleteById(id);
    }

    /**
     * 功能描述：统计通道日级别高峰时段过检率
     *
     * @param laneThroughputQuery 筛选条件
     * @return List<LaneThroughputStatsVO>
     * @method countLanePeakThroughput
     * @author PanHu Sun
     * @date 2026/5/19 15:29
     */
    @Override
    public List<LaneThroughputResVO> countLanePeakThroughput(CountQueryReqVO laneThroughputQuery) {
        // 核心逻辑：未选择任何筛选条件，返回空数组
        if (Objects.isNull(laneThroughputQuery.getDeptId()) && Objects.isNull(laneThroughputQuery.getTeamId()) && Objects.isNull(laneThroughputQuery.getGroupId())) {
            return Collections.emptyList();
        }
        
        // 查询数据库中存在的日期数据
        List<LaneThroughputResVO> laneThroughputResList = this.baseMapper.countLanePeakThroughput(laneThroughputQuery);
        laneThroughputResList = CollUtil.emptyIfNull(laneThroughputResList);
        
        log.info("SQL查询返回数据条数: {}", laneThroughputResList.size());
        
        // 生成近30天的日期列表
        List<Date> last30Days = DateUtils.generateLast30Days();
        
        // 将查询结果按日期建立映射（只比较日期部分，忽略时间）
        Map<String, LaneThroughputResVO> dataMap = laneThroughputResList.stream()
                .collect(Collectors.toMap(
                        vo -> DateUtils.formatDateKey(vo.getRecordDate()),
                        vo -> vo,
                        (existing, replacement) -> existing
                ));
        
        log.info("数据Map中的日期键: {}", dataMap.keySet());

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

        // 补齐缺失的日期数据
        List<LaneThroughputResVO> resultList = Lists.newArrayList();
        for (Date date : last30Days) {
            String dateKey = DateUtils.formatDateKey(date);
            if (dataMap.containsKey(dateKey)) {
                // 存在的日期，使用查询结果
                resultList.add(dataMap.get(dateKey));
            } else {
                // 缺失的日期，补充0数据
                LaneThroughputResVO emptyLaneThroughput = new LaneThroughputResVO(date, groupName);
                resultList.add(emptyLaneThroughput);
            }
        }
        
        log.info("补齐后返回的总数据条数: {}", resultList.size());
        
        // 按日期升序排序
        resultList.sort(Comparator.comparing(LaneThroughputResVO::getRecordDate));
        
        return resultList;
    }
}
