package com.njcn.energy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.energy.mapper.*;
import com.njcn.energy.pojo.constant.TableName;
import com.njcn.energy.pojo.dto.NetAndDevByLineDTO;
import com.njcn.energy.pojo.enums.EnergyResponseEnum;
import com.njcn.energy.pojo.param.DataHisParam;
import com.njcn.energy.pojo.param.DevCfgParam;
import com.njcn.energy.pojo.param.EnergyBaseParam;
import com.njcn.energy.pojo.param.GroupArrParam;
import com.njcn.energy.pojo.po.*;
import com.njcn.energy.pojo.vo.*;
import com.njcn.energy.service.IDataGroupService;
import com.njcn.energy.service.IGroupArrayService;
import com.njcn.energy.service.ILogicDeviceLineService;
import com.njcn.influx.deprecated.InfluxDBPublicParam;
import com.njcn.influx.utils.InfluxDbUtils;
import lombok.RequiredArgsConstructor;
import org.influxdb.dto.QueryResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * pqs
 *
 * @author cdf
 * @date 2022/2/24
 */
@Service
@RequiredArgsConstructor
public class LogicDeviceLineServiceImpl extends ServiceImpl<LogicDeviceLineMapper, LogicDev> implements ILogicDeviceLineService {

    private final LogicDeviceLineMapper logicDeviceLineMapper;

    private final DataSetMapper dataSetMapper;

    private final NetDevMapper netDevMapper;

    private final DataGroupMapper dataGroupMapper;

    private final DataArrayMapper dataArrayMapper;

    private final GroupArrayMapper groupArrMapper;

    private final IDataGroupService iDataGroupService;

    private final IGroupArrayService iGroupArrayService;

    private final InfluxDbUtils influxDbUtils;

    @Override
    public List<EnergyDeviceTreeVO> getEnergyTree() {
        List<EnergyDeviceTreeVO> netDevList = netDevMapper.getNetDevList();
        List<EnergyDeviceTreeVO> logicDevList = logicDeviceLineMapper.getLogicDevList();
        List<EnergyDeviceTreeVO> elLineList = logicDeviceLineMapper.getEleLineList();
        if (CollectionUtil.isEmpty(logicDevList) || CollectionUtil.isEmpty(elLineList) || CollectionUtil.isEmpty(netDevList)) {
            throw new BusinessException(EnergyResponseEnum.DEV_LINE_EMPTY);
        }
        List<EnergyDeviceTreeVO> logicAllDevList = logicDevList.stream().peek(item -> item.setChildren(getChildren(item, elLineList))).collect(Collectors.toList());
        return netDevList.stream().peek(item -> item.setChildren(getChildren(item, logicAllDevList))).collect(Collectors.toList());
    }

    @Override
    public List<EnergyDeviceTreeVO> getAirLineTree(){
        List<EnergyDeviceTreeVO> netDevList = netDevMapper.getNetDevList();
        netDevList = netDevList.stream().filter(item-> item.getName().contains("空调")).collect(Collectors.toList());
        List<EnergyDeviceTreeVO> logicDevList = logicDeviceLineMapper.getLogicDevList();
        List<EnergyDeviceTreeVO> elLineList = logicDeviceLineMapper.getEleLineList();
        if (CollectionUtil.isEmpty(logicDevList) || CollectionUtil.isEmpty(elLineList) || CollectionUtil.isEmpty(netDevList)) {
            throw new BusinessException(EnergyResponseEnum.DEV_LINE_EMPTY);
        }
        List<EnergyDeviceTreeVO> logicAllDevList = logicDevList.stream().peek(item -> item.setChildren(getChildren(item, elLineList))).collect(Collectors.toList());

        return netDevList.stream().peek(item -> item.setChildren(getChildren(item, logicAllDevList))).collect(Collectors.toList());
    }

