package com.yfd.platform.modules.basedata.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.basedata.domain.SubstationComponent;
import com.yfd.platform.modules.basedata.domain.SubstationDevice;
import com.yfd.platform.modules.basedata.domain.SubstationMaindevice;
import com.yfd.platform.modules.basedata.domain.TreeNode;
import com.yfd.platform.modules.basedata.service.IDeviceChannelService;
import com.yfd.platform.modules.basedata.service.ISubstationDeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationMaindeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationPatroldeviceService;
import com.yfd.platform.system.domain.SysDictionaryItems;
import com.yfd.platform.system.domain.SysUser;
import com.yfd.platform.system.service.ISysOrganizationService;
import com.yfd.platform.system.service.IUserService;
import com.yfd.platform.utils.FileUtil;
import com.yfd.platform.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 变电站_巡视点位 前端控制器
 * </p>
 *
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/basedata/substation-device")
@Api(value = "SubstationDeviceController", tags = "变电站_巡视点位")
@Slf4j
public class SubstationDeviceController {

    @Resource
    private ISubstationMaindeviceService substationMaindeviceService;

    @Resource
    private ISubstationDeviceService substationDeviceService;

    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;

    @Resource
    private IDeviceChannelService deviceChannelService;

    @Resource
    private Map<String, List<Map<String, Object>>> typeList;

    @Resource
    private IUserService userService;

    @Resource
    private ISysOrganizationService sysOrganizationService;

    @PostMapping("/getSubstationDeviceList")
    @ApiOperation("分页查询巡视点位")
    @PreAuthorize("@el.check('select:device')")
    public ResponseResult getSubstationDeviceList(@RequestBody String param) {
        JSONObject jsonObject = JSONUtil.parseObj(param);
        Page<Map<String, Object>> page = new Page<>();
        if (jsonObject.containsKey("current")) {
            page.setCurrent(jsonObject.getInt("current"));
        }
        if (jsonObject.containsKey("size")) {
            page.setSize(jsonObject.getInt("size"));
        }
        String stationId = jsonObject.getStr("stationId");
        String bayId = jsonObject.getStr("bayId");
        String areaId = jsonObject.getStr("areaId");
        String componentId = jsonObject.getStr("componentId");
        String mainDeviceId = jsonObject.getStr("mainDeviceId");
        String deviceName = jsonObject.getStr("deviceName");
        String ids = jsonObject.getStr("ids");
        String status = jsonObject.getStr("status");
        String dataType = jsonObject.getStr("dataType");
        String patrolDeviceCode = jsonObject.getStr("patrolDeviceCode");
        //        Page<Map<String, Object>> page, String stationId, String bayId,
//                String componentId, String mainDeviceId, String deviceName,
//                String ids, String status, String patrolDeviceCode
        LambdaQueryWrapper<SubstationDevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(stationId)) {
            queryWrapper.eq(SubstationDevice::getStationId, stationId);
        }
        if (StrUtil.isNotBlank(bayId)) {
            queryWrapper.eq(SubstationDevice::getBayId, bayId);
        }
        if (StrUtil.isNotBlank(areaId)) {
            queryWrapper.eq(SubstationDevice::getAreaId, areaId);
        }
        if (StrUtil.isNotBlank(dataType)) {
            queryWrapper.like(SubstationDevice::getDataType, dataType);
        }
        if (StrUtil.isNotBlank(deviceName)) {
            queryWrapper.like(SubstationDevice::getDeviceName, deviceName);
        }
        if (StrUtil.isNotBlank(ids)) {
            String[] split = ids.split(",");
            queryWrapper.notIn(SubstationDevice::getDeviceId, Arrays.asList(split));
        }
        // 根据部件查询
        if (StrUtil.isNotBlank(componentId)) {
            queryWrapper.eq(SubstationDevice::getComponentId, componentId);
        }

