package com.yfd.platform.modules.basedata.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfd.platform.modules.auxcontrol.domain.DeviceSignal;
import com.yfd.platform.modules.auxcontrol.service.IDeviceSignalService;
import com.yfd.platform.modules.basedata.domain.*;
import com.yfd.platform.modules.basedata.mapper.*;
import com.yfd.platform.modules.basedata.service.ISubstationMaindeviceService;
import com.yfd.platform.system.domain.SysDictionary;
import com.yfd.platform.system.domain.SysDictionaryItems;
import com.yfd.platform.system.service.ISysDictionaryItemsService;
import com.yfd.platform.system.service.ISysDictionaryService;
import com.yfd.platform.utils.SecurityUtils;
import freemarker.template.utility.NullArgumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 变电站_主设备 服务实现类
 * </p>
 *
 *
 * @since 2023-03-28
 */
@Transactional
@Service
public class SubstationMaindeviceServiceImpl extends ServiceImpl<SubstationMaindeviceMapper, SubstationMaindevice> implements ISubstationMaindeviceService {

    @Resource
    private SubstationComponentMapper substationComponentMapper;

    @Resource
    private SubstationBayMapper substationBayMapper;

    @Resource
    private SubstationMapper substationMapper;
    @Resource
    private SubstationAreaMapper substationAreaMapper;
    @Resource
    private SubstationDeviceMapper substationDeviceMapper;
    @Resource
    private ISysDictionaryService sysDictionaryService;

    @Resource
    private ISysDictionaryItemsService sysDictionaryItemsService;

    @Resource
    private IDeviceSignalService deviceSignalService;

