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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfd.platform.config.HttpServerConfig;
import com.yfd.platform.modules.basedata.domain.*;
import com.yfd.platform.modules.basedata.mapper.*;
import com.yfd.platform.modules.basedata.service.ISubstationDeviceService;
import com.yfd.platform.modules.patroltask.domain.TaskResult;
import com.yfd.platform.modules.patroltask.mapper.TaskResultMapper;
import com.yfd.platform.system.domain.SysDictionary;
import com.yfd.platform.system.domain.SysDictionaryItems;
import com.yfd.platform.system.mapper.SysDictionaryMapper;
import com.yfd.platform.system.service.ISysDictionaryItemsService;
import com.yfd.platform.utils.FileUtil;
import com.yfd.platform.utils.SecurityUtils;
import com.yfd.platform.utils.VideoToImageUtil;
import freemarker.template.utility.NullArgumentException;
import lombok.extern.slf4j.Slf4j;
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 javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
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
 */
@Service
@Transactional
@Slf4j
public class SubstationDeviceServiceImpl extends ServiceImpl<SubstationDeviceMapper, SubstationDevice> implements ISubstationDeviceService {

    @Resource
    private SysDictionaryMapper sysDictionaryMapper;

    @Resource
    private ISysDictionaryItemsService sysDictionaryItemsService;
    @Resource
    private SubstationDeviceMapper substationDeviceMapper;
    @Resource
    private SubstationAreaMapper substationAreaMapper;
    @Resource
    private SubstationBayMapper substationBayMapper;
    @Resource
    private SubstationMapper substationMapper;

    @Resource
    private TaskResultMapper taskResultMapper;
    @Resource
    private SubstationMaindeviceMapper substationMaindeviceMapper;

    @Resource
    private SubstationComponentMapper substationComponentMapper;
    @Resource
    private HttpServerConfig Config;

    /**********************************
     * 用途说明: 删除巡视点位
     * 参数说明 deviceId 巡视点位id
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean deleteSubstationDeviceById(String deviceId) {
        String[] split = deviceId.split(",");
        for (String s : split) {
            SubstationDevice substationDevice = this.getById(s);
            if ("1".equals(substationDevice.getDatastatus())) {
                continue;
            }
            LambdaUpdateWrapper<TaskResult> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TaskResult::getDeviceId, s).eq(TaskResult::getFlag, "0").set(TaskResult::getFlag, "6");
            taskResultMapper.update(null, updateWrapper);
            this.removeById(s);
        }
        return true;
    }

    /**********************************
     * 用途说明: 设置巡视点位状态是否启用
     * 参数说明 deviceId 巡视点位id
     * 参数说明 dataStatus 巡视点位状态
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean setSubstationDeviceStatus(String deviceId, String dataStatus) {
        SubstationDevice substationDevice = this.getById(deviceId);
        substationDevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationDevice.setLastmodifydate(LocalDateTime.now());
        substationDevice.setDatastatus(dataStatus);
        return this.updateById(substationDevice);
    }

    /**********************************
     * 用途说明: 获取类型
     * 参数说明
     * 返回值说明: java.util.List<java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Object>>>
     ***********************************/
    @Override
    public Map<String, List<Map<String, Object>>> getDeviceType() {
        List<SysDictionary> sysDictionaries = sysDictionaryMapper.selectList(null);
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        for (SysDictionary sysDictionary : sysDictionaries) {
            String dictCode = sysDictionary.getDictCode();
            String id = sysDictionary.getId();
            List<Map<String, Object>> list =
                    sysDictionaryItemsService.listMaps(new LambdaQueryWrapper<SysDictionaryItems>().eq(SysDictionaryItems::getDictId, id).select(SysDictionaryItems::getId, SysDictionaryItems::getItemCode, SysDictionaryItems::getDictName, SysDictionaryItems::getCustom2));
            if ("SilentMonitoringType".equals(dictCode)) {
                List<Map<String, Object>> listMaps = new ArrayList<>();
                for (Map<String, Object> stringObjectMap : list) {
                    stringObjectMap.put("checkInfo", false);
                    listMaps.add(stringObjectMap);
                }
                map.put(dictCode, listMaps);
            } else {
                map.put(dictCode, list);
            }

        }
        return map;
    }