        // 根据主设备查询
        if (StrUtil.isNotBlank(mainDeviceId)) {
            queryWrapper.eq(SubstationDevice::getMainDeviceId, mainDeviceId);
        }
        if ("0".equals(status)) {
            int count = substationDeviceService.count(queryWrapper);
            page.setSize(count);
        }
//        if (StrUtil.isNotBlank(patrolDeviceCode)) {
//            List<String> idList = substationDeviceService.getDeviceByCode(patrolDeviceCode);
//            if (idList.size() > 0) {
//                queryWrapper.in(SubstationDevice::getDeviceId, idList);
//            }
//        }
        queryWrapper.orderByAsc(SubstationDevice::getDeviceCode);
        Page<Map<String, Object>> mapPage = substationDeviceService.pageMaps(page, queryWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        List<Map<String, Object>> deviceRecords = new ArrayList<>();
        for (Map<String, Object> record : records) {
            record.remove("lastmodifydate");
            deviceRecords.add(record);
        }
        mapPage.setRecords(deviceRecords);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getAlarmThresholdList")
    @ApiOperation("分页查询巡视点位告警阈值")
    public ResponseResult getAlarmThresholdList(Page<Map<String, Object>> page, String stationId, String areaId,
                                                String bayId, String componentId,
                                                String mainDeviceId, String deviceName, String metertype,
                                                String recognitionType) {
        LambdaQueryWrapper<SubstationDevice> queryWrapper = new LambdaQueryWrapper<>();
        SysUser userInfo = userService.getUserInfo();
        Integer usertype = userInfo.getUsertype();
        if (usertype != 0) {
            Set<String> orgCodeByUser = sysOrganizationService.getOrgCodeByUser(userInfo.getId());
            if (orgCodeByUser != null && orgCodeByUser.size() > 0) {
                queryWrapper.in(SubstationDevice::getStationCode, orgCodeByUser);
            }
        }
        // 根据条件查询
        if (StrUtil.isNotBlank(deviceName)) {
            queryWrapper.like(SubstationDevice::getDeviceName, deviceName);
        }
        if (StrUtil.isNotBlank(stationId)) {
            queryWrapper.eq(SubstationDevice::getStationId, stationId);
        }
        if (StrUtil.isNotBlank(areaId)) {
            queryWrapper.eq(SubstationDevice::getAreaId, areaId);
        }
        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(metertype)) {
            queryWrapper.eq(SubstationDevice::getMeterType, metertype);
        }
        if (StrUtil.isNotBlank(recognitionType)) {
            queryWrapper.like(SubstationDevice::getRecognitionTypeNameList, recognitionType);
        }
        queryWrapper.orderByAsc(SubstationDevice::getDeviceCode);
        Page<Map<String, Object>> mapPage = substationDeviceService.pageMaps(page, queryWrapper);
        return ResponseResult.successData(mapPage);
    }


    @GetMapping("/getDeviceType")
    @ApiOperation("获取类型")
    public ResponseResult getDeviceType() {
        Map<String, List<Map<String, Object>>> types = typeList;
        return ResponseResult.successData(types);
    }

