package com.inspect.metadata.patrolpointmnt.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspect.base.core.domain.DataMsg;
import com.inspect.base.core.service.SyncDataToUpstreamService;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.SFTPUtil;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.xml.GenXmlByBean;
import com.inspect.metadata.alg.domain.BasedataAlgSubtype;
import com.inspect.metadata.alg.mapper.BasedataAlgSubtypeMapper;
import com.inspect.metadata.area.domain.BaseDataArea;
import com.inspect.metadata.area.mapper.BaseDataAreaMapper;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBook;
import com.inspect.metadata.eqpbook.domain.vo.PatrolTaskFtp;
import com.inspect.metadata.eqpbook.mapper.BasedataEqpBookChannelMapper;
import com.inspect.metadata.eqpbook.mapper.BasedataEqpBookMapper;
import com.inspect.metadata.patrolpointmnt.domain.BasedataPatrolPoint;
import com.inspect.metadata.patrolpointmnt.domain.BasedataPatrolPointPreset;
import com.inspect.metadata.patrolpointmnt.domain.vo.DevicePointModel;
import com.inspect.metadata.patrolpointmnt.domain.vo.DevicePointModelItem;
import com.inspect.metadata.patrolpointmnt.domain.vo.PointLatestResultVo;
import com.inspect.metadata.patrolpointmnt.domain.vo.PointStatsVo;
import com.inspect.metadata.patrolpointmnt.feign.FeignMinioService;
import com.inspect.metadata.patrolpointmnt.feign.MultipartFileUtils;
import com.inspect.metadata.patrolpointmnt.feign.UploadResponse;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataPatrolPointMapper;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataPatrolPointPresetMapper;
import com.inspect.metadata.patrolpointmnt.service.IBasedataPatrolPointService;
import com.inspect.metadata.prodevmnt.domain.BasedataDevice;
import com.inspect.metadata.prodevmnt.domain.BasedataDeviceType;
import com.inspect.metadata.prodevmnt.mapper.BasedataDeviceMapper;
import com.inspect.metadata.prodevmnt.mapper.BasedataDeviceTypeMapper;
import com.inspect.metadata.station.domain.BasedataStation;
import com.inspect.metadata.station.mapper.BasedataStationMapper;
import com.inspect.system.base.domain.SysDictData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