    /***********************************
     * 用途说明：保存图片模板
     * 参数说明
     * deviceId  点位ID
     * multipartFile   文件对象
     * 返回值说明: 文件名
     ************************************/
    @Override
    public String saveImgTemplate(HttpServletResponse response, String deviceId, String devicecode,
                                  String channelcode) throws Exception {
        //根据id查询
        SubstationDevice substationDevice = this.getById(deviceId);
        // 模板图片地址
        String tempPath = Config.getTempFilePath();
        String imageNormalUrlPath = substationDevice.getImageNormalUrlpath();
        if (StrUtil.isNotBlank(imageNormalUrlPath)) {
            String imgDecode = URLDecoder.decode(imageNormalUrlPath, "utf-8");
            String imgName = tempPath + imgDecode;
            FileUtil.del(imgName);
        }
        String tempfilepath = String.format("%s/%s/",
                substationDevice.getStationCode(),
                DateUtil.format(DateUtil.date(), "yyyyMMdd")
        );
        //文件命名格式为：变电站_点位.jpg
        String filename = String.format("%s_%s.jpg",
                substationDevice.getStationName(),
                substationDevice.getDeviceName()
        );
        String filePathName = tempfilepath + filename;
        String imgPath = tempPath + filePathName;
        String url = String.format("rtsp://%s:%s/rtp/%s_%s", Config.getMediaIp(), Config.getMonitorRtspPort(),
                devicecode, channelcode);

        VideoToImageUtil.getVideoPicture(Config.getffmpegPath(), url, imgPath);
        //修改 模板图片
        substationDevice.setImageNormalUrlpath(URLEncoder.encode(filePathName, "utf-8"));
        //修改 最近修改者
        substationDevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        //修改 最近修改日期
        substationDevice.setLastmodifydate(LocalDateTime.now());
        //更新点位表
        this.updateById(substationDevice);
        return filePathName;
    }

    @Override
    public List<String> getDeviceByCode(String patrolDeviceCode) {

        return substationDeviceMapper.getDeviceByCode(patrolDeviceCode);
    }

