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

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.ledger.domain.OperationStationHourlyThroughput;
import com.sundot.airport.ledger.domain.vo.AreaFlowVO;
import com.sundot.airport.ledger.domain.vo.StationHourlyThroughputGroupResVO;
import com.sundot.airport.ledger.domain.vo.StationHourlyThroughputVO;
import com.sundot.airport.ledger.mapper.OperationStationHourlyThroughputMapper;
import com.sundot.airport.ledger.service.IOperationStationHourlyThroughputService;
import com.sundot.airport.system.domain.BasePosition;
import com.sundot.airport.system.mapper.BasePositionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 站级时间段别总过检Service业务层处理
 */
@Service
public class OperationStationHourlyThroughputServiceImpl extends ServiceImpl<OperationStationHourlyThroughputMapper, OperationStationHourlyThroughput> implements IOperationStationHourlyThroughputService {

    @Autowired
    private OperationStationHourlyThroughputMapper operationStationHourlyThroughputMapper;
    @Autowired
    private BasePositionMapper basePositionMapper;

    /**
     * 查询站级时间段别总过检列表
     *
     * @param operationStationHourlyThroughput 站级时间段别总过检
     * @return 站级时间段别总过检
     */
    @Override
    public List<OperationStationHourlyThroughput> selectOperationStationHourlyThroughputList(OperationStationHourlyThroughput operationStationHourlyThroughput) {
        return operationStationHourlyThroughputMapper.selectOperationStationHourlyThroughputList(operationStationHourlyThroughput);
    }

    /**
     * 新增站级时间段别总过检
     *
     * @param operationStationHourlyThroughput 站级时间段别总过检
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertOperationStationHourlyThroughput(OperationStationHourlyThroughput operationStationHourlyThroughput) {
        operationStationHourlyThroughput.setCreateTime(DateUtils.getNowDate());
        return operationStationHourlyThroughputMapper.insert(operationStationHourlyThroughput);
    }

    /**
     * 修改站级时间段别总过检
     *
     * @param operationStationHourlyThroughput 站级时间段别总过检
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOperationStationHourlyThroughput(OperationStationHourlyThroughput operationStationHourlyThroughput) {
        operationStationHourlyThroughput.setUpdateTime(DateUtils.getNowDate());
        return operationStationHourlyThroughputMapper.updateById(operationStationHourlyThroughput);
    }

    /**
     * 批量删除站级时间段别总过检
     *
     * @param ids 需要删除的站级时间段别总过检主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOperationStationHourlyThroughputByIds(Long[] ids) {
        return operationStationHourlyThroughputMapper.deleteBatchIds(java.util.Arrays.asList(ids));
    }

    /**
     * 删除站级时间段别总过检信息
     *
     * @param id 站级时间段别总过检主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOperationStationHourlyThroughputById(Long id) {
        return operationStationHourlyThroughputMapper.deleteById(id);
    }

    /**
     * 功能描述：统计站级时间段人流量
     *
     * @return List<StationHourlyThroughputGroupResVO> 站级时间段人流量
     * @method countStationHourlyThroughput
     * @author PanHu Sun
     * @date 2026/5/19 16:46
     */
    @Override
    public List<StationHourlyThroughputGroupResVO> countStationHourlyThroughput() {
        List<StationHourlyThroughputVO> stationHourlyThroughputList = this.baseMapper.countStationHourlyThroughput();
        if (CollUtil.isEmpty(stationHourlyThroughputList)) {
            return Collections.emptyList();
        }

        Map<Long, BasePosition> areaInfoMap = Maps.newHashMap();
        // 1. 预处理：获取区域名称
        Set<Long> areaIds = stationHourlyThroughputList.stream()
                .filter(station -> Objects.nonNull(station.getAreaId()))
                .map(StationHourlyThroughputVO::getAreaId)
                .collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(areaIds)) {
            // 查询base_position表获取区域名称
            List<BasePosition> basePositions = basePositionMapper.selectPositionListByIds(areaIds);
            // 将basePositions转成map，key是id，value是BasePosition
            areaInfoMap = CollUtil.emptyIfNull(basePositions).stream().collect(Collectors.toMap(BasePosition::getId, v -> v));
        }

        // 2. 核心：按小时分组 → 组装成前端需要的层级结构
        Map<String, List<StationHourlyThroughputVO>> hourGroupMap = stationHourlyThroughputList.stream().collect(Collectors.groupingBy(StationHourlyThroughputVO::getHourOfDay));

        Map<Long, BasePosition> finalAreaInfoMap = areaInfoMap;
        return hourGroupMap.entrySet().stream().map(entry -> {
            String hour = entry.getKey();
            List<StationHourlyThroughputVO> hourDataList = entry.getValue();

            // 构建区域列表
            List<AreaFlowVO> areaList = hourDataList.stream().map(stats -> {
                BasePosition basePosition = finalAreaInfoMap.get(stats.getAreaId());

                AreaFlowVO areaFlowVO = new AreaFlowVO();
                areaFlowVO.setAreaId(stats.getAreaId());
                areaFlowVO.setAreaName(Objects.nonNull(basePosition) ? basePosition.getName() : "");
                areaFlowVO.setAreaFlow(stats.getAreaFlow());
                return areaFlowVO;
            }).collect(Collectors.toList());

            // 构建小时分组对象
            StationHourlyThroughputGroupResVO groupVO = new StationHourlyThroughputGroupResVO();
            groupVO.setHourOfDay(hour);
            // 总人流量（取第一条即可，同小时数据总流量一致）
            groupVO.setTotalHourFlow(hourDataList.get(0).getTotalHourFlow());
            // 区域信息
            groupVO.setAreaList(areaList);
            return groupVO;
        }).collect(Collectors.toList());
    }
}
