package com.njcn.csdevice.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.csdevice.mapper.CsUserPinsMapper;
import com.njcn.csdevice.param.CsUserPinsParam;
import com.njcn.csdevice.pojo.po.CsUserPins;
import com.njcn.csdevice.pojo.vo.CsLedgerVO;
import com.njcn.csdevice.service.ICsUserPinsService;
import com.njcn.web.utils.RequestUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户置顶表 服务实现类
 * </p>
 *
 * @author xy
 * @since 2026-03-04
 */
@Service
public class CsUserPinsServiceImpl extends ServiceImpl<CsUserPinsMapper, CsUserPins> implements ICsUserPinsService {

    @Override
    public boolean engineeringPinToTop(CsUserPinsParam param) {
        LambdaUpdateWrapper<CsUserPins> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(CsUserPins::getUserId, param.getUserId())
                .eq(CsUserPins::getTargetId, param.getTargetId())
                .eq(CsUserPins::getTargetType, param.getTargetType());
        CsUserPins csUserPins = this.getOne(wrapper);
        //为空，则是置顶
        if (Objects.isNull(csUserPins)) {
            CsUserPins po = new CsUserPins();
            BeanUtils.copyProperties(param, po);
            this.save(po);
        }
        //有数据则是取消置顶
        else {
            this.removeById(csUserPins.getId());
        }
        return true;
    }

    @Override
    public List<CsUserPins> getPinToTopList() {
        LambdaUpdateWrapper<CsUserPins> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(CsUserPins::getUserId, RequestUtil.getUserIndex())
                .orderByDesc(CsUserPins::getCreateTime);
        return this.list(wrapper);
    }

    @Override
    public void channelTree(List<CsUserPins> list, List<CsLedgerVO> tree, Integer level) {
        List<String> targetIdList = new ArrayList<>();
        List<String> devList = new ArrayList<>();
        switch (level) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                // 处理工程置顶（第一层）
                targetIdList = list.stream()
                        .filter(item -> Objects.equals(item.getTargetType(), 2))
                        .map(CsUserPins::getTargetId)
                        .collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(targetIdList)) {
                    sortByTargetList(tree, targetIdList);
                }

                // 处理设备置顶（第三层）
                devList = list.stream()
                        .filter(item -> Objects.equals(item.getTargetType(), 1))
                        .map(CsUserPins::getTargetId)
                        .collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(devList)) {
                    // 遍历 tree，找到第三层的数据进行排序
                    for (CsLedgerVO firstLevelNode : tree) {
                        if (firstLevelNode.getLevel() == 0 && CollectionUtil.isNotEmpty(firstLevelNode.getChildren())) {
                            // 第二层
                            for (CsLedgerVO secondLevelNode : firstLevelNode.getChildren()) {
                                if (CollectionUtil.isNotEmpty(secondLevelNode.getChildren())) {
                                    // 第三层
                                    sortByTargetList(secondLevelNode.getChildren(), devList);
                                }
                            }
                        }
                    }
                }
                break;
            case 5:
                // 处理工程置顶（第二层，因为最上面加了一层）
                targetIdList = list.stream()
                        .filter(item -> Objects.equals(item.getTargetType(), 2))
                        .map(CsUserPins::getTargetId)
                        .collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(targetIdList)) {
                    sortSecondLevelByTargetList(tree, targetIdList);
                }
                // 处理设备置顶（第四层）
                devList = list.stream()
                        .filter(item -> Objects.equals(item.getTargetType(), 1))
                        .map(CsUserPins::getTargetId)
                        .collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(devList)) {
                    sortFourthLevelByDevList(tree, devList);
                }
                break;
            default:
                break;

        }
    }

    /**
     * 根据目标 ID 列表对节点列表进行排序
     * @param nodeList 需要排序的节点列表
     * @param targetIdList 目标 ID 列表（决定排序顺序）
     */
    private void sortByTargetList(List<CsLedgerVO> nodeList, List<String> targetIdList) {
        // 分离出匹配 targetIdList 的节点和未匹配的节点
        List<CsLedgerVO> matchedList = new ArrayList<>();
        List<CsLedgerVO> unmatchedList = new ArrayList<>();
        for (CsLedgerVO node : nodeList) {
            if (targetIdList.contains(node.getId())) {
                node.setIsTop(1);
                matchedList.add(node);
            } else {
                unmatchedList.add(node);
            }
        }
        // 根据 targetIdList 的顺序对匹配的节点进行排序
        matchedList.sort(Comparator.comparingInt(node -> targetIdList.indexOf(node.getId())));
        // 未匹配的节点按照原有的 sort 字段排序，处理 null 值情况
        unmatchedList.sort(Comparator.comparing(node -> node.getSort() != null ? node.getSort() : Integer.MAX_VALUE));
        // 清空原列表并添加排序后的数据
        nodeList.clear();
        nodeList.addAll(matchedList);
        nodeList.addAll(unmatchedList);
    }

    /**
     * 根据目标 ID 列表对第二层节点进行排序（因为最上面加了一层）
     */
    private void sortSecondLevelByTargetList(List<CsLedgerVO> tree, List<String> targetIdList) {
        for (CsLedgerVO firstLevelNode : tree) {
            if (CollectionUtil.isNotEmpty(firstLevelNode.getChildren())) {
                sortByTargetList(firstLevelNode.getChildren(), targetIdList);
            }
        }
    }

    /**
     * 根据设备 ID 列表对第四层节点进行排序
     */
    private void sortFourthLevelByDevList(List<CsLedgerVO> tree, List<String> devList) {
        for (CsLedgerVO firstLevelNode : tree) {
            if (CollectionUtil.isNotEmpty(firstLevelNode.getChildren())) {
                for (CsLedgerVO secondLevelNode : firstLevelNode.getChildren()) {
                    if (CollectionUtil.isNotEmpty(secondLevelNode.getChildren())) {
                        for (CsLedgerVO thirdLevelNode : secondLevelNode.getChildren()) {
                            if (CollectionUtil.isNotEmpty(thirdLevelNode.getChildren())) {
                                // 第四层
                                sortByTargetList(thirdLevelNode.getChildren(), devList);
                            }
                        }
                    }
                }
            }
        }
    }


}