@Service
public class BasedataPatrolPointServiceImpl implements IBasedataPatrolPointService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    BasedataStationMapper basedataStationMapper;
    @Resource
    BasedataDeviceTypeMapper basedataDevicetypeMapper;
    @Resource
    BasedataPatrolPointPresetMapper basedataPatrolpointPresetMapper;
    @Resource
    BasedataEqpBookMapper basedataEqpbookMapper;
    @Resource
    BasedataEqpBookChannelMapper basedataEqpBookChannelMapper;
    @Resource
    BaseDataAreaMapper baseDataAreaMapper;
    @Resource
    SyncDataToUpstreamService syncDataToUpstreamService;
    @Resource
    private BasedataPatrolPointMapper basedataPatrolpointMapper;
    @Resource
    private BasedataDeviceMapper basedataDeviceMapper;
    @Resource
    private BasedataAlgSubtypeMapper basedataAlgSubtypeMapper;

    @Resource
    private FeignMinioService feignMinioService;

    public BasedataPatrolPoint selectBasedataPatrolPointByPatrolPointId(Long patrolPointId) {
        return this.basedataPatrolpointMapper.selectBasedataPatrolPointByPatrolPointId(patrolPointId);
    }

    public List<BasedataPatrolPoint> selectBasedataPatrolPointList(BasedataPatrolPoint basedataPatrolpoint) {
        return this.basedataPatrolpointMapper.selectBasedataPatrolPointList(basedataPatrolpoint);
    }

    @Override
    public List<BasedataPatrolPoint> selectBasedataMonitorList(BasedataPatrolPoint basedataPatrolpoint) {
        List<BasedataPatrolPoint> pointList = basedataPatrolpointMapper.selectBasedataMonitorList(basedataPatrolpoint);
        logger.info("[META] pointList size: {},pointList: {}", pointList.size(), pointList);

        // NOTE std_patrol_point_id关联匹配会导致点位管理查询出异常点位，暂时注释
//        if (null != basedataPatrolpoint.getDeviceId()) {
//            BasedataDevice basedataDevice = basedataDeviceMapper.selectBasedataDeviceByDeviceId(basedataPatrolpoint.getDeviceId());
//            if(basedataDevice != null) {
//                logger.info("before pointList size: {}", pointList.size());
//                basedataPatrolpoint.setDeviceTypeId(basedataDevice.getDeviceTypeId());
//                List<BasedataPatrolPoint> stdPointList = basedataPatrolpointMapper.selectBasedataMonitorUnionList(basedataPatrolpoint);
//                logger.info("[META] stdPointList cnt: {}", stdPointList.size());
//                for (BasedataPatrolPoint stdPoint : stdPointList) {
//                    if (!pointList.isEmpty()) {
//                        if (pointList.stream().filter((item) -> stdPoint.getStdParolPointId().equals(item.getStdParolPointId())).count() == 0) {
//                            pointList.add(stdPoint);
//                        }
//                    } else {
//                        pointList.add(stdPoint);
//                    }
//                }
//            } else {
//                logger.warn(Color.RED + "[META] basedataDevice deviceId: {} not exist!" + Color.END, basedataPatrolpoint.getDeviceId());
//            }
//            logger.info("after pointList size: {}, pointList: {}", pointList.size(), pointList);
//        }

        List<BasedataAlgSubtype> basedataAlgSubtypes = basedataAlgSubtypeMapper.selectBasedataAlgSubtypeList(new BasedataAlgSubtype());
        logger.info("[META] basedataAlgSubtypes cnt: {}", basedataAlgSubtypes.size());
        Map<String, String> algSubtypeMap = new HashMap<>();
        basedataAlgSubtypes.forEach((item) -> {
            algSubtypeMap.put(item.getAlgSubtypeId() + "", item.getAlgSubtypeName());
        });
        logger.info("[META] algSubtypeMap: {}", algSubtypeMap);
        List<SysDictData> dictList = getSysDictDataList("point_device_type");
        Optional<SysDictData> defaultDictData = dictList.stream()
                .filter(SysDictData::getDefault)
                .findFirst();
        for (BasedataPatrolPoint basedataPatrolPoint : pointList) {
            basedataPatrolPoint.loadAlgSubtypeName(algSubtypeMap);
            processPointType(basedataPatrolPoint, dictList, defaultDictData);
        }
        logger.info("[META] pointList size: {},pointList: {}", pointList.size(), pointList);
        return pointList;
    }

    @Override
    public List<BasedataPatrolPoint> selectBasedataMonitorRelationList(BasedataPatrolPoint basedataPatrolpoint) {
        List<BasedataPatrolPoint> pointList = basedataPatrolpointMapper.selectBasedataMonitorRelationList(basedataPatrolpoint);

        // NOTE std_patrol_point_id关联匹配会导致点位管理查询出异常点位，暂时注释
//        if (null != basedataPatrolpoint.getRelationDeviceId()) {
//            BasedataDevice basedataDevice = basedataDeviceMapper.selectBasedataDeviceRelationByDeviceId(basedataPatrolpoint.getRelationDeviceId());
//
//            if(basedataDevice != null) {
//                logger.info("[META] before pointList size: {}", pointList.size());
//                basedataPatrolpoint.setDeviceTypeId(basedataDevice.getDeviceTypeId());
//                List<BasedataPatrolPoint> stdPointList = basedataPatrolpointMapper.selectBasedataMonitorUnionList(basedataPatrolpoint);
//                logger.info("[META] stdPointList cnt: {}", stdPointList.size());
//                for (BasedataPatrolPoint stdPoint : stdPointList) {
//                    if (!pointList.isEmpty()) {
//                        if (pointList.stream().filter((item) -> stdPoint.getStdParolPointId().equals(item.getStdParolPointId())).count() == 0) {
////                            pointList.add(stdPoint);
//                        }
//                    } else {
//                        pointList.add(stdPoint);
//                    }
//                }
//            } else {
//                logger.warn(Color.RED + "[META] basedataDevice deviceId: {} not exist!" + Color.END, basedataPatrolpoint.getDeviceId());
//            }
//            logger.info("[META] after pointList size: {},pointList: {}", pointList.size(), pointList);
//        }

        List<BasedataAlgSubtype> basedataAlgSubtypes = basedataAlgSubtypeMapper.selectBasedataAlgSubtypeList(new BasedataAlgSubtype());
        logger.info("[META] basedataAlgSubtypes cnt: {}", basedataAlgSubtypes.size());
        Map<String, String> algSubtypeMap = new HashMap<>();
        basedataAlgSubtypes.forEach((item) -> {
            algSubtypeMap.put(item.getAlgSubtypeId() + "", item.getAlgSubtypeName());
        });
        logger.info("[META] algSubtypeMap: {}", algSubtypeMap);
        List<SysDictData> dictList = getSysDictDataList("point_device_type");
        Optional<SysDictData> defaultDictData = dictList.stream()
                .filter(SysDictData::getDefault)
                .findFirst();
        for (BasedataPatrolPoint basedataPatrolPoint : pointList) {
            basedataPatrolPoint.loadAlgSubtypeName(algSubtypeMap);
            processPointType(basedataPatrolPoint, dictList, defaultDictData);
        }
        logger.info("[META] pointList size: {},pointList: {}", pointList.size(), pointList);
        return pointList;
    }

    /**
     * 处理点位的设备类型
     *
     * @param dictList
     * @param basedataPatrolPoint
     */
    private void processPointType(BasedataPatrolPoint basedataPatrolPoint, List<SysDictData> dictList, Optional<SysDictData> defaultDictData) {
        String patrolPointCode = basedataPatrolPoint.getPatrolPointCode();
        if (StringUtils.isNotEmpty(patrolPointCode)) {
            if (patrolPointCode.contains("|")) {
                String finalPatrolPointCode = patrolPointCode.substring(0, patrolPointCode.indexOf("|"));
                Optional<String> pointTypeName = dictList.stream()
                        .filter(dict -> {
                            String valueStr = dict.getDictValue(); // 调用 getter
                            if (valueStr == null) {
                                return false;
                            }
                            return Arrays.stream(valueStr.split(","))
                                    .map(String::trim)
                                    .anyMatch(code -> code.equals(finalPatrolPointCode));
                        })
                        .map(SysDictData::getDictLabel)
                        .findFirst();
                basedataPatrolPoint.setPointTypeName(pointTypeName.orElse("未知设备类型"));
                basedataPatrolPoint.setPointTypeCode(finalPatrolPointCode);
            } else {
                defaultDictData.ifPresent(dict -> {
                    basedataPatrolPoint.setPointTypeName(dict.getDictLabel());
                    String[] codes = dict.getDictValue().split(",");
                    logger.info("[META] pointTypeCode: {}", codes);
                    if (codes.length > 0) {
                        basedataPatrolPoint.setPointTypeCode(codes[0]);
                    }
                });
            }
        }
    }

    private List<SysDictData> getSysDictDataList(String dictType) {
        return basedataPatrolpointMapper.selectDictDataByType(dictType);
    }

    public BasedataPatrolPoint insertBasedataPatrolPoint(BasedataPatrolPoint basedataPatrolpoint) {
        basedataPatrolpoint.setCreateTime(DateUtils.getNowDate());
        int resId = basedataPatrolpointMapper.insertBasedataPatrolPoint(basedataPatrolpoint);
        logger.info("[METADATA] insertBasedataPatrolPoint resId: {}", resId);
        return basedataPatrolpoint;
    }

    public int updateBasedataPatrolPoint(BasedataPatrolPoint basedataPatrolpoint) {
        basedataPatrolpoint.setUpdateTime(DateUtils.getNowDate());
        return this.basedataPatrolpointMapper.updateBasedataPatrolPoint(basedataPatrolpoint);
    }

    public int deleteBasedataPatrolPointByPatrolPointIds(Long[] patrolPointIds) {
        return this.basedataPatrolpointMapper.deleteBasedataPatrolPointByPatrolPointIds(patrolPointIds);
    }

    public int deleteBasedataPatrolPointByPatrolPointId(Long patrolPointId) {
        return this.basedataPatrolpointMapper.deleteBasedataPatrolPointByPatrolPointId(patrolPointId);
    }

    public int selectPresetPosByPatrolPointId(Long[] patrolPointIds) {
        return this.basedataPatrolpointMapper.selectPresetPosByPatrolPointId(patrolPointIds);
    }

    public String superSystemSynPatrolPointModel() {
        logger.info("[META] superSystemSynPatrolPointModel");
        List<BasedataStation> stations = this.basedataStationMapper.selectBasedataStationList(new BasedataStation());
        String stationNo = stations.get(0).getStationNo();
        if ("lingzhouzhiliu".equals(stationNo)) {
            stationNo = "1cc010d8a78a598ccb52fb470301531cbff88e26c5";
        }
        String modelXml = this.getModelXml(new BasedataPatrolPoint());
        System.out.println("modelXml::" + modelXml);
        if (null != modelXml && !modelXml.isEmpty()) {
            String typename = "device_file_path";
            String ftpUpPath = this.modelFileUpToFtps(typename, modelXml, stationNo);
            String filename = ftpUpPath.substring(ftpUpPath.lastIndexOf("/") + 1);
            ftpUpPath = modelFileUpToMinio(filename, modelXml);
            System.out.println("ftpUpPath::" + ftpUpPath);
            return ftpUpPath;
        } else {
            return null;
        }
    }

    @Async
    public void upPatrolPointModel(BasedataPatrolPoint basedataPatrolpoint) {
        String modelXml = this.getModelXml(basedataPatrolpoint);
        System.out.println("modelXml::" + modelXml);
        if (null != modelXml && !modelXml.isEmpty()) {
            List<BasedataStation> stations = this.basedataStationMapper.selectBasedataStationList(new BasedataStation());
            String stationNo = stations.get(0).getStationNo();
            String typename = "device_file_path";
            String ftpUpPath = this.modelFileUpToFtps(typename, modelXml, stationNo);
            System.out.println("ftpUpPath::" + ftpUpPath);
            BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
            basedataEqpbook.setType("20");
            List<BasedataEqpBook> eqpbooks = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("SendCode", eqpbooks.get(0).getPatrolDeviceCode());
            jsonObject.put("Code", stations.get(0).getStationNo());
            jsonObject.put("Type", 11);
            JSONObject jsonItem = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            jsonItem.put("time", DateUtils.getTime());
            jsonItem.put("type", "1");
            jsonItem.put("file_path", ftpUpPath);
            jsonArray.add(jsonItem);
            jsonObject.put("Items", jsonArray);
            String jsonString = jsonObject.toJSONString();
            this.syncDataToUpstreamService.postMessage(jsonString);
            System.out.println("jsonString:" + jsonString);
        }

    }

    private String getModelXml(BasedataPatrolPoint basedataPatrolpoint) {
        List<BasedataPatrolPoint> list = this.basedataPatrolpointMapper.selectBasedataPatrolPointList(basedataPatrolpoint);
        if (null != list && !list.isEmpty()) {
            logger.info("省侧点位同步[META] list size: {}", list.size());
            DevicePointModel devicePointModel = new DevicePointModel();
            List<DevicePointModelItem> items = new ArrayList<>();
            String station_id = null;
            String station_name = null;
            List<BasedataStation> stations = this.basedataStationMapper.selectBasedataStationList(new BasedataStation());
            if (null != stations && !stations.isEmpty()) {
                station_id = stations.get(0).getStationNo();
                // 灵州站编码
                if ("lingzhouzhiliu".equals(station_id)) {
                    station_id = "1cc010d8a78a598ccb52fb470301531cbff88e26c5";
                }
                station_name = stations.get(0).getStationName();
            }

            for (BasedataPatrolPoint patrolPoint : list) {
                Set<String> hashSet = new HashSet<>();
                DevicePointModelItem modelItem = new DevicePointModelItem();
                String main_device_name = null;
                String main_device_id = null;
                String device_type = null;
                String component_id = null;
                String component_name = null;
//                String device_id = patrolPoint.getPatrolPointCode();
                String device_id = patrolPoint.getPatrolPointId() + "";
                String device_name = patrolPoint.getPatrolPointName();
                String phase = null;
                String device_info = patrolPoint.getPatrolContent();
                String bay_id = null;
                String bay_name = null;
                String area_id = null;
                String area_name = null;
                new DevicePointModelItem();
                Long mainDeviceId = patrolPoint.getMainDeviceId();
                // 主设备
                BasedataDevice mainDevice = this.basedataDeviceMapper.selectBasedataDeviceByDeviceId(mainDeviceId);
                Long deviceId;
                if (null != mainDevice) {
                    main_device_name = mainDevice.getDeviceName();
                    main_device_id = patrolPoint.getMainDeviceId() + "";
                    deviceId = mainDevice.getDeviceTypeId();
                    // 设备类型
                    BasedataDeviceType deviceType = this.basedataDevicetypeMapper.selectBasedataDeviceTypeByDeviceTypeId(deviceId);
                    if (null != deviceType) {
                        device_type = deviceType.getDeviceTypeCode();
                    }
                }
                // 部件
                deviceId = patrolPoint.getDeviceId();
                BasedataDevice componentDevice = this.basedataDeviceMapper.selectBasedataDeviceByDeviceId(deviceId);
                if (null != componentDevice) {
                    component_id = patrolPoint.getDeviceId() + "";
                    component_name = componentDevice.getDeviceName();
                    String devicePhase = componentDevice.getPhase();
                    phase = this.handlePhase(devicePhase);
                }

                Long areaId = patrolPoint.getAreaId();
                if (null != areaId) {
                    BaseDataArea baseDataArea = this.baseDataAreaMapper.selectAreaById(areaId);
                    if (null != baseDataArea) {
//                        if ("bayunit".equals(baseDataArea.getAreaType())) {
                            bay_id = patrolPoint.getAreaId() + "";
//                            bay_id = baseDataArea.getUpSystemAreaId();
                            bay_name = baseDataArea.getAreaName();
//                            bay_name = baseDataArea.getUpSystemAreaName();
                            BaseDataArea areaPa = this.baseDataAreaMapper.selectAreaById(baseDataArea.getParentId());
                            if (null != areaPa) {
                                area_id = areaPa.getAreaId() + "";
                                area_name = areaPa.getAreaName();
                            } else {
//                                area_id = baseDataArea.getUpSystemAreaId();
//                                area_name = baseDataArea.getUpSystemAreaName();
                                area_id = patrolPoint.getAreaId() + "";
                                area_name = baseDataArea.getAreaName();
                            }
//                        } else {
//                            area_id = patrolPoint.getAreaId() + "";
//                            area_name = baseDataArea.getAreaName();
//                        }
                    }
                }

                String algSubtypeIds = patrolPoint.getAlgSubtypeIds();
                if (StringUtils.isNotEmpty(algSubtypeIds)) {
                    String[] split = algSubtypeIds.split(",");
                    for (String algSubtypeId : split) {
                        BasedataAlgSubtype basedataAlgSubtype = basedataAlgSubtypeMapper.selectBasedataAlgSubtypeByAlgSubtypeId(Long.valueOf(algSubtypeId));
                        if (basedataAlgSubtype != null && StringUtils.isNotEmpty(basedataAlgSubtype.getAlgSubtypeName())) {
                            if (basedataAlgSubtype.getAlgSubtypeName().contains("读数")) {
                                hashSet.add("1");
                            } else if (basedataAlgSubtype.getAlgSubtypeName().contains("红外")) {
                                hashSet.add("4");
                            } else {
                                hashSet.add("3");
                            }
                        }
                    }
                }
                BasedataPatrolPointPreset basedataPatrolpointPreset = new BasedataPatrolPointPreset();
                basedataPatrolpointPreset.setPatrolPointId(patrolPoint.getPatrolPointId());
                JSONArray presetJsonArray = this.modelPatrolPointPresetHandle(basedataPatrolpointPreset);
                String video_pos = "";
                if (!presetJsonArray.isEmpty()) {
//                    for (int j = 0; j < presetJsonArray.size(); ++j) {
//                        JSONObject presetJsonObject = presetJsonArray.getJSONObject(j);
//                        String deviceCode = presetJsonObject.getString("device_code");
//                        if (null != deviceCode && deviceCode.indexOf("#") != -1) {
//                            presetJsonObject.put("device_code", deviceCode.substring(0, deviceCode.indexOf("#")));
//                        }
//                    }
                    video_pos = presetJsonArray.toJSONString();
                }

                modelItem.setStation_name(nullToEmpty(station_name));
                modelItem.setStation_code(nullToEmpty(station_id));
                modelItem.setArea_id(nullToEmpty(area_id));
                modelItem.setArea_name(nullToEmpty(area_name));
                modelItem.setBay_id(nullToEmpty(bay_id));
                modelItem.setBay_name(nullToEmpty(bay_name));
                modelItem.setMain_device_id(nullToEmpty(main_device_id));
                modelItem.setMain_device_name(nullToEmpty(main_device_name));
                modelItem.setComponent_id(nullToEmpty(component_id));
                modelItem.setComponent_name(nullToEmpty(component_name));
                modelItem.setDevice_id(nullToEmpty(device_id));
                modelItem.setDevice_name(nullToEmpty(device_name));
                modelItem.setDevice_type(nullToEmpty(device_type));
                modelItem.setMeter_type("");
                modelItem.setAppearance_type("9");
                modelItem.setSave_type_list("");
                modelItem.setRecognition_type_list(hashSet.size() == 0 ? "" : StringUtils.join(hashSet, ","));
                modelItem.setPhase(nullToEmpty(phase));
                modelItem.setDevice_info(nullToEmpty(device_info));
                modelItem.setData_type("1");
                modelItem.setLower_value("");
                modelItem.setUpper_value("");
                modelItem.setVideo_pos(nullToEmpty(video_pos));
                modelItem.setPoint_type("1");
                modelItem.setLabel_attri("1");
                // 灵州站的设备类型为10000时，省侧规范中不存在10000，设备类型设置为空，相位也为空（）特殊处理一下
                if ("10000".equals(modelItem.getDevice_type()) || StringUtils.isEmpty(modelItem.getDevice_type())) {
                    modelItem.setDevice_type("21");
                }
//                if(hasChinese(main_device_id) || hasChinese(component_id) || hasChinese(device_id)) {
//                    continue;
//                }
                if (StringUtils.isEmpty(modelItem.getVideo_pos()) || StringUtils.isEmpty(modelItem.getMain_device_id()) || StringUtils.isEmpty(modelItem.getComponent_id())) {
                    continue;
                }

                items.add(modelItem);
            }
            logger.info("getModelXml items size: {}", items.size());
            devicePointModel.setItem(items);
            GenXmlByBean<Object> pulseGet = new GenXmlByBean<>();
            return pulseGet.getXml(devicePointModel);
        } else {
            return null;
        }
    }

    private String nullToEmpty(String str) {
        return null == str ? "" : str;
    }

    private boolean hasChinese(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        return str.matches(".*[\u4e00-\u9fa5].*");
    }

    public String xml(DevicePointModelItem devicePointModelItem, Long[] deviceIds) {
        DevicePointModel devicePointModel = new DevicePointModel();
        List<DevicePointModelItem> items = new ArrayList<>();
        List<BasedataDevice> basedataDeviceList = this.basedataDeviceMapper.selectPatrolPointList(deviceIds);
        int k = 0;

        for (int i = 0; i < basedataDeviceList.size(); ++i) {
            if ("Yes".equals(basedataDeviceList.get(i).getPowerMainEquFlag())) {
                k = i;
            }

            DevicePointModelItem modelItem = new DevicePointModelItem();
            modelItem.setStation_code(devicePointModelItem.getStation_code());
            modelItem.setStation_name(devicePointModelItem.getStation_name());
            modelItem.setBay_name(devicePointModelItem.getBay_name());
            modelItem.setBay_id(devicePointModelItem.getBay_id());
            modelItem.setDevice_info(devicePointModelItem.getDevice_info());
            modelItem.setPhase(devicePointModelItem.getPhase());
            modelItem.setDevice_type(devicePointModelItem.getDevice_type());
            modelItem.setMeter_type(devicePointModelItem.getMeter_type());
            modelItem.setAppearance_type(devicePointModelItem.getAppearance_type());
            modelItem.setSave_type_list(devicePointModelItem.getSave_type_list());
            modelItem.setArea_id(devicePointModelItem.getArea_id());
            modelItem.setArea_name(devicePointModelItem.getArea_name());
            modelItem.setRecognition_type_list(devicePointModelItem.getRecognition_type_list());
            modelItem.setVideo_pos(devicePointModelItem.getVideo_pos());
            modelItem.setDevice_id(basedataDeviceList.get(i).getMonitorIndexNo());
            modelItem.setDevice_name(basedataDeviceList.get(i).getDeviceName());
            modelItem.setMain_device_id(basedataDeviceList.get(k).getDeviceCode());
            modelItem.setMain_device_name(basedataDeviceList.get(k).getDeviceName());
            modelItem.setComponent_id(basedataDeviceList.get(i).getDeviceCode());
            modelItem.setComponent_name(basedataDeviceList.get(i).getDeviceName());
            if ("No".equals(basedataDeviceList.get(i).getPowerMainEquFlag())) {
                items.add(modelItem);
            }
        }

        devicePointModel.setItem(items);
        GenXmlByBean<Object> pulseGet = new GenXmlByBean<>();
        return pulseGet.getXml(devicePointModel).replaceAll("amp;", StringUtils.EMPTY);
    }



    private JSONArray modelPatrolPointPresetHandleOld(BasedataPatrolPointPreset basedataPatrolpointPreset) {
        JSONArray jsonArray = new JSONArray();
        List<BasedataPatrolPointPreset> presets = this.basedataPatrolpointPresetMapper.selectBasedataPatrolPointPresetList(basedataPatrolpointPreset);
        if (null != presets && !presets.isEmpty()) {
            Iterator<BasedataPatrolPointPreset> iterator = presets.iterator();
            while (true) {
                BasedataPatrolPointPreset preset;
                BasedataEqpBook eqpbook;
                String type;
                JSONObject jsonObject;
                String presetCode;
                do {
                    do {
                        if (!iterator.hasNext()) {
                            return jsonArray;
                        }

                        preset = iterator.next();
                        Long eqpBookId = preset.getEqpBookId();
                        eqpbook = this.basedataEqpbookMapper.selectBasedataEqpBookByEqpBookId(eqpBookId);
                    } while (null == eqpbook);

                    type = eqpbook.getType();
                    if ("10".equals(type)) {
                        jsonObject = new JSONObject();
                        jsonObject.put("device_code", eqpbook.getPatrolDeviceCode());
                        presetCode = preset.getPresetCode();
                        if (null != presetCode && !presetCode.isEmpty()) {
                            jsonObject.put("device_pos", presetCode);
                        } else {
                            jsonObject.put("device_pos", "1");
                        }

                        jsonArray.add(jsonObject);
                    }

                    if ("1".equals(type) || "2".equals(type) || "3".equals(type)) {
                        jsonObject = new JSONObject();
                        jsonObject.put("robot_code", eqpbook.getPatrolDeviceCode());
                        presetCode = preset.getPresetCode();
                        if (null != presetCode && !presetCode.isEmpty()) {
                            jsonObject.put("robot_pos", presetCode);
                        } else {
                            jsonObject.put("robot_pos", "1");
                        }

                        jsonArray.add(jsonObject);
                    }
                } while (!"13".equals(type));

                jsonObject = new JSONObject();
                jsonObject.put("uav_code", eqpbook.getPatrolDeviceCode());
                presetCode = preset.getPresetCode();
                if (null != presetCode && !presetCode.isEmpty()) {
                    jsonObject.put("uav_pos", presetCode);
                } else {
                    jsonObject.put("uav_pos", "1");
                }

                jsonArray.add(jsonObject);
            }
        } else {
            return jsonArray;
        }
    }


    private JSONArray modelPatrolPointPresetHandle(BasedataPatrolPointPreset basedataPatrolpointPreset) {
        JSONArray jsonArray = new JSONArray();
        List<BasedataPatrolPointPreset> presets = this.basedataPatrolpointPresetMapper.selectBasedataPatrolPointPresetList(basedataPatrolpointPreset);
        if (null != presets && !presets.isEmpty()) {
            Iterator<BasedataPatrolPointPreset> iterator = presets.iterator();
            while (true) {
                BasedataPatrolPointPreset preset;
                BasedataEqpBook eqpbook;
                String type = "";
                JSONObject jsonObject;
                String presetCode;
                do {
                    do {
                        if (!iterator.hasNext()) {
                            return jsonArray;
                        }

                        preset = iterator.next();
                        Long eqpBookId = preset.getEqpBookId();
                        eqpbook = this.basedataEqpbookMapper.selectBasedataEqpBookByEqpBookId(eqpBookId);
                    } while (null == eqpbook);
                    type = eqpbook.getType();
                    if ("10".equals(type)) {
                        jsonObject = new JSONObject();
                        jsonObject.put("device_code", eqpbook.getUpSystemDeviceCode());
                        presetCode = preset.getPresetCode();
                        if (null != presetCode && !presetCode.isEmpty()) {
                            jsonObject.put("device_pos", presetCode);
                        } else {
                            jsonObject.put("device_pos", "1");
                        }

                        jsonArray.add(jsonObject);
                    }

                    if ("1".equals(type) || "2".equals(type) || "3".equals(type)) {
                        jsonObject = new JSONObject();
                        jsonObject.put("robot_code", eqpbook.getUpSystemDeviceCode());
                        presetCode = preset.getPresetCode();
                        if (null != presetCode && !presetCode.isEmpty()) {
                            jsonObject.put("robot_pos", presetCode);
                        } else {
                            jsonObject.put("robot_pos", "1");
                        }

                        jsonArray.add(jsonObject);
                    }
                } while (!"13".equals(type));

                if ("13".equals(type)) {
                    jsonObject = new JSONObject();
                    jsonObject.put("uav_code", eqpbook.getUpSystemDeviceCode());
                    presetCode = preset.getPresetCode();
                    if (null != presetCode && !presetCode.isEmpty()) {
                        jsonObject.put("uav_pos", presetCode);
                    } else {
                        jsonObject.put("uav_pos", "1");
                    }

                    jsonArray.add(jsonObject);
                }
            }
        } else {
            return jsonArray;
        }
    }

    private String handlePhase(String localPhase) {
        StringBuilder builder = new StringBuilder();
        if (null != localPhase && !"O".equals(localPhase) && !localPhase.isEmpty()) {
            char[] chars = localPhase.toCharArray();

            for (int i = 0; i < chars.length; ++i) {
                char c = chars[i];
                switch (Character.toUpperCase(c)) {
                    case 'A':
                        c = '1';
                        break;
                    case 'B':
                        c = '2';
                        break;
                    case 'C':
                        c = '3';
                        break;
                    default:
                        // 保持原字符不变
                        break;
                }
                if (i == chars.length - 1) {
                    builder.append(c);
                } else {
                    builder.append(c);
                    builder.append(StringUtils.COMMA);
                }
            }
        }

        return builder.toString();
    }

    private String modelFileUpToFtps(String typename, String modelXml, String stationNo) {
        InputStream in_nocode = new ByteArrayInputStream(modelXml.getBytes());
        PatrolTaskFtp patrolTaskFtp = this.basedataEqpbookMapper.selectPatrolTaskFtpByLineId(3L);
        String filename = "device_model_" + System.currentTimeMillis();
        String fileUpPath = "";

        try {
            fileUpPath = stationNo + "/Model/";
            DataMsg DataMsg = new DataMsg();
            DataMsg.setIp(patrolTaskFtp.getFtpIp());
            DataMsg.setPort(patrolTaskFtp.getFtpPort());
            DataMsg.setUsername(patrolTaskFtp.getFtpUserName());
            DataMsg.setPassword(patrolTaskFtp.getFtpPwd());
            DataMsg.setBasePath(patrolTaskFtp.getFtpPath());
            DataMsg.setType("0");
            DataMsg.setFilePath(fileUpPath);
            DataMsg.setFileName(filename + ".xml");
            DataMsg.setInputStream(in_nocode);
            DataMsg.setIsImplicit("true");
            SFTPUtil.uploadFileForXml(DataMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return fileUpPath + filename + ".xml";
    }

    private String modelFileUpToMinio(String filename, String modelXml) {
        UploadResponse uploadResponse = new UploadResponse("test", "http://emptu.com");
        try {
            MultipartFile multipartFile = MultipartFileUtils.toMultipartFile(new ByteArrayInputStream(modelXml.getBytes()),
                    filename,
                    ("application/octet-stream"));
            uploadResponse = feignMinioService.uploadFileToMinio(multipartFile);
            String path =  uploadResponse.getUrl();
            logger.info("path: " + path);
            return path;
        } catch (Exception e) {
            logger.error("error", e);
        }

        return "";
    }
    @Override
    public PointStatsVo getInspectPointStats(PointStatsVo pointStatsVo) {
        PointStatsVo inspectPointStats = basedataPatrolpointMapper.getInspectPointStats(pointStatsVo);
        List<BasedataPatrolPoint> basedataPatrolPoints = basedataPatrolpointMapper.selectBasedataPatrolPointList(new BasedataPatrolPoint());
        inspectPointStats.setInspectionPointTotal(basedataPatrolPoints.size());
        return inspectPointStats;
    }

    @Override
    public List<PointLatestResultVo> pointLatestResult(PointLatestResultVo pointLatestResultVo) {
        List<PointLatestResultVo> result = basedataPatrolpointMapper.pointLatestResult(pointLatestResultVo);
//        List<BasedataPatrolPoint> basedataPatrolPoints = basedataPatrolpointMapper.selectBasedataPatrolPointList(new BasedataPatrolPoint());
//        inspectPointStats.setInspectionPointTotal(basedataPatrolPoints.size());
        return result;
    }

    @Override
    public void updateBasedataPatrolPointRelation(Long toAreaId, Long deviceId) {
        basedataPatrolpointMapper.updateBasedataPatrolPointRelation(toAreaId, deviceId);
    }

    @Override
    public void batchUpdateBasedataPatrolPointRelation(Long toAreaId, Long toParentId, Long toDeviceId, List<Long> patrolPointIds) {
        basedataPatrolpointMapper.batchUpdateBasedataPatrolPointRelation(toAreaId, toParentId, toDeviceId, patrolPointIds);
    }
}