    @Override
    public EleLoadSetTreeVO getEnergyLoadTree(String id) {
        EleLoadSetTreeVO eleLoadSetTreeVO = new EleLoadSetTreeVO();
        List<EnergyDeviceTreeVO> netDevList = netDevMapper.getNetDevList();
        netDevList = netDevList.stream().filter(item -> item.getName().indexOf("空调") == -1).collect(Collectors.toList());
        List<EnergyDeviceTreeVO> logicDevList = logicDeviceLineMapper.getLogicDevList();
        List<EnergyDeviceTreeVO> netNoDevList = netDevMapper.getNetDevList();
        netNoDevList = netNoDevList.stream().filter(item -> item.getName().indexOf("空调") == -1).collect(Collectors.toList());
        List<EnergyDeviceTreeVO> logicNoDevList = logicDeviceLineMapper.getLogicDevList();
        List<EnergyDeviceTreeVO> elBindsLineList = logicDeviceLineMapper.getEleBindsLineList(id);
        List<EnergyDeviceTreeVO> elNoBindsLineList = logicDeviceLineMapper.getEleNoBindsLineList();
        List<EnergyDeviceTreeVO> energyNoBindsDeviceTreeVOList = new ArrayList<>();
        List<EnergyDeviceTreeVO> energyBindsDeviceTreeVOList = new ArrayList<>();
        List<EnergyDeviceTreeVO> energyNetTreeVOList = new ArrayList<>();
        List<EnergyDeviceTreeVO> energyNetNoTreeVOList = new ArrayList<>();
        if (!CollectionUtil.isEmpty(elBindsLineList)) {
            List<EnergyDeviceTreeVO> logicBindsDevList = logicDevList.stream().peek(item -> item.setChildren(getChildren(item, elBindsLineList))).collect(Collectors.toList());
            List<EnergyDeviceTreeVO> energyDeviceTreeVOList = logicBindsDevList.stream().filter(item -> item.getChildren().size() != 0).collect(Collectors.toList());
            energyBindsDeviceTreeVOList = netDevList.stream().peek(item -> item.setChildren(getChildren(item, energyDeviceTreeVOList))).collect(Collectors.toList());
            energyNetTreeVOList = energyBindsDeviceTreeVOList.stream().filter(item -> item.getChildren().size() != 0).collect(Collectors.toList());
        }

        if (!CollectionUtil.isEmpty(elNoBindsLineList)) {
            List<EnergyDeviceTreeVO> logicNoBindsDevList = logicNoDevList.stream().peek(item -> item.setChildren(getChildren(item, elNoBindsLineList))).collect(Collectors.toList());
            List<EnergyDeviceTreeVO> energyDeviceNoTreeVOList = logicNoBindsDevList.stream().filter(item -> item.getChildren().size() != 0).collect(Collectors.toList());
            energyNoBindsDeviceTreeVOList = netNoDevList.stream().peek(item -> item.setChildren(getChildren(item, energyDeviceNoTreeVOList))).collect(Collectors.toList());
            energyNetNoTreeVOList = energyNoBindsDeviceTreeVOList.stream().filter(item -> item.getChildren().size() != 0).collect(Collectors.toList());
        }
        eleLoadSetTreeVO.setBinds(energyNetTreeVOList);
        eleLoadSetTreeVO.setNoBinds(energyNetNoTreeVOList);
        return eleLoadSetTreeVO;
    }

    @Override
    public LogicDeviceLineInfoVO getEnergyDevInfoById(String id) {
        return logicDeviceLineMapper.getDevInfo(id);
    }