    @Override
    public String uploadExcel(MultipartFile file) 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());
            return a;
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }

    }

    /**********************************
     * 用途说明: 导出点位
     * 参数说明 ids 点位id
     * 返回值说明: void
     ***********************************/
    @Override
    public void deviceDownloadFile(Page<Map<String, Object>> page, String bayId,
                                   String componentId, String mainDeviceId, String deviceName,
                                   HttpServletResponse response) throws IOException {

        LambdaQueryWrapper<SubstationDevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(bayId)) {
            queryWrapper.eq(SubstationDevice::getBayId, bayId);
        }
        if (StrUtil.isNotBlank(componentId)) {
            queryWrapper.eq(SubstationDevice::getComponentId, componentId);
        }
        if (StrUtil.isNotBlank(mainDeviceId)) {
            queryWrapper.eq(SubstationDevice::getMainDeviceId, mainDeviceId);
        }
        if (StrUtil.isNotBlank(deviceName)) {
            queryWrapper.like(SubstationDevice::getDeviceName, deviceName);
        }
        queryWrapper.orderByAsc(SubstationDevice::getDeviceId);
        Page<Map<String, Object>> mapPage = this.pageMaps(page, queryWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        List<Map<String, Object>> mapList = new ArrayList<>();
        // 点位分类
        List<Map<String, Object>> deviceClassList = sysDictionaryItemsService.getDeviceByType("DeviceClass");
        // 主设备类型
        List<Map<String, Object>> equipmentType = sysDictionaryItemsService.getDeviceByType(
                "EquipmentType");
        // 标记类型
        List<Map<String, Object>> meterTypeList = sysDictionaryItemsService.getDeviceByType(
                "MeterType");
        records.forEach(r -> {
            String deviceTypeName = "";
            if (ObjectUtil.isNotEmpty(r.get("deviceType"))) {
                for (Map<String, Object> device : equipmentType) {
                    String deviceType = r.get("deviceType").toString();
                    String itemcode = device.get("itemcode").toString();
                    if (deviceType.equals(itemcode)) {
                        deviceTypeName = device.get("dictname").toString();
                        break;
                    }

                }
            }
            r.put("deviceTypeName", deviceTypeName);
            String meterTypeName = "";
            if (ObjectUtil.isNotEmpty(r.get("meterType"))) {
                for (Map<String, Object> device : meterTypeList) {
                    String meterType = r.get("meterType").toString();
                    String itemcode = device.get("itemcode").toString();
                    if (meterType.equals(itemcode)) {
                        meterTypeName = device.get("dictname").toString();
                        break;
                    }

                }
            }
            r.put("meterTypeName", meterTypeName);
            String deviceClassName = "";
            if (ObjectUtil.isNotEmpty(r.get("deviceClass"))) {
                for (Map<String, Object> device : deviceClassList) {
                    String deviceClass = r.get("deviceClass").toString();
                    String itemcode = device.get("itemcode").toString();
                    if (deviceClass.equals(itemcode)) {
                        deviceClassName = device.get("dictname").toString();
                        break;
                    }

                }
            }
            r.put("deviceClassName", deviceClassName);
        });
        String[] headers = {"巡视点位编号", "巡视点位名称", "所属主设备", "主设备类型", "所属部件", "表记类型", "点位分类"};
        String[] keys = {"deviceCode", "deviceName", "mainDeviceName", "deviceTypeName", "componentName", "meterTypeName", "deviceClassName"};
        FileUtil.excelImg(records, headers, keys, "", "", response);
        FileUtil.downloadExcel(mapList, response);

    }

    @Transactional(rollbackFor = Exception.class)
    public String parseRowCell(String filename, InputStream inputStream) {
        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>> deviceClassList = sysDictionaryItemsService.getDeviceByType(
                    "DeviceClass");
            // 主设备类型
            List<Map<String, Object>> equipmentType = sysDictionaryItemsService.getDeviceByType(
                    "EquipmentType");
            // 数据来源
            List<Map<String, Object>> dataTypeList = sysDictionaryItemsService.getDeviceByType(
                    "dataType");
            // 识别类型
            List<Map<String, Object>> recognitionType = sysDictionaryItemsService.getDeviceByType(
                    "recognition_type");
            // 表计类型
            List<Map<String, Object>> meterTypeList = sysDictionaryItemsService.getDeviceByType(
                    "MeterType");
            // 图像状态分析类型
            List<Map<String, Object>> pictureAnalysisTypeList = sysDictionaryItemsService.getDeviceByType(
                    "PictureAnalysisType");
            // 表计特征
            List<Map<String, Object>> outsideFeatureList = sysDictionaryItemsService.getDeviceByType(
                    "OutsideFeature");
            // 图像缺陷分析类型
            List<Map<String, Object>> pictureDefectAnalysisTypeList = sysDictionaryItemsService.getDeviceByType(
                    "PictureDefectAnalysisType");
            // 相位类型
            List<Map<String, Object>> devicePhaseList = sysDictionaryItemsService.getDeviceByType(
                    "DevicePhase");
            // 图像判别分析类型
            List<Map<String, Object>> pictureDiscriminateAnalysisTypeList =
                    sysDictionaryItemsService.getDeviceByType("PictureDiscriminateAnalysisType");
            // 工作表中第一行是表头，不获取，从第二行开始获取
            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;
                }

                SubstationDevice substationDevice = new SubstationDevice();
                // 主设备状态
                substationDevice.setDatastatus("1");

                // 变电站编号
                String stationCode = "";
                if (row.getCell(1) != null) {
                    row.getCell(1).setCellType(CellType.STRING);
                    stationCode = row.getCell(1).getStringCellValue().trim();
                    substationDevice.setStationCode(stationCode);
                }
                Substation substation =
                        substationMapper.selectOne(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode
                                , stationCode));
                if (substation != null) {
                    substationDevice.setStationId(substation.getStationId());
                }
                // 变电站名称
                String stationName = "";
                if (row.getCell(2) != null) {
                    row.getCell(2).setCellType(CellType.STRING);
                    stationName = row.getCell(2).getStringCellValue().trim();
                    substationDevice.setStationName(stationName);
                }
                // 区域名称
                String areaName = "";
                if (row.getCell(3) != null) {
                    row.getCell(3).setCellType(CellType.STRING);
                    areaName = row.getCell(3).getStringCellValue().trim();
                    substationDevice.setAreaName(areaName);
                }
                // 间隔名称
                String bayName = "";
                if (row.getCell(4) != null) {
                    row.getCell(4).setCellType(CellType.STRING);
                    bayName = row.getCell(4).getStringCellValue().trim();
                    substationDevice.setBayName(bayName);
                }
                // 巡视点位编号
                String deviceCode = "";
                if (row.getCell(5) != null) {
                    row.getCell(5).setCellType(CellType.STRING);
                    deviceCode = row.getCell(5).getStringCellValue().trim();
                    substationDevice.setDeviceCode(deviceCode);
                }

                // 巡视点位名称
                String deviceName = "";
                if (row.getCell(6) != null) {
                    row.getCell(6).setCellType(CellType.STRING);
                    deviceName = row.getCell(6).getStringCellValue().trim();
                    substationDevice.setDeviceName(deviceName);
                }

                // 点位分类
                String deviceClass = "";
                if (row.getCell(7) != null) {
                    row.getCell(7).setCellType(CellType.STRING);
                    deviceClass = row.getCell(7).getStringCellValue().trim();
                }
                deviceClass = deviceClass.trim();
                boolean isBool1 = false;
                if (StrUtil.isNotBlank(deviceClass)) {
                    for (Map<String, Object> map : deviceClassList) {
                        String dictname = map.get("dictname").toString();
                        if (deviceClass.equals(dictname)) {
                            String itemcode = map.get("itemcode").toString();
                            substationDevice.setDeviceClass(itemcode);
                            isBool1 = true;
                            break;
                        }
                    }
                }
                if (!isBool1) {
                    if (row.getCell(0) != null) {
                        row.getCell(0).setCellType(CellType.STRING);
                        throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() +
                                "：不存在该点位分类,请检查");
                    }
                }

                // 主设备名称
                String mainDeviceName = "";
                if (row.getCell(8) != null) {
                    row.getCell(8).setCellType(CellType.STRING);
                    mainDeviceName = row.getCell(8).getStringCellValue().trim();
                    substationDevice.setMainDeviceName(mainDeviceName);
                }
                // (主设备类型)，赋值给deviceType
                String dictType = "";
                if (row.getCell(9) != null) {
                    row.getCell(9).setCellType(CellType.STRING);
                    dictType = row.getCell(9).getStringCellValue().trim();
                }
                dictType = dictType.trim();
                boolean isBool = false;
                log.info("主设备类型");
                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();
                            substationDevice.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() +
                                "：不存在该主设备类型,请检查");
                    }
                }

                // (部件名称)，赋值给componentName
                String componentName = "";
                if (row.getCell(10) != null) {
                    row.getCell(10).setCellType(CellType.STRING);
                    componentName = row.getCell(10).getStringCellValue().trim();
                    substationDevice.setComponentName(componentName);
                }

                SubstationComponent substationComponent =
                        substationComponentMapper.selectOne(new LambdaQueryWrapper<SubstationComponent>().eq(SubstationComponent::getStationCode, stationCode).eq(SubstationComponent::getStationName, stationName).eq(SubstationComponent::getAreaName, areaName).eq(SubstationComponent::getBayName, bayName).eq(SubstationComponent::getComponentName, componentName).eq(SubstationComponent::getMainDeviceName, mainDeviceName));
                if (substationComponent == null) {
                    if (row.getCell(0) != null) {
                        row.getCell(0).setCellType(CellType.STRING);
                        throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() +
                                "：数据不正确,请检查");
                    }
                }
                substationDevice.setComponentId(substationComponent.getComponentId());
                // 区域
                substationDevice.setAreaId(substationComponent.getAreaId());
                // 间隔
                substationDevice.setBayId(substationComponent.getBayId());
                // 主设备
                substationDevice.setMainDeviceId(substationComponent.getMainDeviceId());

                // 数据来源
                String dataType = "";
                if (row.getCell(12) != null) {
                    row.getCell(12).setCellType(CellType.STRING);
                    dataType = row.getCell(12).getStringCellValue().trim();
                }
                dataType = dataType.trim();
                for (Map<String, Object> map : dataTypeList) {
                    String dictname = map.get("dictname").toString();
                    if (dataType.equals(dictname)) {
                        String itemcode = map.get("itemcode").toString();
                        substationDevice.setDataType(itemcode);
                        break;
                    }
                }

                // 识别类型
                String recognitionTypeList = "";
                if (row.getCell(13) != null) {
                    row.getCell(13).setCellType(CellType.STRING);
                    recognitionTypeList = row.getCell(13).getStringCellValue().trim();
                }

                recognitionTypeList = recognitionTypeList.trim();
                if (StrUtil.isNotBlank(recognitionTypeList)) {
                    for (Map<String, Object> map : recognitionType) {
                        String dictname = map.get("dictname").toString();
                        if (recognitionTypeList.equals(dictname)) {
                            String itemcode = map.get("itemcode").toString();
                            substationDevice.setRecognitionTypeList(itemcode);
                            if ("4".equals(itemcode)) {
                                substationDevice.setSaveTypeList("1");
                            } else if ("5".equals(itemcode)) {
                                substationDevice.setSaveTypeList("3");
                            } else if ("6".equals(itemcode)) {
                                substationDevice.setSaveTypeList("4");
                            } else {
                                substationDevice.setSaveTypeList("2");
                            }
                            break;
                        }
                    }
                }
                // 表计类型
                String meterType = "";
                if (row.getCell(14) != null) {
                    row.getCell(14).setCellType(CellType.STRING);
                    meterType = row.getCell(14).getStringCellValue().trim();

                }
                meterType = meterType.trim();
                if (StrUtil.isNotBlank(meterType)) {
                    for (Map<String, Object> map : meterTypeList) {
                        String dictname = map.get("dictname").toString();
                        if (meterType.equals(dictname)) {
                            String itemcode = map.get("itemcode").toString();
                            substationDevice.setMeterType(itemcode);
                            break;
                        }
                    }
                }
                JSONObject jsonObject = new JSONObject();
                // 状态分析类型
                String pictureAnalysisType = "";
                if (row.getCell(15) != null) {
                    row.getCell(15).setCellType(CellType.STRING);
                    pictureAnalysisType = row.getCell(15).getStringCellValue().trim();
                }

                pictureAnalysisType = pictureAnalysisType.trim();
                if (StrUtil.isNotBlank(pictureAnalysisType)) {
                    for (Map<String, Object> map : pictureAnalysisTypeList) {
                        String dictname = map.get("dictname").toString();
                        if (pictureAnalysisType.equals(dictname)) {
                            String itemcode = map.get("itemcode").toString();
                            jsonObject.putOnce("PictureAnalysisType", itemcode);
                            break;
                        }
                    }
                }
                // 分析仪表特征
                String outsideFeature = "";
                if (row.getCell(16) != null) {
                    row.getCell(16).setCellType(CellType.STRING);
                    outsideFeature = row.getCell(16).getStringCellValue().trim();
                }

                outsideFeature = outsideFeature.trim();
                if (StrUtil.isNotBlank(outsideFeature)) {
                    for (Map<String, Object> map : outsideFeatureList) {
                        String dictname = map.get("dictname").toString();
                        if (outsideFeature.equals(dictname)) {
                            String itemcode = map.get("itemcode").toString();
                            substationDevice.setOutsideFeature(itemcode);
                            break;
                        }
                    }
                }

                // 缺陷分析类型
                String pictureDefectAnalysisType = "";
                if (row.getCell(17) != null) {
                    row.getCell(17).setCellType(CellType.STRING);
                    pictureDefectAnalysisType = row.getCell(17).getStringCellValue().trim();
                }
                pictureDefectAnalysisType = pictureDefectAnalysisType.trim();
                if (StrUtil.isNotBlank(pictureDefectAnalysisType)) {
                    for (Map<String, Object> map : pictureDefectAnalysisTypeList) {
                        String dictname = map.get("dictname").toString();
                        if (pictureDefectAnalysisType.equals(dictname)) {
                            String itemcode = map.get("itemcode").toString();
                            jsonObject.putOnce("PictureDefectAnalysisType", itemcode);
                            break;
                        }
                    }
                }
                // 判别分析类型
                String pictureDiscriminateAnalysisType = "";
                if (row.getCell(18) != null) {
                    row.getCell(18).setCellType(CellType.STRING);
                    pictureDiscriminateAnalysisType = row.getCell(18).getStringCellValue().trim();
                }

                pictureDiscriminateAnalysisType = pictureDiscriminateAnalysisType.trim();
                if (StrUtil.isNotBlank(pictureDiscriminateAnalysisType)) {
                    for (Map<String, Object> map : pictureDiscriminateAnalysisTypeList) {
                        String dictname = map.get("dictname").toString();
                        if (pictureDiscriminateAnalysisType.equals(dictname)) {
                            String itemcode = map.get("itemcode").toString();
                            jsonObject.putOnce("PictureDiscriminateAnalysisType", itemcode);
                            break;
                        }
                    }
                }
                // 三种缺陷类型
                substationDevice.setPictureAnalysisTypeList(jsonObject.toString());
                // 正常范围上限
                String upperValue = "";
                if (row.getCell(19) != null) {
                    row.getCell(19).setCellType(CellType.STRING);
                    upperValue = row.getCell(19).getStringCellValue().trim();
                    substationDevice.setUpperValue(upperValue);
                }

                // 正常范围下限
                String lowerValue = "";
                if (row.getCell(20) != null) {
                    row.getCell(20).setCellType(CellType.STRING);
                    lowerValue = row.getCell(20).getStringCellValue().trim();
                    substationDevice.setLowerValue(lowerValue);
                }
                // 计量单位
                String unit = "";
                if (row.getCell(21) != null) {
                    row.getCell(21).setCellType(CellType.STRING);
                    unit = row.getCell(21).getStringCellValue().trim();
                    substationDevice.setUnit(unit);
                }

                // 是否告警
                String isAlarm = "";
                if (row.getCell(22) != null) {
                    row.getCell(22).setCellType(CellType.STRING);
                    isAlarm = row.getCell(22).getStringCellValue().trim();
                }
                if ("是".equals(isAlarm)) {
                    substationDevice.setIsAlarm("1");
                } else {
                    substationDevice.setIsAlarm("0");
                }

                // 是否识别实物ID
                String identifyMaterialId = "";
                if (row.getCell(23) != null) {
                    row.getCell(23).setCellType(CellType.STRING);
                    identifyMaterialId = row.getCell(23).getStringCellValue().trim();
                }

                if ("是".equals(identifyMaterialId)) {
                    substationDevice.setIdentifyMaterialId("1");
                } else {
                    substationDevice.setIdentifyMaterialId("0");
                }

                // 备注
                String deviceInfo = "";
                if (row.getCell(24) != null) {
                    row.getCell(24).setCellType(CellType.STRING);
                    deviceInfo = row.getCell(24).getStringCellValue().trim();
                    substationDevice.setPatroldeviceJson(deviceInfo);

                }
                // 备注
                String phase = "";
                if (row.getCell(25) != null) {
                    row.getCell(25).setCellType(CellType.STRING);
                    phase = row.getCell(25).getStringCellValue().trim();
                }
                phase = phase.trim();
                if (StrUtil.isNotBlank(phase)) {
                    for (Map<String, Object> map : devicePhaseList) {
                        String dictname = map.get("dictname").toString();
                        if (phase.equals(dictname)) {
                            String itemcode = map.get("itemcode").toString();
                            substationDevice.setPhase(itemcode);
                            break;
                        }
                    }
                }
                String dataType1 = substationDevice.getDataType();

                if ("0x01".equals(dataType1) && JSONUtil.isTypeJSONArray(deviceInfo)) {
                    JSONArray jsonArray = JSONUtil.parseArray(deviceInfo);
                    JSONArray videoPosArray = new JSONArray();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject deviceJSON = jsonArray.getJSONObject(i);
                        JSONObject videoPos = new JSONObject();
                        videoPos.putOnce("device_code", deviceJSON.getStr("patroldevice_code"));
                        videoPos.putOnce("device_pos", deviceJSON.getStr("patroldevice_pos"));
                        videoPos.putOnce("device_xyzf", "");
                        videoPos.putOnce("robot_code", "");
                        videoPos.putOnce("robot_pos", "");
                        videoPos.putOnce("uav_code", "");
                        videoPos.putOnce("uav_pos", "");
                        videoPosArray.add(videoPos);
                    }
                    substationDevice.setVideoPos(videoPosArray.toString());
                }
                int count =
                        this.count(new LambdaQueryWrapper<SubstationDevice>().eq(SubstationDevice::getDeviceCode,
                                deviceCode).eq(SubstationDevice::getBayId, substationComponent.getBayId()));
                if (count > 0) {
                    if (row.getCell(0) != null) {
                        row.getCell(0).setCellType(CellType.STRING);
                        throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() +
                                "：当前点位已经存在,请检查");
                    }
                }
                substationDevice.setLastmodifier(SecurityUtils.getCurrentUsername());
                substationDevice.setLastmodifydate(LocalDateTime.now());
                boolean ok = this.save(substationDevice);
                if (!ok) {
                    if (row.getCell(0) != null) {
                        row.getCell(0).setCellType(CellType.STRING);
                        throw new RuntimeException("序号" + row.getCell(0).getStringCellValue().trim() + "：导入失败,请检查");
                    }
                }
                log.info("导入行数:" + rowNum);

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

    @Override
    public List<TreeNode> getComponentTree(String bayId, String deviceName) {
        LambdaQueryWrapper<SubstationDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationDevice::getBayId, bayId);
        if (StrUtil.isNotBlank(deviceName)) {
            queryWrapper.like(SubstationDevice::getDeviceName, deviceName);
        }
        queryWrapper.select(SubstationDevice::getBayId,
                SubstationDevice::getBayName, SubstationDevice::getMainDeviceId,
                SubstationDevice::getMainDeviceName, SubstationDevice::getComponentId,
                SubstationDevice::getComponentName);
        List<Map<String, Object>> list = this.listMaps(queryWrapper);
        Map<String, TreeNode> bayNodeMap = new HashMap<>();
        Map<String, TreeNode> mainDeviceMap = new HashMap<>();
        Map<String, TreeNode> componentMap = new HashMap<>();
        List<Map<String, Object>> mapList = list.stream().distinct().collect(Collectors.toList());
        for (Map<String, Object> map : mapList) {
            String bayid = (String) map.get("bayId");
            String mainDeviceId = (String) map.get("mainDeviceId");
            String componentId = (String) map.get("componentId");
            TreeNode bayNode = bayNodeMap.computeIfAbsent(bayid, k -> new TreeNode(bayid, (String) map.get("bayName")));
            TreeNode mainDeviceNode = mainDeviceMap.computeIfAbsent(mainDeviceId, k -> new TreeNode(mainDeviceId,
                    (String) map.get("mainDeviceName")));
            long count =
                    bayNode.getChildren().stream().filter(b -> b.getName().equals(mainDeviceNode.getName())).count();
            if (count <= 0) {
                bayNode.getChildren().add(mainDeviceNode);
            }
            TreeNode componentNode = componentMap.computeIfAbsent(componentId, k -> new TreeNode(componentId,
                    (String) map.get("componentName")));
            mainDeviceNode.getChildren().add(componentNode);
        }
        TreeNode treeNode = bayNodeMap.get(bayId);
        if (treeNode == null) {
            return new ArrayList<>();
        }
        return treeNode.getChildren();
    }

    @Override
    public TreeNode getBayTree(String stationCode, String deviceName) {
        LambdaQueryWrapper<SubstationDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationDevice::getStationCode, stationCode);
        if (StrUtil.isNotBlank(deviceName)) {
            queryWrapper.like(SubstationDevice::getDeviceName, deviceName);
        }
        queryWrapper.select(SubstationDevice::getStationCode,
                SubstationDevice::getStationName, SubstationDevice::getStationName, SubstationDevice::getAreaId,
                SubstationDevice::getAreaName, SubstationDevice::getBayId, SubstationDevice::getBayName);
        List<Map<String, Object>> list = this.listMaps(queryWrapper);
        List<Map<String, Object>> mapList = list.stream().distinct().collect(Collectors.toList());
        // 分组并构建树形结构
        Map<String, TreeNode> stationMap = new HashMap<>();
        Map<String, TreeNode> areaNodeMap = new HashMap<>();
        Map<String, TreeNode> bayNodeMap = new HashMap<>();
        //        Map<String, TreeNode> mainDeviceMap = new HashMap<>();
        for (Map<String, Object> map : mapList) {
            //            String code = (String) map.get("stationCode");
            String areaId = (String) map.get("areaId");
            String bayId = (String) map.get("bayId");
            //            String mainDeviceid = (String) map.get("mainDeviceId");
            //            TreeNode stationNode = stationMap.computeIfAbsent(code, k -> new TreeNode(code, (String)
            //                    map.get("stationName")));
            // 创建或获取Area节点
            TreeNode areaNode = areaNodeMap.computeIfAbsent(areaId, k -> new TreeNode(areaId, (String)
                    map.get("areaName")));
            //            stationNode.getChildren().add(areaNode);
            // 创建或获取Bay节点，并将其添加到Area节点的children中
            TreeNode bayNode = bayNodeMap.computeIfAbsent(bayId, k -> new TreeNode(bayId, (String) map
                    .get("bayName")));
            areaNode.getChildren().add(bayNode);

            //            TreeNode mainDeviceNode = mainDeviceMap.computeIfAbsent(mainDeviceid, k -> new TreeNode
            //            (mainDeviceid,
            //                    (String) map.get("mainDeviceName")));
            //            bayNode.getChildren().add(mainDeviceNode);

        }
        TreeNode stationNode = new TreeNode();
        List<Substation> substations =
                substationMapper.selectList(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode,
                        stationCode));
        if (substations.size() <= 0) {
            return null;
        }
        Substation substation = substations.get(0);
        stationNode.setId(stationCode);
        stationNode.setName(substation.getStationName());
        stationNode.setChildren(new ArrayList<>(areaNodeMap.values()));
        stationMap.put(stationCode, stationNode);
        return stationMap.get(stationCode);
    }

    @Override
    public List<Map<String, Object>> getDeviceByJson(String internationalId) {
        return substationDeviceMapper.getDeviceByJson(internationalId);
    }

    @Override
    public String selectNextUavDeviceCode() {
        return substationDeviceMapper.selectNextUavDeviceCode();
    }


    @Override
    public List<Map<String, Object>> getRobotCodeByDeviceId(List<String> deviceIds) {
        return substationDeviceMapper.getRobotCodeByDeviceId(deviceIds);
    }

}
