package com.njcn.csharmonic.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.CsUserPinsFeignClient;
import com.njcn.csdevice.api.EngineeringFeignClient;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.param.CsEngineeringQueryParm;
import com.njcn.csdevice.pojo.po.CsUserPins;
import com.njcn.csdevice.pojo.vo.CsEngineeringVO;
import com.njcn.csdevice.pojo.vo.EngineeringHomePageVO;
import com.njcn.csharmonic.mapper.CsEventUserPOMapper;
import com.njcn.csharmonic.pojo.dto.UnReadEventDto;
import com.njcn.csharmonic.service.CsEventUserPOService;
import com.njcn.csharmonic.service.HomePageService;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author xy
 */
@Service
@AllArgsConstructor
@Slf4j
public class HomePageServiceImpl implements HomePageService {

    private final CsEventUserPOMapper csEventUserPOMapper;
    private final EngineeringFeignClient engineeringFeignClient;
    private final CsLedgerFeignClient csLedgerFeignClient;
    private final CsUserPinsFeignClient csUserPinsFeignClient;

    @Override
    public List<EngineeringHomePageVO> getEngineeringHomePage() {
        List<EngineeringHomePageVO> result = new ArrayList<>();
        List<CsEngineeringVO> engineeringList = engineeringFeignClient.queryEngineering(new CsEngineeringQueryParm()).getData();
        if (CollectionUtils.isNotEmpty(engineeringList)) {
            // 提取所有工程 ID
            List<String> engineeringIds = engineeringList.stream().map(CsEngineeringVO::getId).collect(Collectors.toList());

            // 批量获取所有工程的设备信息
            List<DevDetailDTO> devList = csLedgerFeignClient.getDevInfoByEngineerIds(engineeringIds).getData();
            Map<String, List<DevDetailDTO>> devMap = Objects.isNull(devList) ? new HashMap<>() :
                    devList.stream().collect(Collectors.groupingBy(DevDetailDTO::getEngineeringid));

            // 遍历工程列表，从内存中获取设备数据
            engineeringList.forEach(item -> {
                EngineeringHomePageVO vo = new EngineeringHomePageVO();
                vo.setEngineeringId(item.getId());
                vo.setEngineeringName(item.getName());

                // 从 Map 中获取该工程的设备列表 (无设备时为 null 或空列表)
                List<DevDetailDTO> devs = devMap.get(item.getId());

                vo.setDevTotal(Objects.isNull(devs) ? 0 : devs.size());
                long status1Count = devs == null ? 0 : devs.stream().filter(d -> d.getRunStatus() == 1).count();
                long status2Count = devs == null ? 0 : devs.stream().filter(d -> d.getRunStatus() == 2).count();
                vo.setOnlineDevTotal((int) status2Count);
                vo.setOfflineDevTotal((int) status1Count);
                vo.setSort(item.getSort());

                // 获取项目事件数量
                int alarmTotal = 0;
                if (CollectionUtil.isNotEmpty(devs) && !Objects.isNull(devs)) {
                    // 获取暂态未读事件
                    List<String> allLineIds = devs.stream()
                            .filter(dev -> CollectionUtil.isNotEmpty(dev.getLineList()))
                            .flatMap(dev -> dev.getLineList().stream())
                            .distinct()
                            .collect(Collectors.toList());

                    List<String> tempEventList = csEventUserPOMapper.queryTempEvent(RequestUtil.getUserIndex(),"","",allLineIds);
                    alarmTotal = alarmTotal + (CollectionUtil.isNotEmpty(tempEventList)?tempEventList.size():0);

                    // 获取稳态未读事件
                    if (CollectionUtil.isNotEmpty(allLineIds)) {
                        List<String> tempHarmonicList = csEventUserPOMapper.queryTempHarmonic(RequestUtil.getUserIndex(),"","",allLineIds);
                        alarmTotal = alarmTotal + (CollectionUtil.isNotEmpty(tempHarmonicList)?tempHarmonicList.size():0);
                    }
                }
                vo.setAlarmTotal(alarmTotal);
                result.add(vo);
            });

            // 获取用户是否有置顶的工程
            List<CsUserPins> pinList = csUserPinsFeignClient.getPinToTopList().getData();
            if (CollectionUtils.isNotEmpty(pinList)) {
                List<String> targetIdList = pinList.stream()
                        .filter(item -> Objects.equals(item.getTargetType(), 2))
                        .map(CsUserPins::getTargetId)
                        .collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(targetIdList)) {
                    // 分离出匹配 targetIdList 的节点和未匹配的节点
                    List<EngineeringHomePageVO> matchedList = new ArrayList<>();
                    List<EngineeringHomePageVO> unmatchedList = new ArrayList<>();
                    for (EngineeringHomePageVO node : result) {
                        if (targetIdList.contains(node.getEngineeringId())) {
                            node.setIsTop(1);
                            matchedList.add(node);
                        } else {
                            unmatchedList.add(node);
                        }
                    }
                    // 根据 targetIdList 的顺序对匹配的节点进行排序
                    matchedList.sort(Comparator.comparingInt(node -> targetIdList.indexOf(node.getEngineeringId())));
                    // 未匹配的节点按照原有的 sort 字段排序，处理 null 值情况
                    unmatchedList.sort(Comparator.comparing(node -> node.getSort() != null ? node.getSort() : Integer.MAX_VALUE));
                    // 清空原列表并添加排序后的数据
                    result.clear();
                    result.addAll(matchedList);
                    result.addAll(unmatchedList);
                }
            }
        }
        return result;
    }

}
