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

import cn.hutool.core.collection.CollUtil;
import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.item.domain.push.SeizureMessagePushDTO;
import com.sundot.airport.item.mapper.ItemLargeScreenMapper;
import com.sundot.airport.item.service.ISeizureMessagePushService;
import com.sundot.airport.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 查获消息推送服务实现类
 *
 * @author wangxx
 * @date 2026-03-31
 */
@Slf4j
@Service
public class SeizureMessagePushServiceImpl implements ISeizureMessagePushService {

    @Autowired
    private ItemLargeScreenMapper itemLargeScreenMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 获取查获消息推送数据
     *
     * @param userId    用户 ID
     * @param deptId    部门 ID
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 查获消息推送数据
     */
    @Override
    public SeizureMessagePushDTO getSeizureMessagePushData(Long userId, Long deptId, Date startDate, Date endDate) {
        try {
            // 1. 获取用户所在的站点 ID
            Long stationId = getStationIdByUserId(userId, deptId);
            if (stationId == null) {
                throw new ServiceException("未找到用户所属的站点信息");
            }

            // 2. 构建查询参数（直接使用站点 ID 查询全站数据）
            BaseLargeScreenQueryParamDto queryDto = new BaseLargeScreenQueryParamDto();
            queryDto.setInspectStationId(stationId);
            queryDto.setStartDate(startDate);
            queryDto.setEndDate(endDate);

            // 3. 查询移交公安违禁品 TOP3
            List<SeizureMessagePushDTO.ProhibitedItemTop3> prohibitedItemsTop3 = getProhibitedItemsTop3(queryDto);

            // 4. 查询故意隐匿物品藏匿部位 TOP3
            List<SeizureMessagePushDTO.ConcealmentPositionTop3> concealmentPositionsTop3 = getConcealmentPositionsTop3(queryDto);

            // 5. 查询移交公安违禁品高发通道 TOP3
            List<SeizureMessagePushDTO.HighRiskChannelTop3> highRiskChannelsTop3 = getHighRiskChannelsTop3(queryDto);

            // 6. 组装返回结果
            SeizureMessagePushDTO result = new SeizureMessagePushDTO();
            result.setProhibitedItemsTop3(prohibitedItemsTop3);
            result.setConcealmentPositionsTop3(concealmentPositionsTop3);
            result.setHighRiskChannelsTop3(highRiskChannelsTop3);

            return result;
        } catch (Exception e) {
            log.error("获取查获消息推送数据失败，userId: {}, deptId: {}, error: {}", userId, deptId, e.getMessage());
            throw new ServiceException("获取查获消息推送数据失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户 ID 获取所在站点 ID
     */
    private Long getStationIdByUserId(Long userId, Long deptId) {
        try {
            // 从当前用户的部门向上查找站点
            SysDept currentDept = sysDeptService.selectDeptById(deptId);
            while (currentDept != null && !"STATION".equals(currentDept.getDeptType())) {
                currentDept = sysDeptService.selectDeptById(currentDept.getParentId());
            }
            return currentDept != null ? currentDept.getDeptId() : null;
        } catch (Exception e) {
            log.error("获取站点 ID 失败，userId: {}, deptId: {}, error: {}", userId, deptId, e.getMessage());
            return null;
        }
    }

    /**
     * 获取移交公安违禁品 TOP3
     */
    private List<SeizureMessagePushDTO.ProhibitedItemTop3> getProhibitedItemsTop3(BaseLargeScreenQueryParamDto dto) {
        List<SeizureMessagePushDTO.ProhibitedItemTop3> resultList = itemLargeScreenMapper.selectProhibitedItemsTop3ForPush(dto);

        // 设置排名
        if (CollUtil.isNotEmpty(resultList)) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setRank(i + 1);
            }
        }

        return resultList;
    }

    /**
     * 获取故意隐匿物品藏匿部位 TOP3
     */
    private List<SeizureMessagePushDTO.ConcealmentPositionTop3> getConcealmentPositionsTop3(BaseLargeScreenQueryParamDto dto) {
        List<SeizureMessagePushDTO.ConcealmentPositionTop3> resultList = itemLargeScreenMapper.selectConcealmentPositionsTop3ForPush(dto);

        // 设置排名
        if (CollUtil.isNotEmpty(resultList)) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setRank(i + 1);
            }
        }

        return resultList;
    }

    /**
     * 获取移交公安违禁品高发通道 TOP3
     */
    private List<SeizureMessagePushDTO.HighRiskChannelTop3> getHighRiskChannelsTop3(BaseLargeScreenQueryParamDto dto) {
        List<SeizureMessagePushDTO.HighRiskChannelTop3> resultList = itemLargeScreenMapper.selectHighRiskChannelsTop3ForPush(dto);

        // 设置排名
        if (CollUtil.isNotEmpty(resultList)) {
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setRank(i + 1);
            }
        }

        return resultList;
    }
}