    @Log(module = "巡视点位设置", value = "新增巡视点位", type = "1")
    @PostMapping("/addSubstationDevice")
    @ApiOperation("新增巡视点位")
    @PreAuthorize("@el.check('add:device')")
    public ResponseResult addSubstationDevice(@RequestBody SubstationDevice substationDevice) {
        // 主设备id
        String mainDeviceId = substationDevice.getMainDeviceId();
        // 部件id
        String componentId = substationDevice.getComponentId();
        // 设备点位编号
        String deviceCode = substationDevice.getDeviceCode();
        // 同一个变电站下不可存在相同编号的巡视点位
        LambdaQueryWrapper<SubstationDevice> deviceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        deviceLambdaQueryWrapper.eq(SubstationDevice::getDeviceCode, deviceCode).eq(SubstationDevice::getStationId,
                substationDevice.getStationId());
        int count = substationDeviceService.count(deviceLambdaQueryWrapper);
        if (count > 0) {
            return ResponseResult.error("巡视点位已经存在");
        }
        String recognitionTypeList1 = substationDevice.getRecognitionTypeList();
        // 根据识别类型判断文件类型
        if (!Objects.isNull(recognitionTypeList1)) {
            if ("4".equals(recognitionTypeList1)) {
                substationDevice.setSaveTypeList("1");
            } else if ("5".equals(recognitionTypeList1)) {
                substationDevice.setSaveTypeList("3");
            } else if ("6".equals(recognitionTypeList1)) {
                substationDevice.setSaveTypeList("4");
            } else {
                substationDevice.setSaveTypeList("2");
            }
        }
        String recognitionTypeList = substationDevice.getRecognitionTypeList();
        String[] split = recognitionTypeList.split(",");
        List<String> recognitions = new ArrayList<>(Arrays.asList(split));
        List<Map<String, Object>> maps2 = typeList.get("recognition_type");
        List<String> recognitionNames = new ArrayList<>();
        for (Map<String, Object> map : maps2) {
            String itemcode = map.get("itemcode").toString();
            if (recognitions.contains(itemcode)) {
                String dictname = map.get("dictname").toString();
                recognitionNames.add(dictname);
            }
        }
        String join1 = String.join(",", recognitionNames);
        substationDevice.setRecognitionTypeNameList(join1);
        SubstationMaindevice substationMaindevice = substationMaindeviceService.getById(mainDeviceId);
        if (substationMaindevice != null) {
            substationDevice.setMainDeviceName(substationMaindevice.getMainDeviceName());
        }
        SubstationComponent substationComponent = substationMaindeviceService.getComponentById(componentId);
        if (substationComponent != null) {
            substationDevice.setComponentName(substationComponent.getComponentName());
        }
        substationDevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationDevice.setLastmodifydate(LocalDateTime.now());
        substationDevice.setDatastatus("1");
        boolean ok = substationDeviceService.save(substationDevice);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("新增失败");
        }
    }

    @GetMapping("/getCameraById")
    @ApiOperation("查询关联摄像头")
    public ResponseResult getCameraById(String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("参数为空");
        }
        SubstationDevice substationDevice = substationDeviceService.getById(id);
        String videoPos = substationDevice.getVideoPos();
        //Json转List
        JSONObject objects = JSONUtil.parseObj(videoPos);
        Map maps = JSONUtil.toBean(objects, Map.class);
        return ResponseResult.successData(maps);
    }

    @Log(module = "巡视点位设置", value = "修改巡视点位", type = "1")
    @PostMapping("/updateSubstationDeviceById")
    @ApiOperation("修改巡视点位")
    @PreAuthorize("@el.check('update:device')")
    public ResponseResult updateSubstationDeviceById(@RequestBody SubstationDevice substationDevice) {
        if (substationDevice == null) {
            return ResponseResult.error("参数为空");
        }
        String deviceId = substationDevice.getDeviceId();
        String deviceCode = substationDevice.getDeviceCode();
        LambdaQueryWrapper<SubstationDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(SubstationDevice::getDeviceId, deviceId).eq(SubstationDevice::getDeviceCode, deviceCode);
        int count = substationDeviceService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("当前巡视点位已经存在");
        }
        String recognitionTypeList = substationDevice.getRecognitionTypeList();
        // 根据识别类型判断文件类型
        if (!Objects.isNull(recognitionTypeList)) {
            if ("4".equals(recognitionTypeList)) {
                substationDevice.setSaveTypeList("1");
            } else if ("5".equals(recognitionTypeList)) {
                substationDevice.setSaveTypeList("3");
            } else if ("6".equals(recognitionTypeList)) {
                substationDevice.setSaveTypeList("4");
            } else {
                substationDevice.setSaveTypeList("2");
            }
        }
        String[] split = recognitionTypeList.split(",");
        List<String> recognitions = new ArrayList<>(Arrays.asList(split));
        List<Map<String, Object>> maps2 = typeList.get("recognition_type");
        List<String> recognitionNames = new ArrayList<>();
        for (Map<String, Object> map : maps2) {
            String itemcode = map.get("itemcode").toString();
            if (recognitions.contains(itemcode)) {
                String dictname = map.get("dictname").toString();
                recognitionNames.add(dictname);
            }
        }
        String join1 = String.join(",", recognitionNames);
        substationDevice.setRecognitionTypeNameList(join1);
        substationDevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationDevice.setLastmodifydate(LocalDateTime.now());
        SubstationComponent component = substationMaindeviceService.getComponentById(substationDevice.getComponentId());
        if (component != null) {
            substationDevice.setComponentName(component.getComponentName());
        }
        boolean ok = substationDeviceService.updateById(substationDevice);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @PostMapping("/updateSubstationDevice")
    @ApiOperation("临时修改巡视点位")
    public ResponseResult updateSubstationDevice(@RequestBody SubstationDevice substationDevice) {
        substationDeviceService.updateById(substationDevice);
        return ResponseResult.success();
    }

    @GetMapping("/getSubstationDeviceById")
    @ApiOperation("根据Id查询巡视点位")
    public ResponseResult getSubstationDeviceById(String id) {
        SubstationDevice substationDevice = substationDeviceService.getById(id);
        return ResponseResult.successData(substationDevice);
    }

    @Log(module = "巡视点位设置", value = "删除巡视点位", type = "1")
    @PostMapping("/deleteSubstationDeviceById")
    @ApiOperation("删除巡视点位")
    @PreAuthorize("@el.check('del:device')")
    public ResponseResult deleteSubstationDeviceById(String deviceId) {
        if (StrUtil.isBlank(deviceId)) {
            return ResponseResult.error("参数为空");
        }
        boolean ok = substationDeviceService.deleteSubstationDeviceById(deviceId);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }
    }

    @Log(module = "巡视点位设置", value = "设置巡视点位状态是否启用", type = "1")
    @PostMapping("/setSubstationDeviceStatus")
    @ApiOperation("设置巡视点位状态是否启用")
    public ResponseResult setSubstationDeviceStatus(String deviceId, String dataStatus) {
        boolean ok = substationDeviceService.setSubstationDeviceStatus(deviceId, dataStatus);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    /***********************************
     * 用途说明：保存图片模板
     * 参数说明
     * deviceId  点位ID
     * multipartFile   文件对象
     * 返回值说明: 文件名
     ************************************/
    @ApiOperation("截图并且保存图片模板")
    @PostMapping(value = "/saveImgTemplate")
    public ResponseResult saveImgTemplate(HttpServletResponse response, String deviceId, String devicecode,
                                          String channelcode) throws Exception {
        if (StrUtil.isBlank(deviceId)) {
            ResponseResult.error("参数为空");
        }
        if (StrUtil.isBlank(devicecode) && StrUtil.isBlank(channelcode)) {
            return ResponseResult.error("没有通道信息");
        }
        String filename = substationDeviceService.saveImgTemplate(response, deviceId, devicecode, channelcode);
        return ResponseResult.successData(filename);
    }

    /***********************************
     * 用途说明：新增40000条点位数据
     * 参数说明
     * deviceId  点位ID
     * multipartFile   文件对象
     * 返回值说明: 文件名
     ************************************/
    @ApiOperation("新增40000条点位数据")
    @PostMapping(value = "/deviceBatchAdd")
    public ResponseResult deviceBatchAdd() {

        List<SubstationDevice> deviceList = new ArrayList<>();
        for (int i = 1; i < 40000; i++) {
            String code = "20230802" + i;
            String name = "测试20230802" + i;
            SubstationDevice substationDevice = new SubstationDevice();
            substationDevice.setDeviceCode(code);
            substationDevice.setDeviceName(name);
            substationDevice.setStationId("9b4e9d9f70b2256a69dfcbdecb13c960");
            substationDevice.setStationName("东南区220KV标准型变电站");
            substationDevice.setStationCode("0001");
            substationDevice.setAreaId("7015de8df7881a1ce473b9180a21ba0d");
            substationDevice.setAreaName("主变区域");
            substationDevice.setBayId("1c116533607071930ab9dc85a508064f");
            substationDevice.setBayName("主变间隔2#");
            substationDevice.setMainDeviceId("b19198173d2325c29a114c98cd06efd4");
            substationDevice.setMainDeviceName("2#油浸式变压器");
            substationDevice.setDeviceType("1");
            substationDevice.setComponentId("6f7ef2895a58be8d8b951c74d94bcbeb");
            substationDevice.setComponentName("06.01测试部件");
            substationDevice.setMeterType("4");
            substationDevice.setAppearanceType("6");
            substationDevice.setRecognitionTypeList("{\"device_code\":\"\",\"device_pos\":\"\",\"robot_code\":\"\"," +
                    "\"robot_pos\":\"\",\"uav_code\":\"\"}");
            substationDevice.setDatastatus("1");
            substationDevice.setLastmodifier("测试40000条数据");
            substationDevice.setLastmodifydate(LocalDateTime.now());
            deviceList.add(substationDevice);
        }
        long l = System.currentTimeMillis();
        log.info("-----------------------------开始保存--------------------------------------");
        substationDeviceService.saveBatch(deviceList);
        log.info("-----------------------------保存结束--------------------------------------");
        long l1 = System.currentTimeMillis();
        log.info("耗时" + (l1 - l) / 1000);
        return ResponseResult.success();
    }

    @PostMapping("/uploadFile")
    @ApiOperation("导入文件")
    public ResponseResult uploadFile(MultipartFile file) throws Exception {
        String str = substationDeviceService.uploadExcel(file);
        if (StrUtil.isBlank(str)) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    @PostMapping("/deviceDownloadFile")
    @ApiOperation("导出点位")
    public void deviceDownloadFile(Page<Map<String, Object>> page, String bayId,
                                   String componentId, String mainDeviceId, String deviceName,
                                   HttpServletResponse response) throws IOException {
        substationDeviceService.deviceDownloadFile(page, bayId, componentId, mainDeviceId, deviceName, response);
    }

    @GetMapping("/getComponentTree")
    @ApiOperation("获取部件树")
    public ResponseResult getComponentTree(String bayId, String deviceName) {
        List<TreeNode> mapList = substationDeviceService.getComponentTree(bayId, deviceName);
        return ResponseResult.successData(mapList);
    }

    @GetMapping("/getBayTree")
    @ApiOperation("获取间隔树")
    public ResponseResult getBayTree(String stationCode, String deviceName) {
        TreeNode treeNode = substationDeviceService.getBayTree(stationCode, deviceName);
        return ResponseResult.successData(treeNode);
    }

    @GetMapping("/getDeviceList")
    @ApiOperation("获取点位信息")
    public ResponseResult getDeviceList(String componentId, String deviceName) {
        LambdaQueryWrapper<SubstationDevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(deviceName)) {
            queryWrapper.like(SubstationDevice::getDeviceName, deviceName);
        }
        queryWrapper.eq(SubstationDevice::getComponentId, componentId).select(SubstationDevice::getDeviceId,
                SubstationDevice::getDeviceName, SubstationDevice::getPatroldeviceJson,
                SubstationDevice::getComponentId);
        List<Map<String, Object>> mapList = substationDeviceService.listMaps(queryWrapper);
        return ResponseResult.successData(mapList);
    }

    @PostMapping("/deviceModelDownload")
    @ApiOperation("导出点位")
    public void deviceModelDownload(HttpServletResponse response) throws IOException {
        List<SubstationDevice> substationDevices = substationDeviceService.list();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (SubstationDevice substationDevice : substationDevices) {
            Map<String, Object> map = new HashMap<>();
            map.put("station_name", substationDevice.getStationName());
            map.put("station_code", substationDevice.getStationCode());
            map.put("area_id", substationDevice.getAreaId());
            map.put("area_name", substationDevice.getAreaName());
            map.put("device_id", substationDevice.getDeviceId());
            map.put("device_name", substationDevice.getDeviceName());
            map.put("component_id", substationDevice.getComponentId());
            map.put("component_name", substationDevice.getComponentName());
            map.put("bay_id", substationDevice.getBayId());
            map.put("bay_name", substationDevice.getBayName());
            map.put("main_device_id", substationDevice.getMainDeviceId());
            map.put("main_device_name", substationDevice.getMainDeviceName());
            map.put("device_type", substationDevice.getDeviceType());
            map.put("meter_type", substationDevice.getMeterType());
            map.put("appearance_type", substationDevice.getAppearanceType());
            map.put("save_type_list", substationDevice.getSaveTypeList());
            map.put("recognition_type_list", substationDevice.getRecognitionTypeList());
            map.put("phase", substationDevice.getPhase());
            map.put("device_info", substationDevice.getDeviceInfo());
            map.put("data_type", substationDevice.getDataType());
            map.put("lower_value", substationDevice.getLowerValue());
            map.put("upper_value", substationDevice.getUpperValue());
            map.put("video_pos", "");
            mapList.add(map);
        }
        StringBuilder xml = new StringBuilder();
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        xml.append("<").append("Device_Model").append(">\n");
        for (Map<String, Object> map : mapList) {
            xml.append("<Item ");
            for (String key : map.keySet()) {
                String value = "";
                if (ObjectUtil.isNotEmpty(map.get(key))) {
                    value = map.get(key).toString();
                }
                xml.append(key).append("=\"").append(value).append("\" ");
            }
            xml.append("/>\n");
        }
        xml.append("</").append("Device_Model").append(">");
        // 设置响应头
        response.setContentType("application/xml");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String fileName = "device_model.xml";
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        // 写入响应体
        try (PrintWriter out = response.getWriter()) {
            out.print(xml.toString());
            out.flush();
        }

    }

    @PostMapping("/createDeviceByLine")
    @ApiOperation("根据航线生成点位")
    public void createDeviceByLine(String filePath,String bayId,String bayName) throws IOException {
        try {
            List<String> labelList = new ArrayList<>();
            File file = new File(filePath);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(file);
            doc.getDocumentElement().normalize();
            // 查找所有wpml:action元素

            NodeList actionNodeList = doc.getElementsByTagName("Placemark");
            if (actionNodeList.getLength() > 0) {
                // 遍历所有action元素
                for (int i = 0; i < actionNodeList.getLength(); i++) {
                    Element actionElement = (Element) actionNodeList.item(i);

                    // 查找当前action元素下的wpml:actionActuatorFuncParam元素
                    NodeList funcParamNodeList = actionElement.getElementsByTagName("wpml:action");
                    for (int j = 0; j < funcParamNodeList.getLength(); j++) {
                        Element funcParamElement = (Element) funcParamNodeList.item(j);

                        // 查找wpml:label元素并获取其内容
                        NodeList labelNodeList = funcParamElement.getElementsByTagName("wpml:label");
                        if (labelNodeList.getLength() > 0) {
                            String label = labelNodeList.item(0).getTextContent();
                            labelList.add(label);
                        }
                    }

                }
            }
            /**
             * 变电站id
             */
            String stationId = "35c4e466ddd9809445d3f880f94b4a2f";

            String stationName = "500kV庄周变电站";

            /**
             * 和中台对应资源 ID 保持一致
             */
            String stationCode = "7FE4BB37-F54A-4808-852B-6CAB43DD71B3-00001";

            /**
             * 和中台对应资源 ID 保持一致
             */
            String areaId = "f77421bca31a87c361e87e6ee107c5ed";

            /**
             * 区域全名
             */
            String areaName = "无人机巡检区域";

            /**
             * 和中台对应资源 ID 保持一致
             */
//            String bayId = "753befbf2a10ed3c684f2b4ddd1be8bd";

            /**
             * 间隔全名
             */
//            String bayName = "无人机巡检间隔";

            /**
             * 主设备ID，和中台对应资源 ID 保持一致
             */
            String mainDeviceId = "7f84eebefcf838f9419f433e5e740d68";

            /**
             * 主设备全名
             */
            String mainDeviceName = "无人机巡检主设备";

            /**
             * 主设备类型，字典项，选择主设备列表的时候带过来
             */
            String deviceType = "24";

            /**
             * 和中台对应资源 ID 保持一致
             */
            String componentId = "2ad2ceca3116b07a5f5689d302778f7d";

            /**
             * 部件名称
             */
            String componentName = "无人机巡检部件";

            /**
             * 采集/保存文件类型列表，格式：多个采集文件类型，采用","分隔
             */
            String saveTypeList = "2";

            /**
             * 识别类型列表，格式：多个识别类型，采用","分隔
             */
            String recognitionTypeList = "2";

            /**
             * <1>:=A 相<2>:=B 相<3>:=C 相 多个相位，采用"，"分隔
             */
            String phase = "1";


            /**
             * 按位定义数据来源，支持 32 位 1 为有效， 0 为无效，如下：第 0 位：摄像机第 1 位：机器人第 2 位：无人机第 3 位：声纹第 4 位：在线监测区域巡视主机上报上级系统填写
             */
            String dataType = "0x03";

            /**
             * 关联视频编码及预置位，json格式
             */
            String videoPos = "{\"device_code\":\"\",\"device_pos\":\"\",\"robot_code\":\"\",\"robot_pos\":\"\",\"uav_code\":\"\"}";

            /**
             * 0：不进行告警；1：进行告警
             */
            String isAlarm = "0";

            String deviceClass = "1";
            String pictureAnalysisTypeList = "{\"PictureDefectAnalysisType\":\"yw_gkxfw,yxdgsg,jyz_pl,bmwh,yw_nc\"}";
            log.info("=========labeiList========" + labelList.size());
            List<SubstationDevice> list = new ArrayList<>();
            LocalDateTime now = LocalDateTime.now();
            String prefix = "DJ_";
            String deviceCode = substationDeviceService.selectNextUavDeviceCode();
            int i = NumberUtil.parseInt(deviceCode);
            for (String label : labelList) {
                if (StrUtil.isBlank(label)) {
                    continue;
                }
                LambdaQueryWrapper<SubstationDevice> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SubstationDevice::getAreaId, areaId).eq(SubstationDevice::getDeviceName, label);
                int count = substationDeviceService.count(queryWrapper);
                if (count > 0) {
                    continue;
                }
                SubstationDevice substationDevice = new SubstationDevice();
                substationDevice.setStationId(stationId);
                substationDevice.setStationCode(stationCode);
                substationDevice.setStationName(stationName);
                substationDevice.setAreaId(areaId);
                substationDevice.setAreaName(areaName);
                substationDevice.setBayId(bayId);
                substationDevice.setBayName(bayName);
                substationDevice.setMainDeviceId(mainDeviceId);
                substationDevice.setMainDeviceName(mainDeviceName);
                substationDevice.setDeviceType(deviceType);
                substationDevice.setComponentId(componentId);
                substationDevice.setComponentName(componentName);
                substationDevice.setSaveTypeList(saveTypeList);
                substationDevice.setRecognitionTypeList(recognitionTypeList);
                substationDevice.setDeviceName(label);
                substationDevice.setIsAlarm(isAlarm);
                substationDevice.setVideoPos(videoPos);
                substationDevice.setPhase(phase);
                substationDevice.setDataType(dataType);
                substationDevice.setStationId(stationId);
                substationDevice.setLastmodifier("admin");
                substationDevice.setLastmodifydate(now);
                substationDevice.setIdentifyMaterialId("0");
                substationDevice.setDeviceClass(deviceClass);
                substationDevice.setPictureAnalysisTypeList(pictureAnalysisTypeList);

                String formattedString = String.format("%06d", i);
                substationDevice.setDeviceCode(prefix + formattedString);
                substationDevice.setDatastatus("1");
                substationDevice.setRecognitionTypeNameList("位置状态识别");
                list.add(substationDevice);
                i++;
            }
            substationDeviceService.saveBatch(list);
        } catch (Exception e) {
            log.error(e.getMessage());;
        }
    }

}