    /**********************************
     * 用途说明: 获取主设备及部件树
     * 参数说明 name 参数名称
     * 返回值说明: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     ***********************************/
    @Override
    public List<Map<String, Object>> getMainDeviceTree(String bayId, String name) {
        LambdaQueryWrapper<SubstationMaindevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationMaindevice::getBayId, bayId);
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like(SubstationMaindevice::getMainDeviceName, name).orderByAsc(SubstationMaindevice::getCustom1);
            List<Map<String, Object>> list = this.listMaps(queryWrapper);
            list.forEach(l -> l.put("type", "主设备"));
            LambdaQueryWrapper<SubstationComponent> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SubstationComponent::getBayId, bayId).like(SubstationComponent::getComponentName, name).orderByAsc(SubstationComponent::getCustom1);
            List<Map<String, Object>> maps = substationComponentMapper.selectMaps(queryWrapper1);
            maps.forEach(m -> m.put("type", "部件"));
            list.addAll(maps);
            return list;
        }
        queryWrapper.orderByAsc(SubstationMaindevice::getCustom1);
        List<Map<String, Object>> list = this.listMaps(queryWrapper);
        List<Map<String, Object>> listMainDevice = new ArrayList<>();
        for (Map<String, Object> map : list) {
            map.put("type", "主设备");
            String mainDeviceId = (String) map.get("mainDeviceId");
            LambdaQueryWrapper<SubstationComponent> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SubstationComponent::getMainDeviceId, mainDeviceId);
           /* if (StrUtil.isNotBlank(name)) {
                queryWrapper1.like(SubstationComponent::getComponentName, name);
            }*/
            queryWrapper1.orderByAsc(SubstationComponent::getCustom1);
            List<Map<String, Object>> list1 = substationComponentMapper.selectMaps(queryWrapper1);
            map.put("count", list1.size());
            List<Map<String, Object>> listComponent = new ArrayList<>();
            for (Map<String, Object> stringObjectMap : list1) {
                stringObjectMap.put("type", "部件");
                listComponent.add(stringObjectMap);
            }
            if (listComponent.size() > 0) {
                map.put("children", listComponent);
            }
            listMainDevice.add(map);
        }
        return listMainDevice;
    }

    /**********************************
     * 用途说明: 修改主设备状态
     * 参数说明 id 主设备id
     * 参数说明 dataStatus 修改的状态
     * 返回值说明: boolean
     ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setMainDeviceStatus(String id, String dataStatus) {
        SubstationMaindevice substationMaindevice = this.getById(id);
        substationMaindevice.setDatastatus(dataStatus);
        substationMaindevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationMaindevice.setLastmodifydate(LocalDateTime.now());
        // 修改部件状态
        boolean ok = this.updateById(substationMaindevice);
        if ("0".equals(dataStatus)) {
            // 获取所有部件信息
            List<SubstationComponent> substationComponents =
                    substationComponentMapper.selectList(new LambdaQueryWrapper<SubstationComponent>().eq(SubstationComponent::getMainDeviceId, id));
            for (SubstationComponent substationComponent : substationComponents) {
                substationComponent.setDatastatus(dataStatus);
                substationComponent.setLastmodifier(SecurityUtils.getCurrentUsername());
                substationComponent.setLastmodifydate(LocalDateTime.now());
                substationComponentMapper.updateById(substationComponent);
            }
        }
        return ok;
    }

    /**********************************
     * 用途说明: 删除主设备
     * 参数说明 id 主设备id
     * 返回值说明: boolean
     ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMainDevice(String id) {

        Integer integer =
                substationComponentMapper.selectCount(new LambdaQueryWrapper<SubstationComponent>().eq(SubstationComponent::getMainDeviceId, id));
        if (integer > 0) {
            throw new RuntimeException("当前主设备已经绑定部件无法删除");
        }

        SubstationMaindevice substationMaindevice = this.getById(id);
        // 如果是启用状态不允许删除
        if ("1".equals(substationMaindevice.getDatastatus())) {
            return false;
        }
//        LambdaQueryWrapper<SubstationComponent> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(SubstationComponent::getMainDeviceId, id);
//        substationComponentMapper.delete(queryWrapper);
        boolean ok = this.removeById(id);
        String bayId = substationMaindevice.getBayId();
        List<SubstationMaindevice> list =
                list(new LambdaQueryWrapper<SubstationMaindevice>().eq(SubstationMaindevice::getBayId, bayId).orderByAsc(SubstationMaindevice::getCustom1));
        for (int i = 0; i < list.size(); i++) {
            SubstationMaindevice substationMaindevice1 = list.get(i);
            substationMaindevice1.setCustom1(i + 1);
            this.updateById(substationMaindevice1);
        }
        return ok;
    }

    /**********************************
     * 用途说明: 新增部件
     * 参数说明 substationComponent 部件对象
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean addComponent(SubstationComponent substationComponent) {
        substationComponent.setDatastatus("1");
        substationComponent.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationComponent.setLastmodifydate(LocalDateTime.now());
        int insert = substationComponentMapper.insert(substationComponent);
        return insert > 0;
    }

    /**********************************
     * 用途说明: 根据Id获取部件
     * 参数说明 componentId 部件id
     * 返回值说明: com.yfd.platform.basedata.domain.SubstationComponent
     ***********************************/
    @Override
    public SubstationComponent getComponentById(String componentId) {
        return substationComponentMapper.selectById(componentId);
    }

    /**********************************
     * 用途说明: 修改部件
     * 参数说明 substationComponent 部件对象
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean updateComponent(SubstationComponent substationComponent) {
        substationComponent.setDatastatus("1");
        substationComponent.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationComponent.setLastmodifydate(LocalDateTime.now());
        int insert = substationComponentMapper.updateById(substationComponent);
        return insert > 0;
    }

    /**********************************
     * 用途说明: 修改部件状态
     * 参数说明 componentId 部件id
     * 参数说明 dataStatus  修改的状态
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean setComponentStatus(String componentId, String dataStatus) {
        SubstationComponent substationComponent = substationComponentMapper.selectById(componentId);
        if ("1".equals(dataStatus)) {
            String mainDeviceId = substationComponent.getMainDeviceId();
            SubstationMaindevice substationMaindevice = this.getById(mainDeviceId);
            String datastatus = substationMaindevice.getDatastatus();
            if (!dataStatus.equals(datastatus)) {
                substationMaindevice.setDatastatus(dataStatus);
                this.updateById(substationMaindevice);
            }
        }
        substationComponent.setDatastatus(dataStatus);
        substationComponent.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationComponent.setLastmodifydate(LocalDateTime.now());
        int i = substationComponentMapper.updateById(substationComponent);
        return i > 0;
    }

    /**********************************
     * 用途说明: 删除部件
     * 参数说明 componentId 部件id
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean deleteComponent(String componentId) {
        SubstationComponent substationComponent = substationComponentMapper.selectById(componentId);
        // 如果是启用状态不允许删除
        if ("1".equals(substationComponent.getDatastatus())) {
            return false;
        }
        LambdaQueryWrapper<SubstationDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationDevice::getComponentId, componentId);
        Integer integer = substationDeviceMapper.selectCount(queryWrapper);
        if (integer > 0) {
            throw new RuntimeException("当前部件已经绑定点位无法删除");
        }
        int i = substationComponentMapper.deleteById(componentId);
        String mainDeviceId = substationComponent.getMainDeviceId();
        List<SubstationComponent> list =
                substationComponentMapper.selectList(new LambdaQueryWrapper<SubstationComponent>().eq(SubstationComponent::getMainDeviceId, mainDeviceId).orderByAsc(SubstationComponent::getCustom1));
        for (int j = 0; j < list.size(); j++) {
            SubstationComponent substationComponent1 = list.get(j);
            substationComponent1.setCustom1(j + 1);
            substationComponentMapper.updateById(substationComponent1);
        }
        return i > 0;
    }

    /**********************************
     * 用途说明: 导入文件
     * 参数说明 file
     * 参数说明 type 主设备,部件
     * 返回值说明: java.lang.String
     ***********************************/
    @Override
    public String uploadExcel(MultipartFile file, String type) throws Exception {
        if (file == null) {
            throw new NullArgumentException();
        }
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new NullArgumentException();
        }
        String a = "";
        try {
            // 调用解析文件方法
            a = parseRowCell(filename, file.getInputStream(), type);
            return a;
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }

    }

    /**********************************
     * 用途说明: 获取部件
     * 参数说明
     * 返回值说明: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     ***********************************/
    @Override
    public List<Map<String, Object>> getComponent(String mainDeviceId, String bayId, String componentName) {
        LambdaQueryWrapper<SubstationComponent> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(mainDeviceId)) {
            queryWrapper.eq(SubstationComponent::getMainDeviceId, mainDeviceId);
        }
        if (StrUtil.isNotBlank(bayId)) {
            queryWrapper.eq(SubstationComponent::getBayId, bayId);
        }
        if (StrUtil.isNotBlank(componentName)) {
            queryWrapper.like(SubstationComponent::getComponentName, componentName);
        }
        queryWrapper.eq(SubstationComponent::getDatastatus, "1");
        queryWrapper.select(SubstationComponent::getComponentId, SubstationComponent::getComponentName,
                SubstationComponent::getAreaId, SubstationComponent::getAreaName,
                SubstationComponent::getMainDeviceId, SubstationComponent::getMainDeviceName,
                SubstationComponent::getStationCode, SubstationComponent::getStationName,
                SubstationComponent::getBayId, SubstationComponent::getBayName);
        return substationComponentMapper.selectMaps(queryWrapper);
    }

    /**********************************
     * 用途说明: 获取当前主设备类型
     * 参数说明 deviceType
     * 返回值说明: com.yfd.platform.system.domain.SysDictionaryItems
     ***********************************/
    @Override
    public SysDictionaryItems getMainDeviceType(String deviceType) {
        LambdaQueryWrapper<SysDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictionary::getDictCode, "EquipmentType");
        // 获取类型
        List<SysDictionary> list = sysDictionaryService.list(queryWrapper);
        if (list.size() <= 0) {
            return null;
        }
        SysDictionary sysDictionary = list.get(0);
        String id = sysDictionary.getId();
        SysDictionaryItems sysDictionaryItems =
                sysDictionaryItemsService.getOne(new LambdaQueryWrapper<SysDictionaryItems>().eq(SysDictionaryItems::getItemCode, deviceType).eq(SysDictionaryItems::getDictId, id));
        return sysDictionaryItems;
    }

    /**********************************
     * 用途说明: 获取主设备类型集合
     * 参数说明
     * 返回值说明: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     ***********************************/
    @Override
    public List<Map<String, Object>> getDeviceType() {
        LambdaQueryWrapper<SysDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictionary::getDictCode, "EquipmentType");
        // 获取类型
        List<SysDictionary> list = sysDictionaryService.list(queryWrapper);
        SysDictionary sysDictionary = list.get(0);
        String id = sysDictionary.getId();
        LambdaQueryWrapper<SysDictionaryItems> eq =
                new LambdaQueryWrapper<SysDictionaryItems>().eq(SysDictionaryItems::getDictId, id).select(SysDictionaryItems::getId, SysDictionaryItems::getDictName, SysDictionaryItems::getItemCode);
        List<Map<String, Object>> listItems = sysDictionaryItemsService.listMaps(eq);
        return listItems;
    }

    /**********************************
     * 用途说明: 获取间隔下的部件
     * 参数说明 bayId 间隔Id
     * 返回值说明: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     ***********************************/
    @Override
    public List<Map<String, Object>> getComponentByBay(String bayId) {
        LambdaQueryWrapper<SubstationComponent> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(bayId)) {
            queryWrapper.eq(SubstationComponent::getBayId, bayId);
        }
        queryWrapper.eq(SubstationComponent::getDatastatus, "1");
        queryWrapper.select(SubstationComponent::getComponentId, SubstationComponent::getComponentName);
        return substationComponentMapper.selectMaps(queryWrapper);
    }

    /**********************************
     * 用途说明: 解析文件方法
     * 参数说明 filename 文件名
     * 参数说明 inputStream
     * 返回值说明: java.lang.String
     ***********************************/
    private String parseRowCell(String filename, InputStream inputStream, String type) {
        try {
            Workbook workbook = null;
            // 判断excel的后缀，不同的后缀用不同的对象去解析
            // xls是低版本的Excel文件
            if (filename.endsWith(".xls")) {
                workbook = new HSSFWorkbook(inputStream);
            }
            // xlsx是高版本的Excel文件
            if (filename.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(inputStream);
            }
            if (workbook == null) {
                throw new RuntimeException("上传失败");
            }

            // 取到excel 中的第一张工作表
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new NullArgumentException();
            }
            List<Map<String, Object>> equipmentType = sysDictionaryItemsService.getDeviceByType(
                    "EquipmentType");
            // 工作表中第一行是表头，不获取，从第二行开始获取
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                // 获取到这一行的数据
                Row row = sheet.getRow(rowNum);
                if (row == null || row.getCell(0) == null) {
                    continue;
                }
                if (StrUtil.isBlank(row.getCell(0).toString())) {
                    continue;
                }
                if ("01".equals(type)) {
                    SubstationMaindevice substationMaindevice = new SubstationMaindevice();
                    // 主设备状态
                    substationMaindevice.setDatastatus("1");

                    // 变电站编号
                    String stationCode = "";
                    if (row.getCell(1) != null) {
                        row.getCell(1).setCellType(CellType.STRING);
                        stationCode = row.getCell(1).getStringCellValue().trim();
                        substationMaindevice.setStationCode(stationCode);
                    }
                    // 变电站名称
                    String stationName = "";
                    if (row.getCell(2) != null) {
                        row.getCell(2).setCellType(CellType.STRING);
                        stationName = row.getCell(2).getStringCellValue().trim();
                        substationMaindevice.setStationName(stationName);
                    }
                    // 区域名称
                    String areaName = "";
                    if (row.getCell(3) != null) {
                        row.getCell(3).setCellType(CellType.STRING);
                        areaName = row.getCell(3).getStringCellValue().trim();
                        substationMaindevice.setAreaName(areaName);
                    }
                    // 间隔名称
                    String bayName = "";
                    if (row.getCell(4) != null) {
                        row.getCell(4).setCellType(CellType.STRING);
                        bayName = row.getCell(4).getStringCellValue().trim();
                        substationMaindevice.setBayName(bayName);
                    }
                    // 主设备名称
                    String mainDeviceName = "";
                    if (row.getCell(5) != null) {
                        row.getCell(5).setCellType(CellType.STRING);
                        mainDeviceName = row.getCell(5).getStringCellValue().trim();
                        substationMaindevice.setMainDeviceName(mainDeviceName);
                    }
                    // (主设备类型)，赋值给deviceType
                    String dictType = "";
                    if (row.getCell(6) != null) {
                        row.getCell(6).setCellType(CellType.STRING);
                        dictType = row.getCell(6).getStringCellValue().trim();
                    }
                    dictType = dictType.trim();
                    boolean isBool = false;
                    if (StrUtil.isNotBlank(dictType)) {

                        for (Map<String, Object> map : equipmentType) {
                            String dictname = map.get("dictname").toString();
                            if (dictType.equals(dictname)) {
                                String itemcode = map.get("itemcode").toString();
                                substationMaindevice.setDeviceType(itemcode);
                                isBool = true;
                                break;
                            }
                        }
                    }
                    if (!isBool) {
                        if (row.getCell(0) != null) {
                            row.getCell(0).setCellType(CellType.STRING);
                            throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() +
                                    "：不存在该主设备类型,请检查");
                        }
                    }
                    // 实物ID
                    String materialId = "";
                    if (row.getCell(7) != null) {
                        row.getCell(7).setCellType(CellType.STRING);
                        materialId = row.getCell(7).getStringCellValue().trim();
                        substationMaindevice.setMaterialId(materialId);
                    }
                    // 间隔id
                    LambdaQueryWrapper<SubstationBay> bayQueryWrapper = new LambdaQueryWrapper<>();
                    bayQueryWrapper.eq(SubstationBay::getStationCode, stationCode).eq(SubstationBay::getStationName,
                            stationName).eq(SubstationBay::getAreaName,
                            areaName).eq(SubstationBay::getBayName, bayName);
                    List<SubstationBay> bayList = substationBayMapper.selectList(bayQueryWrapper);
                    if (bayList == null || bayList.size() == 0) {
                        if (row.getCell(0) != null) {
                            row.getCell(0).setCellType(CellType.STRING);
                            throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() +
                                    "：数据不正确,请检查");
                        }
                    }
                    SubstationBay substationBay = bayList.get(0);
                    String areaId = substationBay.getAreaId();
                    substationMaindevice.setAreaId(areaId);
                    String bayId = substationBay.getBayId();
                    substationMaindevice.setBayId(bayId);
                    int count =
                            this.count(new LambdaQueryWrapper<SubstationMaindevice>().eq(SubstationMaindevice::getMainDeviceName, mainDeviceName));
                    if (count > 0) {
                        if (row.getCell(0) != null) {
                            row.getCell(0).setCellType(CellType.STRING);
                            throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() +
                                    "：当前主设备已经存在,请检查");
                        }
                    }
                    int count1 =
                            this.count(new LambdaQueryWrapper<SubstationMaindevice>().eq(SubstationMaindevice::getBayId, bayId)) + 1;
                    substationMaindevice.setCustom1(count1);
                    substationMaindevice.setLastmodifier(SecurityUtils.getCurrentUsername());
                    substationMaindevice.setLastmodifydate(LocalDateTime.now());
                    boolean ok = this.save(substationMaindevice);
                    if (!ok) {
                        if (row.getCell(0) != null) {
                            row.getCell(0).setCellType(CellType.STRING);
                            throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() + "：导入失败,请检查");
                        }
                    }
                } else {
                    SubstationComponent substationComponent = new SubstationComponent();
                    // 部件状态
                    substationComponent.setDatastatus("1");
                    // 变电站编号
                    String stationCode = "";
                    if (row.getCell(1) != null) {
                        row.getCell(1).setCellType(CellType.STRING);
                        stationCode = row.getCell(1).getStringCellValue().trim();
                        substationComponent.setStationCode(stationCode);
                    }
                    // 变电站名称
                    String stationName = "";
                    if (row.getCell(2) != null) {
                        row.getCell(2).setCellType(CellType.STRING);
                        stationName = row.getCell(2).getStringCellValue().trim();
                        substationComponent.setStationName(stationName);
                    }
                    // 区域名称
                    String areaName = "";
                    if (row.getCell(3) != null) {
                        row.getCell(3).setCellType(CellType.STRING);
                        areaName = row.getCell(3).getStringCellValue().trim();
                        substationComponent.setAreaName(areaName);
                    }
                    // 间隔名称
                    String bayName = "";
                    if (row.getCell(4) != null) {
                        row.getCell(4).setCellType(CellType.STRING);
                        bayName = row.getCell(4).getStringCellValue().trim();
                        substationComponent.setBayName(bayName);
                    }
                    // 主设备名称
                    String mainDeviceName = "";
                    if (row.getCell(5) != null) {
                        row.getCell(5).setCellType(CellType.STRING);
                        mainDeviceName = row.getCell(5).getStringCellValue().trim();
                        substationComponent.setMainDeviceName(mainDeviceName);
                    }
                    // (部件名称)，赋值给componentName
                    String componentName = "";
                    if (row.getCell(6) != null) {
                        row.getCell(6).setCellType(CellType.STRING);
                        componentName = row.getCell(6).getStringCellValue().trim();
                        substationComponent.setComponentName(componentName);
                    }

                    // 实物ID
                    String materialId = "";
                    if (row.getCell(7) != null) {
                        row.getCell(7).setCellType(CellType.STRING);
                        materialId = row.getCell(7).getStringCellValue().trim();
                        substationComponent.setMaterialId(materialId);
                    }
                    List<SubstationMaindevice> list1 =
                            this.list(new LambdaQueryWrapper<SubstationMaindevice>().eq(SubstationMaindevice::getStationCode, stationCode).eq(SubstationMaindevice::getStationName, stationName).eq(SubstationMaindevice::getAreaName, areaName).eq(SubstationMaindevice::getBayName, bayName).eq(SubstationMaindevice::getMainDeviceName, mainDeviceName));
                    if (list1 == null || list1.size() == 0) {
                        if (row.getCell(0) != null) {
                            row.getCell(0).setCellType(CellType.STRING);
                            throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() +
                                    "：数据不正确,请检查");
                        }
                    }
                    SubstationMaindevice substationMaindevice = list1.get(0);
                    substationComponent.setAreaId(substationMaindevice.getAreaId());
                    substationComponent.setBayId(substationMaindevice.getBayId());
                    substationComponent.setMainDeviceId(substationMaindevice.getMainDeviceId());
                    // 主设备类型
                    substationComponent.setDeviceType(substationMaindevice.getDeviceType());
                    // 主设备id
                    substationComponent.setMainDeviceId(substationMaindevice.getMainDeviceId());
                    int count =
                            substationComponentMapper.selectCount(new LambdaQueryWrapper<SubstationComponent>().eq(SubstationComponent::getMainDeviceId, substationMaindevice.getMainDeviceId()).eq(SubstationComponent::getComponentName, componentName));
                    if (count > 0) {
                        if (row.getCell(0) != null) {
                            row.getCell(0).setCellType(CellType.STRING);
                            throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() +
                                    "：当前部件已经存在,请检查");
                        }
                    }
                    int count1 =
                            substationComponentMapper.selectCount(new LambdaQueryWrapper<SubstationComponent>().eq(SubstationComponent::getBayId, substationMaindevice.getMainDeviceId())) + 1;
                    substationComponent.setCustom1(count1);
                    // 最近修改人
                    substationComponent.setLastmodifier(SecurityUtils.getCurrentUsername());
                    // 修改时间
                    substationComponent.setLastmodifydate(LocalDateTime.now());
                    int insert = substationComponentMapper.insert(substationComponent);
                    if (insert <= 0) {
                        if (row.getCell(0) != null) {
                            row.getCell(0).setCellType(CellType.STRING);
                            throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() + "：新增失败,请检查");
                        }
                    }
                }

            }
            return "";
        } catch (IOException e) {
            return e.getMessage();
        }
    }

    /**********************************
     * 用途说明: 获取主设备导航树
     * 参数说明 stationCode
     * 返回值说明: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     ***********************************/
    @Override
    public List<Map<String, Object>> getSubstationMainDeviceTree(String stationCode, String mainDeviceName) {
        LambdaQueryWrapper<SubstationMaindevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationMaindevice::getStationCode, stationCode).eq(SubstationMaindevice::getDatastatus, "1");
        if (StrUtil.isNotBlank(mainDeviceName)) {
            queryWrapper.like(SubstationMaindevice::getMainDeviceName, mainDeviceName);
        }
        List<SubstationMaindevice> list = this.list(queryWrapper);
        Map<String, List<SubstationMaindevice>> collect =
                list.stream().collect(Collectors.groupingBy(SubstationMaindevice::getAreaName));
        List<Map<String, Object>> mainDeviceTree = new ArrayList<>();
        for (String areaName : collect.keySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", areaName);
            List<SubstationMaindevice> substationMaindevices = collect.get(areaName);
            Map<String, List<SubstationMaindevice>> collect1 =
                    substationMaindevices.stream().collect(Collectors.groupingBy(SubstationMaindevice::getBayName));
            List<Map<String, Object>> areaTree = new ArrayList<>();
            for (String bayName : collect1.keySet()) {
                Map<String, Object> bayMap = new HashMap<>();
                bayMap.put("name", bayName);
                List<SubstationMaindevice> substationMaindevices1 = collect1.get(bayName);
                bayMap.put("children", substationMaindevices1);
                areaTree.add(bayMap);
            }
            map.put("children", areaTree);
            mainDeviceTree.add(map);
        }
        return mainDeviceTree;
    }

    /**********************************
     * 用途说明: 获取主设备树（前台）
     * 参数说明 stationCode 变电站编号
     * 参数说明 mainDeviceName 主设备名称
     * 返回值说明: com.yfd.platform.modules.basedata.domain.TreeNode
     ***********************************/
    @Override
    public TreeNode getSubstationMainTree(String stationCode, String mainDeviceName) {

        LambdaQueryWrapper<SubstationMaindevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationMaindevice::getStationCode, stationCode);
        if (StrUtil.isNotBlank(mainDeviceName)) {
            queryWrapper.like(SubstationMaindevice::getMainDeviceName, mainDeviceName);
        }
        queryWrapper.select(SubstationMaindevice::getStationCode,
                SubstationMaindevice::getStationName, SubstationMaindevice::getStationName,
                SubstationMaindevice::getAreaId,
                SubstationMaindevice::getAreaName, SubstationMaindevice::getBayId, SubstationMaindevice::getBayName,
                SubstationMaindevice::getMainDeviceId, SubstationMaindevice::getMainDeviceName);
        List<Map<String, Object>> list = this.listMaps(queryWrapper);
        List<Map<String, Object>> mapList = list.stream().distinct().collect(Collectors.toList());
        List<TreeNode> treeNodes = this.buildTree(mapList);
        return treeNodes.get(0);
    }

    /**********************************
     * 用途说明: 获取信号树（前台）
     * 参数说明 stationCode 变电站编号
     * 参数说明 signalName 信号名称
     * 返回值说明: java.util.List<com.yfd.platform.modules.basedata.domain.TreeNode>
     ***********************************/
    @Override
    public List<TreeNode> getDeviceSignalTree(String stationCode, String signalName) {
        List<Map<String, Object>> dataList = deviceSignalService.getDeviceSignalMaps(stationCode, signalName);
        List<TreeNode> treeNodes = this.buildSignalTree(dataList);
        if (treeNodes.size() <= 0) {
            return treeNodes;
        }
        return treeNodes.get(0).getChildren();
    }

    /**********************************
     * 用途说明: 获取部件树（前台）
     * 参数说明 stationCode 变电站编号
     * 参数说明 componentName 信号名称
     * 返回值说明: java.util.List<com.yfd.platform.modules.basedata.domain.TreeNode>
     ***********************************/
    @Override
    public List<TreeNode> getComponentTree(String stationCode, String componentName) {
        LambdaQueryWrapper<SubstationComponent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(stationCode), SubstationComponent::getStationCode, stationCode);
        queryWrapper.like(StrUtil.isNotBlank(componentName), SubstationComponent::getComponentName, componentName);
        queryWrapper.select(SubstationComponent::getStationCode,
                SubstationComponent::getStationName, SubstationComponent::getStationName,
                SubstationComponent::getAreaId,
                SubstationComponent::getAreaName, SubstationComponent::getBayId, SubstationComponent::getBayName,
                SubstationComponent::getMainDeviceId, SubstationComponent::getMainDeviceName,
                SubstationComponent::getComponentId, SubstationComponent::getComponentName);
        List<Map<String, Object>> dataList = substationComponentMapper.selectMaps(queryWrapper);
        List<TreeNode> treeNodes = buildComponentTree(dataList);
        if (treeNodes.size() <= 0) {
            return treeNodes;
        }
        return treeNodes.get(0).getChildren();
    }

    /**********************************
     * 用途说明: 构造树
     * 参数说明 dataList 名称
     * 返回值说明: java.util.List<com.yfd.platform.modules.basedata.domain.TreeNode>
     ***********************************/
    public List<TreeNode> buildComponentTree(List<Map<String, Object>> dataList) {
        // 存储所有节点（使用ID作为键）
        Map<String, TreeNode> nodeMap = new HashMap<>();
        // 存储最终返回的根节点列表
        List<TreeNode> roots = new ArrayList<>();
        // 遍历原始数据
        for (Map<String, Object> data : dataList) {
            // 1. 解析各层级信息（根据实际字段名称调整）
            String stationCode = (String) data.get("stationCode");
            String stationName = (String) data.get("stationName");
            String areaId = (String) data.get("areaId");
            String areaName = (String) data.get("areaName");
            String bayId = (String) data.get("bayId");
            String bayName = (String) data.get("bayName");
            String mainDeviceId = (String) data.get("mainDeviceId");
            String mainDeviceName = (String) data.get("mainDeviceName");
            String componentId = (String) data.get("componentId");
            String componentName = (String) data.get("componentName");

            TreeNode stationNode = nodeMap.computeIfAbsent(stationCode,
                    k -> {
                        TreeNode node = new TreeNode(stationCode, stationName);
                        roots.add(node); // 将变电站作为根节点
                        return node;
                    });
            if (StrUtil.isNotBlank(areaId)) {
                // 处理变电站层级
                TreeNode areaNode = nodeMap.computeIfAbsent(areaId,
                        k -> {
                            TreeNode node = new TreeNode(areaId, areaName);
                            stationNode.getChildren().add(node); // 将变电站作为根节点
                            return node;
                        });

                // 处理区域层级
                if (StrUtil.isNotBlank(bayId)) {
                    TreeNode bayNode = nodeMap.computeIfAbsent(bayId,
                            k -> {
                                TreeNode node = new TreeNode(bayId, bayName);
                                areaNode.getChildren().add(node);
                                return node;
                            });

                    // 处理间隔层级
                    if (StrUtil.isNotBlank(mainDeviceId)) {
                        TreeNode mainDeviceNode = nodeMap.computeIfAbsent(mainDeviceId,
                                k -> {
                                    TreeNode node = new TreeNode(mainDeviceId, mainDeviceName);
                                    bayNode.getChildren().add(node);
                                    return node;
                                });

                        // 处理主设备层级
                        if (StrUtil.isNotBlank(componentId)) {
                            TreeNode componentNode = nodeMap.computeIfAbsent(componentId,
                                    k -> {
                                        TreeNode node = new TreeNode(componentId, componentName);
                                        mainDeviceNode.getChildren().add(node);
                                        return node;
                                    });
                        }

                    }
                }
            }

        }
        return roots;
    }

    /**********************************
     * 用途说明: 构造树
     * 参数说明 dataList 数据
     * 返回值说明: java.util.List<com.yfd.platform.modules.basedata.domain.TreeNode>
     ***********************************/
    public List<TreeNode> buildSignalTree(List<Map<String, Object>> dataList) {
        // 存储所有节点（使用ID作为键）
        Map<String, TreeNode> nodeMap = new HashMap<>();
        // 存储最终返回的根节点列表
        List<TreeNode> roots = new ArrayList<>();
        // 遍历原始数据
        for (Map<String, Object> data : dataList) {
            // 1. 解析各层级信息（根据实际字段名称调整）
            String stationCode = (String) data.get("stationCode");
            String stationName = (String) data.get("stationName");
            String areaId = (String) data.get("areaId");
            String areaName = (String) data.get("areaName");
            String bayId = (String) data.get("bayId");
            String bayName = (String) data.get("bayName");
            String mainDeviceId = (String) data.get("mainDeviceId");
            String mainDeviceName = (String) data.get("mainDeviceName");
            String componentId = (String) data.get("componentId");
            String componentName = (String) data.get("componentName");
            String signalId = (String) data.get("signalId");
            String signalName = (String) data.get("signalName");

            TreeNode stationNode = nodeMap.computeIfAbsent(stationCode,
                    k -> {
                        TreeNode node = new TreeNode(stationCode, stationName);
                        roots.add(node); // 将变电站作为根节点
                        return node;
                    });
            if (StrUtil.isNotBlank(areaId)) {
                // 处理变电站层级
                TreeNode areaNode = nodeMap.computeIfAbsent(areaId,
                        k -> {
                            TreeNode node = new TreeNode(areaId, areaName);
                            stationNode.getChildren().add(node); // 将变电站作为根节点
                            return node;
                        });

                // 处理区域层级
                if (StrUtil.isNotBlank(bayId)) {
                    TreeNode bayNode = nodeMap.computeIfAbsent(bayId,
                            k -> {
                                TreeNode node = new TreeNode(bayId, bayName);
                                areaNode.getChildren().add(node);
                                return node;
                            });

                    // 处理间隔层级
                    if (StrUtil.isNotBlank(mainDeviceId)) {
                        TreeNode mainDeviceNode = nodeMap.computeIfAbsent(mainDeviceId,
                                k -> {
                                    TreeNode node = new TreeNode(mainDeviceId, mainDeviceName);
                                    bayNode.getChildren().add(node);
                                    return node;
                                });

                        // 处理主设备层级
                        if (StrUtil.isNotBlank(componentId)) {
                            TreeNode componentNode = nodeMap.computeIfAbsent(componentId,
                                    k -> {
                                        TreeNode node = new TreeNode(componentId, componentName);
                                        mainDeviceNode.getChildren().add(node);
                                        return node;
                                    });
                            if (StrUtil.isNotBlank(signalId)) {
                                nodeMap.computeIfAbsent(signalId,
                                        k -> {
                                            TreeNode node = new TreeNode(signalId, signalName);
                                            componentNode.getChildren().add(node);
                                            return node;
                                        });
                            }
                        }

                    }
                }
            }

        }
        return roots;
    }

    /**********************************
     * 用途说明: 构建主设备树
     * 参数说明 dataList 数据
     * 返回值说明: java.util.List<com.yfd.platform.modules.basedata.domain.TreeNode>
     ***********************************/
    public List<TreeNode> buildTree(List<Map<String, Object>> dataList) {
        // 存储所有节点（使用ID作为键）
        Map<String, TreeNode> nodeMap = new HashMap<>();
        // 存储最终返回的根节点列表
        List<TreeNode> roots = new ArrayList<>();

        // 遍历原始数据
        for (Map<String, Object> data : dataList) {
            // 1. 解析各层级信息（根据实际字段名称调整）
            String stationCode = (String) data.get("stationCode");
            String stationName = (String) data.get("stationName");
            String areaId = (String) data.get("areaId");
            String areaName = (String) data.get("areaName");
            String bayId = (String) data.get("bayId");
            String bayName = (String) data.get("bayName");
            String mainDeviceId = (String) data.get("mainDeviceId");
            String mainDeviceName = (String) data.get("mainDeviceName");

            // 2. 逐级创建/获取节点（假设层级关系：station -> area -> bay -> device）

            // 处理变电站层级
            TreeNode stationNode = nodeMap.computeIfAbsent(stationCode,
                    k -> {
                        TreeNode node = new TreeNode(stationCode, stationName);
                        roots.add(node); // 将变电站作为根节点
                        return node;
                    });

            // 处理区域层级
            if (StrUtil.isNotBlank(areaId)) {
                TreeNode areaNode = nodeMap.computeIfAbsent(areaId,
                        k -> {
                            TreeNode node = new TreeNode(areaId, areaName);
                            stationNode.getChildren().add(node);
                            return node;
                        });

                // 处理间隔层级
                if (StrUtil.isNotBlank(bayId)) {
                    TreeNode bayNode = nodeMap.computeIfAbsent(bayId,
                            k -> {
                                TreeNode node = new TreeNode(bayId, bayName);
                                areaNode.getChildren().add(node);
                                return node;
                            });

                    // 处理主设备层级
                    if (StrUtil.isNotBlank(mainDeviceId)) {
                        nodeMap.computeIfAbsent(mainDeviceId,
                                k -> {
                                    TreeNode node = new TreeNode(mainDeviceId, mainDeviceName);
                                    bayNode.getChildren().add(node);
                                    return node;
                                });
                    }
                }
            }
        }
        return roots;
    }
}