    @Override
    public IPage<EnergyTemplateVO> getEnergyTemplateById(String id, Integer pageNum, Integer pageSize) {
        List<EnergyTemplateVO> listRes = new ArrayList<>();
        IPage<DataArray> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<DataArray> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DataArray::getPid, id);
        lambdaQueryWrapper.orderByAsc(DataArray::getSort);
        IPage<DataArray> pageRes = dataArrayMapper.selectPage(page, lambdaQueryWrapper);
        if (pageRes.getTotal() > 0) {
            List<DataArray> arrRes = pageRes.getRecords();
            if (CollectionUtil.isNotEmpty(arrRes)) {
                Map<String, List<DataArray>> classMap = new HashMap<>();
                arrRes.stream().collect(Collectors.groupingBy(DataArray::getClassName, Collectors.toList()))
                        .forEach(classMap::put);
                classMap.forEach((className, dataArrList) -> {

                    List<String> arrIds = dataArrList.stream().map(DataArray::getId).collect(Collectors.toList());
                    List<EnergyTemplateVO> listData = logicDeviceLineMapper.getDataList(className, arrIds);
                    if (CollectionUtil.isNotEmpty(listData)) {
                        listRes.addAll(listData);
                    }
                });
            }

        }
        List<EnergyTemplateVO> listResEs = listRes.stream().sorted(Comparator.comparing(EnergyTemplateVO::getSort)).collect(Collectors.toList());
        IPage<EnergyTemplateVO> pageTurn = new Page<>(pageNum, pageSize);
        pageTurn.setRecords(listResEs);
        pageTurn.setTotal(pageRes.getTotal());
        pageTurn.setSize(pageRes.getSize());
        pageTurn.setCurrent(pageRes.getCurrent());
        pageTurn.setPages(pageRes.getPages());
        return pageTurn;
    }


    @Override
    public IPage<DataGroupTemplateVO> getRealGroupTemplateById(String id, Integer pageNum, Integer pageSize) {
        IPage<DataGroupTemplateVO> page = new Page<>(pageNum, pageSize);
        IPage<DataGroupTemplateVO> pageTurn = new Page<>();
        IPage<DataGroupTemplateVO> pageRes = dataGroupMapper.getGroupDataList(page, id);
        if (pageRes.getTotal() > 0) {
            //查询到分组
            List<EnergyTemplateVO> listDataAll = new ArrayList<>();
            List<DataGroupTemplateVO> groupList = pageRes.getRecords();
            //获取数据集下所有数据项
            List<DataArray> voList = logicDeviceLineMapper.getGroupDataBySetId(id);
            if (CollectionUtil.isNotEmpty(voList)) {
                Map<String, List<DataArray>> classMap = new HashMap<>();
                voList.stream().collect(Collectors.groupingBy(DataArray::getClassName, Collectors.toList()))
                        .forEach(classMap::put);
                classMap.forEach((className, dataArrList) -> {
                    List<String> arrIds = dataArrList.stream().map(DataArray::getId).collect(Collectors.toList());

                    List<EnergyTemplateVO> listData = logicDeviceLineMapper.getDataList(className, arrIds);
                    if (CollectionUtil.isNotEmpty(listData)) {
                        for (EnergyTemplateVO energyTemplateVO : listData) {

                            for (DataArray dataArray : dataArrList) {
                                if (energyTemplateVO.getId().equals(dataArray.getDataId())) {
                                    energyTemplateVO.setPid(dataArray.getPid());
                                    break;
                                }
                            }
                        }
                        listDataAll.addAll(listData);
                    }

                });
                List<EnergyTemplateVO> listDataAllRes = listDataAll.stream().sorted(Comparator.comparing(EnergyTemplateVO::getSort)).collect(Collectors.toList());

                List<DataGroupTemplateVO> grList = groupList.stream().peek((item) -> item.setChildren(getChildrenes(item.getId(), listDataAllRes))).collect(Collectors.toList());
                pageTurn.setRecords(grList);
                pageTurn.setTotal(pageRes.getTotal());
                pageTurn.setSize(pageRes.getSize());
                pageTurn.setCurrent(pageRes.getCurrent());
                pageTurn.setPages(pageRes.getPages());
                return pageTurn;
            } else {
                throw new BusinessException(CommonResponseEnum.FAIL);
            }
        } else {
            pageTurn.setRecords(new ArrayList<>());
            pageTurn.setTotal(pageRes.getTotal());
            pageTurn.setSize(pageRes.getSize());
            pageTurn.setCurrent(pageRes.getCurrent());
            pageTurn.setPages(pageRes.getPages());
            return pageTurn;
        }


    }


    @Override
    public IPage<DataGroupTemplateVO> getHistoryTemplateById(EnergyBaseParam energyBaseParam) {
        LocalDateTime localDateTime = PubUtils.endTimeToLocalDateTime(energyBaseParam.getEndTime());
        String endTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        IPage<DataGroupTemplateVO> page = new Page<>(energyBaseParam.getPageNum(), energyBaseParam.getPageSize());
        IPage<DataGroupTemplateVO> pageTurn = new Page<>();
        IPage<DataGroupTemplateVO> pageRes = dataGroupMapper.getGroupDataList(page, energyBaseParam.getId());

        if (pageRes.getTotal() != 0) {
            //查询到分组
            List<EnergyTemplateVO> listDataAll = new ArrayList<>();
            List<DataGroupTemplateVO> groupList = pageRes.getRecords();
            //获取数据集下所有数据项
            List<DataArray> voList = logicDeviceLineMapper.getGroupDataBySetId(energyBaseParam.getId());
            if (CollectionUtil.isNotEmpty(voList)) {
                Map<String, List<DataArray>> classMap = new HashMap<>();
                voList.stream().collect(Collectors.groupingBy(DataArray::getClassName, Collectors.toList()))
                        .forEach(classMap::put);
                classMap.forEach((className, dataArrList) -> {
                    List<String> arrIds = dataArrList.stream().map(DataArray::getId).collect(Collectors.toList());
                    List<EnergyTemplateVO> listData = logicDeviceLineMapper.getDataList(className, arrIds);
                    String tableName = listData.get(0).getClassId();
                    if (CollectionUtil.isNotEmpty(listData)) {
                        for (EnergyTemplateVO energyTemplateVO : listData) {
                            for (DataArray dataArray : dataArrList) {
                                if (energyTemplateVO.getId().equals(dataArray.getDataId())) {
                                    energyTemplateVO.setPid(dataArray.getPid());
                                    break;
                                }
                            }
                        }

                        if (listData.size() > 0) {


                            Map<String, List<EnergyTemplateVO>> classTemMap = new HashMap<>();

                            listData.stream().collect(Collectors.groupingBy(EnergyTemplateVO::getPhase, Collectors.toList())).forEach(classTemMap::put);
                            classTemMap.forEach((tmpPhase, enList) -> {
                                StringBuilder stringBuilderMax = new StringBuilder("select ");
                                StringBuilder stringBuilderMin = new StringBuilder("select ");

                                StringBuilder condition = new StringBuilder();
                                for (int j = 0; j < enList.size(); j++) {
                                    if (j == enList.size() - 1) {
                                        stringBuilderMax.append("MAX(").append(enList.get(j).getName()).append(") as ").append(enList.get(j).getName()).append(" ");
                                        stringBuilderMin.append("MIN(").append(enList.get(j).getName()).append(") as ").append(enList.get(j).getName()).append(" ");
                                    } else {
                                        stringBuilderMax.append("MAX(").append(enList.get(j).getName()).append(") as ").append(enList.get(j).getName()).append(", ");
                                        stringBuilderMin.append("MIN(").append(enList.get(j).getName()).append(") as ").append(enList.get(j).getName()).append(",  ");
                                    }
                                    condition.append(" and ").append(enList.get(j).getName()).append("!=-1000000");
                                }
                                String tableStr = "";
                                if (TableName.eleEpdPqd.equals(className)) {
                                    tableStr = "_add";
                                }

                                stringBuilderMax.append("from ").append(tableName).append(tableStr).append(" where").append(" time").append(">='").append(energyBaseParam.getStartTime()).append("' and time < '" + endTime + "'").append(" and LineId='" + energyBaseParam.getLineId() + "'").append(" and Phase='" + tmpPhase + "'");
                                stringBuilderMin.append("from ").append(tableName).append(tableStr).append(" where").append(" time").append(">='").append(energyBaseParam.getStartTime()).append("' and time < '" + endTime + "'").append(" and LineId='" + energyBaseParam.getLineId() + "'").append(" and Phase='" + tmpPhase + "'").append(condition);
                                    QueryResult queryResultMax = influxDbUtils.query(stringBuilderMax.toString());
                                    QueryResult queryResultMin = influxDbUtils.query(stringBuilderMin.toString());
                                    if (CollectionUtil.isNotEmpty(queryResultMax.getResults().get(0).getSeries()) && CollectionUtil.isNotEmpty(queryResultMin.getResults().get(0).getSeries())) {
                                        for (int j = 0; j < enList.size(); j++) {
                                            enList.get(j).setMaxValue(queryResultMax.getResults().get(0).getSeries().get(0).getValues().get(0).get(j + 1));
                                            enList.get(j).setMinValue(queryResultMin.getResults().get(0).getSeries().get(0).getValues().get(0).get(j + 1));
                                        }
                                    } else {
                                        throw new BusinessException(EnergyResponseEnum.ENERGY_EMPTY);
                                    }
                                });




                        }

                        listDataAll.addAll(listData);
                    }

                });
                List<DataGroupTemplateVO> grList = groupList.stream().peek((item) -> {
                    item.setChildren(getChildrenes(item.getId(), listDataAll));
                }).collect(Collectors.toList());
                pageTurn.setRecords(grList);
                pageTurn.setTotal(pageRes.getTotal());
                pageTurn.setSize(pageRes.getSize());
                pageTurn.setCurrent(pageRes.getCurrent());
                pageTurn.setPages(pageRes.getPages());
                return pageTurn;
            } else {
                throw new BusinessException(CommonResponseEnum.FAIL);
            }


        } else {
            pageTurn.setRecords(new ArrayList<>());
            pageTurn.setTotal(pageRes.getTotal());
            pageTurn.setSize(pageRes.getSize());
            pageTurn.setCurrent(pageRes.getCurrent());
            pageTurn.setPages(pageRes.getPages());
            return pageTurn;
        }

    }

    @Override
    public IPage<DataGroupTemplateVO> getStatisTemplateById(String id, Integer pageNum, Integer pageSize, String lineId) {
        IPage<DataGroupTemplateVO> pageTurn = new Page<>(); //定义新的返回体
        IPage<DataGroupTemplateVO> page = new Page<>(pageNum, pageSize);
        IPage<DataGroupTemplateVO> pageRes = dataGroupMapper.getGroupDataList(page, id);
        if (pageRes.getTotal() != 0) {
            //查询到分组
            List<EnergyTemplateVO> listDataAll = new ArrayList<>();
            List<DataGroupTemplateVO> groupList = pageRes.getRecords();
            //获取数据集下所有数据项
            List<DataArray> voList = logicDeviceLineMapper.getGroupDataBySetId(id);
            if (CollectionUtil.isNotEmpty(voList)) {
                Map<String, List<DataArray>> classMap = new HashMap<>();
                voList.stream().collect(Collectors.groupingBy(DataArray::getClassName, Collectors.toList())).forEach(classMap::put);
                classMap.forEach((className, dataArrList) -> {
                    List<String> arrIds = dataArrList.stream().map(DataArray::getId).collect(Collectors.toList());
                    List<EnergyTemplateVO> listData = logicDeviceLineMapper.getDataList(className, arrIds);
                    String tableName = listData.get(0).getClassId();
                    if (CollectionUtil.isNotEmpty(listData)) {
                        for (EnergyTemplateVO energyTemplateVO : listData) {
                            for (DataArray dataArray : dataArrList) {
                                if (energyTemplateVO.getId().equals(dataArray.getDataId())) {
                                    energyTemplateVO.setPid(dataArray.getPid());
                                    break;
                                }
                            }
                        }


                        if (listData.size() > 0) {
                            if (TableName.eleEpdPqd.equals(className) || TableName.eleMd.equals(className)) {
                                //电能表
                                Map<String, List<EnergyTemplateVO>> classTemMap = new HashMap<>();

                                listData.stream().collect(Collectors.groupingBy(EnergyTemplateVO::getPhase, Collectors.toList())).forEach(classTemMap::put);
                                classTemMap.forEach((tmpPhase, enList) -> {
                                    StringBuilder stringBuilderMax = new StringBuilder("select ");

                                    for (int j = 0; j < enList.size(); j++) {
                                        if (j == enList.size() - 1) {
                                            stringBuilderMax.append(enList.get(j).getName()).append(" ");
                                        } else {
                                            stringBuilderMax.append(enList.get(j).getName()).append(", ");
                                        }
                                    }
                                    if (tableName.equals(TableName.powerData)) {
                                        stringBuilderMax.append("from ").append(tableName).append("_add_Real").append(" where").append(" LineId='").append(lineId).append("'").append(" and Phase='" + tmpPhase + "'").append(" order by time");
                                    } else {
                                        stringBuilderMax.append("from ").append(tableName).append("_Real").append(" where").append(" LineId='").append(lineId).append("'").append(" and Phase='" + tmpPhase + "'").append(" order by time");
                                    }
                                    List<Map<String, Object>> list = influxDbUtils.getResult(stringBuilderMax.toString(), "");
                                    if (CollectionUtil.isNotEmpty(list)) {
                                        for(int i=0;i<list.size();i++){
                                            Map<String, Object> mapRes = new HashMap<>();
                                            list.get(i).forEach((key, value) -> {
                                                if(Objects.nonNull(value)){
                                                    mapRes.put(key,value);
                                                }
                                            });

                                            for (int j = 0; j < enList.size(); j++) {
                                                if(mapRes.containsKey(enList.get(j).getName())) {

                                                    enList.get(j).setTime(mapRes.get("time").toString());
                                                    enList.get(j).setDataValue(mapRes.get(enList.get(j).getName()).toString());
                                                }
                                            }
                                        }
                                    }
                                });


                            } else if (TableName.eleCtrl.equals(className) || TableName.eleSts.equals(className)) {
                                //展示空调数据
                                StringBuilder stringBuilderMax = new StringBuilder("select ");

                                for (int j = 0; j < listData.size(); j++) {
                                    if (j == listData.size() - 1) {
                                        stringBuilderMax.append(listData.get(j).getName()).append(" ");
                                    } else {
                                        stringBuilderMax.append(listData.get(j).getName()).append(", ");
                                    }
                                }
                                stringBuilderMax.append("from ").append(tableName + "_Real").append(" where").append(" LineId='" + lineId + "'").append(" order by time");
                                List<Map<String, Object>> list = influxDbUtils.getResult(stringBuilderMax.toString(), "");
                                if (CollectionUtil.isNotEmpty(list)) {
                                    for(int i=0;i<list.size();i++){
                                        Map<String, Object> mapRes = new HashMap<>();
                                        list.get(i).forEach((key, value) -> {
                                            if(Objects.nonNull(value)){
                                                mapRes.put(key,value);
                                            }
                                        });

                                        for (int j = 0; j < listData.size(); j++) {
                                            if(mapRes.containsKey(listData.get(j).getName())) {

                                                listData.get(j).setTime(mapRes.get("time").toString());
                                                listData.get(j).setDataValue(mapRes.get(listData.get(j).getName()).toString());
                                            }
                                        }
                                    }
                                }

                            }
                        }

                        listDataAll.addAll(listData);
                    }

                });
                List<DataGroupTemplateVO> grList = groupList.stream().peek((item) -> {
                    item.setChildren(getChildrenes(item.getId(), listDataAll));
                }).collect(Collectors.toList());
                pageTurn.setRecords(grList);
                pageTurn.setTotal(pageRes.getTotal());
                pageTurn.setSize(pageRes.getSize());
                pageTurn.setCurrent(pageRes.getCurrent());
                pageTurn.setPages(pageRes.getPages());
                return pageTurn;
            } else {
                throw new BusinessException(CommonResponseEnum.FAIL);
            }


        } else {
            pageTurn.setRecords(new ArrayList<>());
            pageTurn.setTotal(pageRes.getTotal());
            pageTurn.setSize(pageRes.getSize());
            pageTurn.setCurrent(pageRes.getCurrent());
            pageTurn.setPages(pageRes.getPages());
            return pageTurn;
        }

    }


    @Override
    public List<DataSet> getTabTemplateById(String id) {
        return logicDeviceLineMapper.getTabTemplateById(id);
    }


    @Override
    public List<DataGroupTemplateVO> getGroupDetailList(String setId) {
        List<DataGroupTemplateVO> groupList = dataGroupMapper.getGroupList(setId);
        if (CollectionUtil.isNotEmpty(groupList)) {
            List<EnergyTemplateVO> arrList = logicDeviceLineMapper.getAllDataBySet(setId);
            if (CollectionUtil.isNotEmpty(arrList)) {
                return groupList.stream().peek((item -> item.setChildren(getChildrenes(item.getId(), arrList)))).collect(Collectors.toList());
            } else {
                throw new BusinessException(CommonResponseEnum.FAIL);
            }
        } else {
            throw new BusinessException(CommonResponseEnum.FAIL);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addGroupArr(GroupArrParam groupArrParam) {
        List<GroupArrParam.ArrItem> list = groupArrParam.getData();
        List<String> groupIdList = list.stream().map(GroupArrParam.ArrItem::getId).collect(Collectors.toList());
        LambdaQueryWrapper<GroupArray> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(GroupArray::getGroupId, groupIdList);
        groupArrMapper.delete(lambdaQueryWrapper);

        dataGroupMapper.deleteBatchIds(groupIdList);

        List<DataGroup> listGroup = new ArrayList<>();
        List<GroupArray> arrList = new ArrayList<>();

        Integer sort = 0;
        for (GroupArrParam.ArrItem item : list) {
            if (CollectionUtil.isNotEmpty(item.getChildren())) {
                DataGroup dataGroup = new DataGroup();
                dataGroup.setId(IdUtil.simpleUUID());
                dataGroup.setName(item.getName());
                dataGroup.setPid(groupArrParam.getSetId());
                dataGroup.setSort(sort);
                sort++;

                listGroup.add(dataGroup);

                for (String idItem : item.getChildren()) {
                    GroupArray groupArr = new GroupArray();
                    groupArr.setGroupId(dataGroup.getId());
                    groupArr.setArrId(idItem);
                    arrList.add(groupArr);
                }
            }
        }
        iDataGroupService.batchAdd(listGroup);
        iGroupArrayService.batchAdd(arrList);

        return true;
    }


    @Override
    public List<String> getParseTemplate(String setId) {
        return logicDeviceLineMapper.getParseTemplate(setId);
    }


    @Override
    public LogicDev add(DevCfgParam devCfgParam) {
        LogicDev logicDev = new LogicDev();
        BeanUtil.copyProperties(devCfgParam, logicDev);
        logicDev.setState(DataStateEnum.ENABLE.getCode());
        logicDev.setCreateTime(LocalDateTime.now());
        this.save(logicDev);
        return logicDev;
    }

    @Override
    public LogicDev getLogicDev(String did) {
        return this.lambdaQuery().eq(LogicDev::getDid, did).eq(LogicDev::getState, DataStateEnum.ENABLE.getCode()).one();
    }

    @Override
    public List<LogicDev> getLogicDevByList(List<String> list) {
        return this.lambdaQuery().in(LogicDev::getPid, list).ne(LogicDev::getType,"ACgw").list();
    }

    @Override
    public List<LogicDev> getLogicDev(List<String> list) {
        return this.lambdaQuery().in(LogicDev::getDid, list).list();
    }

    @Override
    public List<LogicDev> getLogicDevByPid(List<String> list) {
        return this.lambdaQuery().in(LogicDev::getPid, list).eq(LogicDev::getState, DataStateEnum.ENABLE.getCode()).list();
    }

    @Override
    public boolean deleteByVersionId(String id) {
        QueryWrapper<LogicDev> logicDevQueryWrapper = new QueryWrapper<>();
        logicDevQueryWrapper.eq("Version_Id", id);
        return this.remove(logicDevQueryWrapper);
    }

    @Override
    public List<LogicDev> getLogicDevByVersionId(String id) {
        return this.lambdaQuery().eq(LogicDev::getVersionId, id).eq(LogicDev::getState, DataStateEnum.ENABLE.getCode()).list();
    }

    @Override
    public void updateLogicDeviceLine(LogicDev logicDev) {
        this.updateById(logicDev);
    }

    @Override
    public void updateLogicDevice(String oldMouldId, String newMouldId) {
        this.lambdaUpdate().set(LogicDev::getIdx, newMouldId).eq(LogicDev::getIdx, oldMouldId).update();
    }

    @Override
    public List<DataHisVO> getHisData(DataHisParam dataHisParam) {

        LocalDateTime startTime = PubUtils.beginTimeToLocalDateTime(dataHisParam.getStartTime());
        String start = startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime endTime = PubUtils.endTimeToLocalDateTime(dataHisParam.getEndTime());
        String end = endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        List<String> arrList = dataHisParam.getArrName();
        List<DataHisVO> listRes = new ArrayList<>();

        LambdaQueryWrapper<DataArray> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(DataArray::getDataId, arrList);
        lambdaQueryWrapper.orderByAsc(true,DataArray::getIdx);
        List<DataArray> list = dataArrayMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            String table;
            if(list.get(0).getClassName().equals(TableName.eleMd)){
                table =  list.get(0).getClassId();
            }else{
                table =  list.get(0).getClassId()+"_add";
            }
            for (int i = 0; i < list.size(); i++) {

                StringBuilder stringBuilder = new StringBuilder("select ");
                stringBuilder.append(list.get(i).getName());
                stringBuilder.append(" from ").append(table).append(" where ").append("LineId='").append(dataHisParam.getLineId()).append("'");
                String ph = "";
                if (!"M".equals(list.get(i).getPhase())) {
                    //有相别
                    ph = list.get(i).getPhase();
                    stringBuilder.append("and Phase = '").append(list.get(i).getPhase()).append("'");
                }
                stringBuilder.append(" and time>'").append(start).append("'").append(" and time < '").append(end).append("'").append(" ORDER BY time");
                List<Map<String, Object>> listMap = influxDbUtils.getResult(stringBuilder.toString(),"");

                if (CollectionUtil.isNotEmpty(listMap)) {
                    DataHisVO dataHisVO = new DataHisVO();
                    dataHisVO.setName(list.get(i).getName());
                    dataHisVO.setAnotherName(ph + list.get(i).getAnotherName());

                    List<List<String>> temX = new ArrayList<>();

                    for(Map<String, Object> map :listMap){
                        if(map.get(list.get(i).getName()).toString().equals("-1000000.0")){
                            continue;
                        }
                        List<String> tem = new ArrayList<>();
                        tem.add(map.get("time").toString());
                        tem.add(map.get(list.get(i).getName()).toString());

                        temX.add(tem);
                    }
                    dataHisVO.setValue(temX);
                    listRes.add(dataHisVO);
                }

            }
        }


        return listRes;

    }


    @Override
    public List<NetAndDevByLineDTO> getNetAndDevByLineIds(List<String> lineIds){
        return logicDeviceLineMapper.getNetAndDevByLineIds(lineIds);
    }

    private List<EnergyDeviceTreeVO> getChildren(EnergyDeviceTreeVO energyDeviceTreeVO, List<EnergyDeviceTreeVO> all) {
        return all.stream().filter(item -> item.getPid().equals(energyDeviceTreeVO.getId())).collect(Collectors.toList());
    }

    private List<EnergyTemplateVO> getChildrenes(String tabId, List<EnergyTemplateVO> all) {
        return all.stream().filter(item -> item.getPid().equals(tabId)).collect(Collectors.toList());
    }


}


/**
 * 拼接监测点
 */
