package com.njcn.product.device.ledger.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.enums.common.ServerEnum;
import com.njcn.common.pojo.response.HttpResult;

import com.njcn.product.device.ledger.mapper.TreeMapper;
import com.njcn.product.device.ledger.pojo.dto.GeneralDeviceDTO;
import com.njcn.product.device.ledger.pojo.dto.TerminalTree;
import com.njcn.product.device.ledger.pojo.enums.LineBaseEnum;
import com.njcn.product.device.ledger.pojo.enums.StatisticsEnum;
import com.njcn.product.device.ledger.pojo.param.DeviceInfoParam;
import com.njcn.product.device.ledger.service.TerminalTreeService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * pqs
 * 终端设备树
 *
 * @author cdf
 * @date 2021/7/19
 */
@Service
@AllArgsConstructor
public class TerminalTreeServiceImpl implements TerminalTreeService {



    private final GeneralDeviceService generalDeviceService;

    private final TreeMapper treeMapper;


    /**
     * 5层树排除设备 母线监测点合并
     *
     * @author cdf
     * @date 2022/1/13
     */
    /**
     * 5层树排除设备 母线监测点合并
     *
     * @author cdf
     * @date 2022/1/13
     */
    @Override
    public List<TerminalTree> getTerminalTreeForFive(DeviceInfoParam deviceInfoParam) {
        //deviceInfoParam.setDeptIndex(RequestUtil.getDeptIndex());
        // 获取所有数据
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfo(deviceInfoParam, Stream.of(0).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList()));
        // 判断所有数据集合状态
        if (CollectionUtil.isNotEmpty(generalDeviceDTOList)) {
            // 创建集合
            List<TerminalTree> taiZhang = new ArrayList<>();
            // 遍历集合
            for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
                // 创建实体类
                TerminalTree terminalTree = new TerminalTree();
                // 判断监测点索引集合状态
                if (CollectionUtils.isEmpty(generalDeviceDTO.getLineIndexes())) {
                    continue;
                }
                // 通过供电公司索引查询省会
                List<TerminalTree> proList = treeMapper.getProvinceList(generalDeviceDTO.getGdIndexes());
                // 通过供电公司索引查询供电公司信息
                List<TerminalTree> gdList = treeMapper.getGdList(generalDeviceDTO.getGdIndexes());
                // 通过供电站索引查询供电站信息
                List<TerminalTree> subList = treeMapper.getSubList(generalDeviceDTO.getSubIndexes());
                // 通过监测点索引查询监测点信息
                List<TerminalTree> lineList = treeMapper.getLineList(generalDeviceDTO.getLineIndexes());

                //处理变电站
                dealChildrenData(subList, lineList, true);

                //监测点前面加序号,后面不需要删除下面两行就行
                //Integer[] arr = {1};
                //subList.forEach(item->item.getChildren().forEach(it->it.setName((arr[0]++ +"_"+it.getName()))));
                //处理供电公司
                dealChildrenData(gdList, subList, false);

                if (deviceInfoParam.getStatisticalType().getCode().equalsIgnoreCase(StatisticsEnum.POWER_NETWORK.getCode())) {
                    terminalTree.setChildren(gdList);
                } else {
                    //还需要额外处理省会
                    dealChildrenData(proList, gdList, false);
                    terminalTree.setChildren(proList);
                }
                terminalTree.setId(generalDeviceDTO.getIndex());
                terminalTree.setName(generalDeviceDTO.getName());
                terminalTree.setLevel(0);
                taiZhang.add(terminalTree);
            }
            return taiZhang;
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 处理变电站
     *
     * @param targetData
     * @param childrenData
     * @param isLine
     */
    private void dealChildrenData(List<TerminalTree> targetData, List<TerminalTree> childrenData, boolean isLine) {
        // 创建一个map集合，用于封装对象
        Map<String, List<TerminalTree>> groupLine;
        if (isLine) {
            // 通过stream流分组
            groupLine = childrenData.stream().collect(Collectors.groupingBy(terminalTree -> {
                // 获取父id字符串，通过 逗号 分割 成一个数组
                String[] pid = terminalTree.getPids().split(",");
                return pid[LineBaseEnum.SUB_LEVEL.getCode()];
            }));
        } else {
            groupLine = childrenData.stream().collect(Collectors.groupingBy(TerminalTree::getPid));
        }
        //变电站
        targetData = targetData.stream().peek(terminalTree -> {
            System.out.println(groupLine.get(terminalTree.getId()));
            System.out.println(terminalTree.getId());
            List<TerminalTree> terminalTrees = groupLine.get(terminalTree.getId()).stream().sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
            if (isLine) {
                //变电站集合
                int size = terminalTrees.stream().map(x -> {
                    // 获取父id字符串，通过 逗号 分割 成一个数组
                    String[] pid = x.getPids().split(",");
                    return pid[LineBaseEnum.DEVICE_LEVEL.getCode()];
                }).distinct().collect(Collectors.toList()).size();

                terminalTree.setName(terminalTree.getName() + "（" + size + "台装置）");

                terminalTree.setChildren(terminalTrees);
            } else {
                terminalTree.setChildren(groupLine.get(terminalTree.getId()));
            }
        }).collect(Collectors.toList());
    }






}
