package com.inspect.metadata.montdatamqhandle.service.component;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.service.IBaseDataAreaService;
import com.inspect.metadata.bdconfig.domain.BasedataBdConfigAlgConvert;
import com.inspect.metadata.bdconfig.domain.BasedataBdConfigDeviceConvert;
import com.inspect.metadata.bdconfig.domain.BasedataBdConfigMainSystem;
import com.inspect.metadata.bdconfig.mapper.BasedataBdConfigAlgConvertMapper;
import com.inspect.metadata.bdconfig.mapper.BasedataBdConfigDeviceConvertMapper;
import com.inspect.metadata.bdconfig.mapper.BasedataBdConfigMainSystemMapper;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBook;
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.DevicePointModelItem;
import com.inspect.metadata.patrolpointmnt.domain.vo.DevicePointModelItemVideoPos;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataPatrolPointPresetMapper;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataStdPatrolPointMapper;
import com.inspect.metadata.patrolpointmnt.service.IBasedataPatrolPointService;
import com.inspect.metadata.prodevmnt.domain.BasedataDevice;
import com.inspect.metadata.prodevmnt.mapper.BasedataDeviceMapper;
import com.inspect.metadata.prodevmnt.mapper.BasedataDeviceTypeMapper;
import com.inspect.metadata.prodevmnt.service.IBasedataDeviceService;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.json.XmlToJsonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component("basedataMontPatrolPointHandleComponent")
public class BasedataMontPatrolPointHandleComponent {
    private final Logger log = LoggerFactory.getLogger(BasedataMontPatrolPointHandleComponent.class);
    @Autowired
    private IBaseDataAreaService baseDataAreaService;//insert
    @Autowired
    private IBasedataDeviceService basedataDeviceService;//insert
    @Autowired
    private IBasedataPatrolPointService basedataPatrolPointService;//insert
    @Autowired
    BasedataPatrolPointPresetMapper basedataPatrolpointPresetMapper;//insert

    @Autowired
    private BasedataDeviceTypeMapper basedataDevicetypeMapper;
    @Autowired
    private BasedataDeviceMapper basedataDeviceMapper;
    @Autowired
    BasedataStdPatrolPointMapper basedataStdpatrolPointMapper;
    @Autowired
    BasedataEqpBookMapper basedataEqpbookMapper;
    @Autowired
    BasedataBdConfigMainSystemMapper basedataBdconfigMainsystemMapper;
    @Autowired
    BasedataBdConfigDeviceConvertMapper basedataBdconfigDeviceConvertMapper;
    @Autowired
    BasedataBdConfigAlgConvertMapper basedataBdconfigAlgConvertMapper;
    @Autowired
    BasedataAlgSubtypeMapper basedataAlgSubtypeMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public void handPointModelData(String SendCode, String pointModel) {
        String convertFlag = "0";
        String algConvertFlag = "0";
        if (null != SendCode) {
            BasedataBdConfigMainSystem mainSystem = basedataBdconfigMainsystemMapper.selectBasedataBdConfigMainSystemByMainSystemCode(SendCode);
            if (null != mainSystem) {
                String flag = mainSystem.getConvertFlag();
                if (null != flag && flag.equals("1")) {
                    convertFlag = "1";
                }

                String algFlag = mainSystem.getAlgConvertFlag();
                if (null != algFlag && algFlag.equals("1")) {
                    algConvertFlag = "1";
                }
            }
        }

        JSONObject jsonObject1 = XmlToJsonUtil.xmlToJsonObject(pointModel);
        assert jsonObject1 != null;
        log.info("MODEL_SYNC XML_TO_JSON: {}", jsonObject1.toJSONString());
        handleJsonObject(jsonObject1, SendCode);
    }

    private void handleJsonObject(JSONObject jsonObject, String sendCode) {
        Map<String, List<String>> deviceMap = new HashMap<>();
        Map<String, List<String>> areaMap = new HashMap<>();
        Object o = jsonObject.get("Item");
        if (o instanceof JSONObject) {
            JSONObject jsonObj = (JSONObject) o;
            DevicePointModelItem javaObject = jsonObj.toJavaObject(DevicePointModelItem.class);
        } else if (o instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) o;
            List<DevicePointModelItem> list = jsonArray.toJavaList(DevicePointModelItem.class);
            if (null != list && !list.isEmpty()) {
                Iterator<DevicePointModelItem> iterator = list.iterator();

                String device_id;
                String device_name;
                while (iterator.hasNext()) {
                    DevicePointModelItem modelItem = iterator.next();
                    String areaKey = modelItem.getArea_id() + ":" + modelItem.getArea_name();
                    String areaData = modelItem.getBay_id() + ":" + modelItem.getBay_name();
                    List areaDataMap = areaMap.get(areaKey);
                    if (CollectionUtils.isNotEmpty(areaDataMap)) {
                        if (!areaDataMap.contains(areaData)) {
                            areaDataMap.add(areaData);
                            areaMap.put(areaKey, areaDataMap);
                        }
                    } else {
                        areaDataMap = new ArrayList<>();
                        areaDataMap.add(areaData);
                        areaMap.put(areaKey, areaDataMap);
                    }

                    device_id = modelItem.getMain_device_id() + ":" + modelItem.getMain_device_name() + ":" + modelItem.getBay_id() + ":" + modelItem.getBay_name();
                    device_name = modelItem.getComponent_id() + ":" + modelItem.getComponent_name();
                    List mainDeviceDataMap = deviceMap.get(device_id);
                    if (CollectionUtils.isNotEmpty(mainDeviceDataMap)) {
                        if (!mainDeviceDataMap.contains(device_name)) {
                            mainDeviceDataMap.add(device_name);
                            deviceMap.put(device_id, mainDeviceDataMap);
                        }
                    } else {
                        mainDeviceDataMap = new ArrayList<>();
                        mainDeviceDataMap.add(device_name);
                        deviceMap.put(device_id, mainDeviceDataMap);
                    }
                }

                log.info("HANDLE_JSON_OBJECT areaMap.size: {}, deviceMap.size: {}, list.size: {}", areaMap.size(), deviceMap.size(), list.size());
                this.saveAreaData(areaMap, sendCode);
                this.saveMainDeviceData(deviceMap, sendCode);
                String convertFlag = "0";
                String algConvertFlag = "0";


                for (DevicePointModelItem devicePointModelItem : list) {
                    DevicePointModelItem modelItem = devicePointModelItem;
                    BasedataPatrolPoint patrolPointInsert = new BasedataPatrolPoint();
                    device_id = modelItem.getDevice_id();
                    device_name = modelItem.getDevice_name();
                    String main_device_id = modelItem.getMain_device_id();
                    String originalDeviceId = modelItem.getComponent_id();
                    String originalAlgSubtypeIds = modelItem.getRecognition_type_list();
                    /**
                     * 根据patrol_point_code(机器人sendCode+"|"+机器人上报点位device_id)从basedata_patrolpoint表中查询
                     */
                    BasedataPatrolPoint basedataPatrolpoint = new BasedataPatrolPoint();
                    basedataPatrolpoint.setPatrolPointCode(sendCode + "|" + device_id);
                    List<BasedataPatrolPoint> patrolpointList = this.basedataPatrolPointService.selectBasedataPatrolPointList(basedataPatrolpoint);
                    if (patrolpointList != null && !patrolpointList.isEmpty()) {
                        BasedataPatrolPoint patrolPoint = patrolpointList.get(0);
                        DevicePointModelItem item = new DevicePointModelItem();
                        this.handPointPresetNew(patrolPoint.getPatrolPointId(), item, sendCode);
                    } else {
                        BasedataDevice basedataDevice = new BasedataDevice();
                        basedataDevice.setOldDeviceId(sendCode + "_component_" + originalDeviceId);
                        List<BasedataDevice> devices = this.basedataDeviceMapper.selectBasedataDeviceList(basedataDevice);
                        if (CollectionUtils.isNotEmpty(devices) && !devices.isEmpty()) {
                            BasedataDevice device = devices.get(0);
                            patrolPointInsert.setPatrolPointCode(sendCode + "|" + device_id);
                            patrolPointInsert.setPatrolPointName(device_name);
                            patrolPointInsert.setOriginalMainDeviceId(main_device_id);
                            patrolPointInsert.setDeviceId(device.getDeviceId());
                            patrolPointInsert.setRelationDeviceId(device.getDeviceId());
                            patrolPointInsert.setCreateTime(DateUtils.getNowDate());
                            patrolPointInsert.setCreateBy("sys");
                            patrolPointInsert.setOriginalAlgSubtypeIds(originalAlgSubtypeIds);
                            patrolPointInsert.setOriginalDeviceId(originalDeviceId);
                            patrolPointInsert.setAlgSubtypeIds(originalAlgSubtypeIds);
                            patrolPointInsert.setPointImptLevel("Ⅰ");
                            patrolPointInsert.setMainDeviceId(device.getParentId());
                            patrolPointInsert.setRelationMainDeviceId(device.getParentId());
                            patrolPointInsert.setDeviceTypeId(978L);
                            patrolPointInsert.setAreaId(device.getAreaId());
                            patrolPointInsert.setRelationAreaId(device.getAreaId());
                            setAlgIdS(patrolPointInsert, sendCode, originalAlgSubtypeIds, algConvertFlag);
                            BasedataPatrolPoint patrolPointInsertRet = basedataPatrolPointService.insertBasedataPatrolPoint(patrolPointInsert);
                            Long patrolPointId = patrolPointInsertRet.getPatrolPointId();
                            DevicePointModelItem item = new DevicePointModelItem();
                            handPointPresetNew(patrolPointId, item, sendCode);
                        }
                    }
                }
            }
        }

    }

    public void handPointPresetNew(Long patrolPointId, DevicePointModelItem item, String sendCode) {
        log.info("sendCode: {}", sendCode);
        String video_pos = item.getVideo_pos();
        if (null == video_pos) {
            BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
            basedataEqpbook.setMainSystemCode(sendCode);
            List<BasedataEqpBook> eqpBooks = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
            if (null != eqpBooks && !eqpBooks.isEmpty()) {
                BasedataEqpBook eqpBook = eqpBooks.get(0);
                log.info("patrolDeviceCode: {}", eqpBook.getPatrolDeviceCode());
                this.insertPatrolPointPresetNew(patrolPointId, eqpBook.getPatrolDeviceCode(), "");
            }
        }

    }

    public void insertPatrolPointPresetNew(Long patrolPointId, String deviceCode, String devicePos) {
        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        basedataEqpbook.setPatrolDeviceCode(deviceCode);
        List<BasedataEqpBook> eqpBooks = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
        if (!eqpBooks.isEmpty()) {
            Long eqpBookId = eqpBooks.get(0).getEqpBookId();
            BasedataPatrolPointPreset basedataPatrolpointPreset = new BasedataPatrolPointPreset();
            basedataPatrolpointPreset.setEqpBookId(eqpBookId);
            basedataPatrolpointPreset.setPresetCode(devicePos);
            basedataPatrolpointPreset.setPatrolPointId(patrolPointId);
            List<BasedataPatrolPointPreset> presets = this.basedataPatrolpointPresetMapper.selectBasedataPatrolPointPresetList(basedataPatrolpointPreset);
            log.info("presets.size: {}, json: {}", presets.size(), JSONObject.toJSONString(presets));
            BasedataPatrolPointPreset pointPreset;
            if (null != presets && !presets.isEmpty()) {
                pointPreset = presets.get(0);
                pointPreset.setPresetCode(devicePos);
                pointPreset.setPatrolDeviceCode(deviceCode);
                pointPreset.setUpdateBy("sys");
                pointPreset.setUpdateTime(DateUtils.getNowDate());
                this.basedataPatrolpointPresetMapper.updateBasedataPatrolPointPreset(pointPreset);
            } else {
                pointPreset = new BasedataPatrolPointPreset();
                pointPreset.setPatrolPointId(patrolPointId);
                pointPreset.setPresetCode(devicePos);
                pointPreset.setEqpBookId(eqpBookId);
                pointPreset.setPatrolDeviceCode(eqpBooks.get(0).getPatrolDeviceCode());
                pointPreset.setCreateBy("sys");
                pointPreset.setCreateTime(DateUtils.getNowDate());
                this.basedataPatrolpointPresetMapper.insertBasedataPatrolPointPreset(pointPreset);
            }
        } else {
            BasedataPatrolPointPreset basedataPatrolpointPreset = new BasedataPatrolPointPreset();
            basedataPatrolpointPreset.setPatrolPointId(patrolPointId);
            basedataPatrolpointPreset.setPatrolDeviceCode(deviceCode);
            basedataPatrolpointPreset.setPresetCode(devicePos);
            this.basedataPatrolpointPresetMapper.insertBasedataPatrolPointPreset(basedataPatrolpointPreset);
        }

    }

    private void handleItem(DevicePointModelItem item, String SendCode, String convertFlag, String algConvertFlag) {
        String area_id = item.getArea_id();
        String area_name = item.getArea_name();
        String bay_id = item.getBay_id();
        String bay_name = item.getBay_name();
        String main_device_id = item.getMain_device_id();
        String main_device_name = item.getMain_device_name();
        String component_id = item.getComponent_id();
        String component_name = item.getComponent_name();
        String device_id = item.getDevice_id();
        String device_name = item.getDevice_name();
        String device_type = item.getDevice_type();
        String meter_type = item.getMeter_type();
        String appearance_type = item.getAppearance_type();
        String save_type_list = item.getSave_type_list();
        String recognition_type_list = item.getRecognition_type_list();
        String phase = item.getPhase();
        String device_info = item.getDevice_info();
        String data_type = item.getData_type();
        String lower_value = item.getLower_value();
        String upper_value = item.getUpper_value();
        Long main_device_type_id = null;
        Long component_type_id = null;
        Long mainDeviceId = null;
        Long componentId = null;
        Long stdPatrolPointId = null;
        Long patrolpointId = null;
        BasedataPatrolPoint patrolPointInsert = new BasedataPatrolPoint();
        BasedataPatrolPoint basedataPatrolpoint = new BasedataPatrolPoint();
        basedataPatrolpoint.setPatrolPointCode(device_id);
        List<BasedataPatrolPoint> patrolpointList = this.basedataPatrolPointService.selectBasedataPatrolPointList(basedataPatrolpoint);
        BasedataPatrolPoint patrolPointInsertRet;
        if (null != patrolpointList && !patrolpointList.isEmpty()) {
            patrolPointInsertRet = patrolpointList.get(0);
            this.setDeviceId(patrolPointInsertRet, SendCode, main_device_id, component_id, convertFlag);
            this.setAlgIdS(patrolPointInsertRet, SendCode, recognition_type_list, algConvertFlag);
            patrolPointInsertRet.setUpdateBy("sys");
            patrolPointInsertRet.setUpdateTime(DateUtils.getNowDate());
            patrolPointInsertRet.setPatrolPointName(device_name);
            patrolPointInsertRet.setOriginalAlgSubtypeIds(recognition_type_list);
            this.basedataPatrolPointService.updateBasedataPatrolPoint(patrolPointInsertRet);
        } else {
            patrolPointInsert.setPatrolPointCode(device_id);
            patrolPointInsert.setPatrolPointName(device_name);
            patrolPointInsert.setOriginalMainDeviceId(main_device_id);
            patrolPointInsert.setDeviceId(componentId);
            patrolPointInsert.setCreateTime(DateUtils.getNowDate());
            patrolPointInsert.setCreateBy("sys");
            patrolPointInsert.setOriginalAlgSubtypeIds(recognition_type_list);
            patrolPointInsert.setOriginalDeviceId(component_id);
            patrolPointInsert.setAlgSubtypeIds(recognition_type_list);
            patrolPointInsert.setPointImptLevel("Ⅰ");
            this.setDeviceId(patrolPointInsert, SendCode, main_device_id, component_id, convertFlag);
            this.setAlgIdS(patrolPointInsert, SendCode, recognition_type_list, algConvertFlag);
            patrolPointInsertRet = this.basedataPatrolPointService.insertBasedataPatrolPoint(patrolPointInsert);
        }
        patrolpointId = patrolPointInsertRet.getPatrolPointId();
        this.handPointPreset(patrolpointId, item);
    }

    public void setDeviceId(BasedataPatrolPoint patrolPointInsert, String SendCode, String main_device_id, String component_id, String convertFlag) {
        List converts;
        List convertList;
        if (convertFlag.equals("0")) {
            BasedataDevice basedataDevice = new BasedataDevice();
            basedataDevice.setDeviceCode(main_device_id);
            converts = this.basedataDeviceMapper.selectBasedataDeviceList(basedataDevice);
            Long componentTypeId;
            if (!converts.isEmpty()) {
                Long main_device_type_id = ((BasedataDevice) converts.get(0)).getDeviceTypeId();
                componentTypeId = ((BasedataDevice) converts.get(0)).getDeviceId();
                patrolPointInsert.setMainDeviceId(componentTypeId);
                patrolPointInsert.setDeviceTypeId(main_device_type_id);
                patrolPointInsert.setAreaId(((BasedataDevice) converts.get(0)).getAreaId());
            }

            basedataDevice.setDeviceCode(component_id);
            convertList = this.basedataDeviceMapper.selectBasedataDeviceList(basedataDevice);
            if (!convertList.isEmpty()) {
                componentTypeId = ((BasedataDevice) convertList.get(0)).getDeviceTypeId();
                Long deviceId = ((BasedataDevice) convertList.get(0)).getDeviceId();
                patrolPointInsert.setDeviceId(deviceId);
                patrolPointInsert.setAreaId(((BasedataDevice) convertList.get(0)).getAreaId());
            }
        } else if (convertFlag.equals("1")) {
            BasedataBdConfigDeviceConvert deviceConvert = new BasedataBdConfigDeviceConvert();
            deviceConvert.setMainSystemCode(SendCode);
            deviceConvert.setOriginalDeviceCode(main_device_id);
            converts = this.basedataBdconfigDeviceConvertMapper.selectBasedataBdConfigDeviceConvertList(deviceConvert);
            if (null != converts && !converts.isEmpty()) {
                BasedataBdConfigDeviceConvert convert = (BasedataBdConfigDeviceConvert) converts.get(0);
                patrolPointInsert.setMainDeviceId(convert.getDeviceId());
                BasedataDevice basedataDevice = this.basedataDeviceMapper.selectBasedataDeviceByDeviceId(convert.getDeviceId());
                patrolPointInsert.setAreaId(basedataDevice.getAreaId());
            }

            deviceConvert.setOriginalDeviceCode(component_id);
            convertList = this.basedataBdconfigDeviceConvertMapper.selectBasedataBdConfigDeviceConvertList(deviceConvert);
            if (null != convertList && !convertList.isEmpty()) {
                BasedataBdConfigDeviceConvert convertC = (BasedataBdConfigDeviceConvert) convertList.get(0);
                patrolPointInsert.setDeviceId(convertC.getDeviceId());
                BasedataDevice basedataDevice = this.basedataDeviceMapper.selectBasedataDeviceByDeviceId(convertC.getDeviceId());
                patrolPointInsert.setAreaId(basedataDevice.getAreaId());
            }
        }

    }

    public void setAlgIdS(BasedataPatrolPoint patrolPointInsert, String SendCode, String recognitionTypeList, String algConvertFlag) {
        if (null != recognitionTypeList && !recognitionTypeList.isEmpty()) {
            StringBuilder builder = new StringBuilder();
            StringBuilder nameBuilder = new StringBuilder();
            JSONArray jsonArray = new JSONArray();
            String[] recognition_type_array = recognitionTypeList.split(StringUtils.COMMA);

            for (String recognition_type : recognition_type_array) {
                List algConverts;
                String name;
                String algSubtypeId;
                if ("0".equals(algConvertFlag)) {
                    BasedataAlgSubtype basedataAlgSubtype = new BasedataAlgSubtype();
                    basedataAlgSubtype.setAlgSubtypeCode(recognition_type);
                    algConverts = this.basedataAlgSubtypeMapper.selectBasedataAlgSubtypeList(basedataAlgSubtype);
                    if (null != algConverts && !algConverts.isEmpty()) {
                        BasedataAlgSubtype algSubtype = (BasedataAlgSubtype) algConverts.get(0);
                        Long algId = algSubtype.getAlgId();
                        builder.append(algId);
                        name = algSubtype.getAlgSubtypeName();
                        nameBuilder.append(name);
                        JSONObject jsonObject = new JSONObject();
                        String lowerFlag = algSubtype.getLowerFlag();
                        if (null != lowerFlag && lowerFlag.equals("1")) {
                            jsonObject.put("lowerValue", algSubtype.getLowerValue());
                        }

                        algSubtypeId = algSubtype.getUpperFlag();
                        if (null != algSubtypeId && algSubtypeId.equals("1")) {
                            jsonObject.put("upperValue", algSubtype.getUpperValue());
                        }

                        if (!jsonObject.isEmpty()) {
                            jsonArray.add(jsonObject);
                            jsonObject.put("id", "sub_" + algSubtype.getAlgSubtypeId());
                            jsonObject.put("code", algSubtype.getAlgSubtypeCode());
                        }
                    }
                } else if ("1".equals(algConvertFlag)) {
                    BasedataBdConfigAlgConvert algConvert = new BasedataBdConfigAlgConvert();
                    algConvert.setMainSystemCode(SendCode);
                    algConvert.setOriginalAlgCode(recognition_type);
                    algConverts = this.basedataBdconfigAlgConvertMapper.selectBasedataBdConfigAlgConvertList(algConvert);
                    if (null != algConverts && !algConverts.isEmpty()) {
                        BasedataBdConfigAlgConvert configAlgConvert = (BasedataBdConfigAlgConvert) algConverts.get(0);
                        String algId = configAlgConvert.getAlgId();
                        builder.append(algId);
                        name = configAlgConvert.getAlgName();
                        nameBuilder.append(name);
                        if (null != algId && !algId.isEmpty()) {
                            String[] algIdArray = algId.split(StringUtils.COMMA);

                            for (String s : algIdArray) {
                                algSubtypeId = s;
                                BasedataAlgSubtype algSubtype = this.basedataAlgSubtypeMapper.selectBasedataAlgSubtypeByAlgSubtypeId(Long.valueOf(algSubtypeId));
                                JSONObject jsonObject = new JSONObject();
                                String lowerFlag = algSubtype.getLowerFlag();
                                if (null != lowerFlag && lowerFlag.equals("1")) {
                                    jsonObject.put("lowerValue", algSubtype.getLowerValue());
                                }

                                String upperFlag = algSubtype.getUpperFlag();
                                if (null != upperFlag && upperFlag.equals("1")) {
                                    jsonObject.put("upperValue", algSubtype.getUpperValue());
                                }

                                if (!jsonObject.isEmpty()) {
                                    jsonArray.add(jsonObject);
                                    jsonObject.put("id", "sub_" + algSubtype.getAlgSubtypeId());
                                    jsonObject.put("code", algSubtype.getAlgSubtypeCode());
                                }
                            }
                        }
                    }
                }
            }

            if (builder.length() > 0) {
                patrolPointInsert.setAlgSubtypeIds(builder.toString());
            }

            if (nameBuilder.length() > 0) {
                patrolPointInsert.setAlgSubtypeName(nameBuilder.toString());
            }

            String alarmThreshold = jsonArray.toJSONString();
            patrolPointInsert.setAlarmThreshold(alarmThreshold);
        }

    }

    public void handPointPreset(Long patrolPointId, DevicePointModelItem item) {
        String video_pos = item.getVideo_pos();
        if (null == video_pos) {
            BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
            Map<String, Object> params = new HashMap<>();
            params.put("robotFlag", "1");
            basedataEqpbook.setParams(params);
            List<BasedataEqpBook> eqpBooks = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
            if (null != eqpBooks && !eqpBooks.isEmpty()) {
                BasedataEqpBook eqpBook = eqpBooks.get(0);
                this.insertPatrolPointPreset(patrolPointId, eqpBook.getPatrolDeviceCode(), "");
            }
        } else {
            JSONArray jsonArray = JSONObject.parseArray(video_pos);
            List<DevicePointModelItemVideoPos> list = jsonArray.toJavaList(DevicePointModelItemVideoPos.class);
            if (null != list && !list.isEmpty()) {

                for (DevicePointModelItemVideoPos videoPos : list) {
                    String device_code = videoPos.getDevice_code();
                    String device_pos = videoPos.getDevice_pos();
                    if (StringUtils.isNotEmpty(device_code)) {
                        this.insertPatrolPointPreset(patrolPointId, device_code, device_pos);
                    }

                    String robot_code = videoPos.getRobot_code();
                    String robot_pos = videoPos.getRobot_pos();
                    if (StringUtils.isNotEmpty(robot_code)) {
                        this.insertPatrolPointPreset(patrolPointId, robot_code, robot_pos);
                    }

                    String uav_code = videoPos.getUav_code();
                    String uav_pos = videoPos.getUav_pos();
                    if (StringUtils.isNotEmpty(uav_code)) {
                        this.insertPatrolPointPreset(patrolPointId, uav_code, uav_pos);
                    }
                }
            }
        }

    }

    public void insertPatrolPointPreset(Long patrolPointId, String deviceCode, String devicePos) {
        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        basedataEqpbook.setPatrolDeviceCode(deviceCode);
        List<BasedataEqpBook> eqpBooks = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
        if (!eqpBooks.isEmpty()) {
            Long eqpBookId = eqpBooks.get(0).getEqpBookId();
            BasedataPatrolPointPreset basedataPatrolpointPreset = new BasedataPatrolPointPreset();
            basedataPatrolpointPreset.setEqpBookId(eqpBookId);
            basedataPatrolpointPreset.setPresetCode(devicePos);
            basedataPatrolpointPreset.setPatrolPointId(patrolPointId);
            List<BasedataPatrolPointPreset> presets = this.basedataPatrolpointPresetMapper.selectBasedataPatrolPointPresetList(basedataPatrolpointPreset);
            BasedataPatrolPointPreset pointPreset;
            if (null != presets && !presets.isEmpty()) {
                pointPreset = presets.get(0);
                pointPreset.setPresetCode(devicePos);
                pointPreset.setPatrolDeviceCode(deviceCode);
                pointPreset.setUpdateBy("sys");
                pointPreset.setUpdateTime(DateUtils.getNowDate());
                this.basedataPatrolpointPresetMapper.updateBasedataPatrolPointPreset(pointPreset);
            } else {
                pointPreset = new BasedataPatrolPointPreset();
                pointPreset.setPatrolPointId(patrolPointId);
                pointPreset.setPresetCode(devicePos);
                pointPreset.setEqpBookId(eqpBookId);
                pointPreset.setPatrolDeviceCode(eqpBooks.get(0).getPatrolDeviceCode());
                pointPreset.setCreateBy("sys");
                pointPreset.setCreateTime(DateUtils.getNowDate());
                this.basedataPatrolpointPresetMapper.insertBasedataPatrolPointPreset(pointPreset);
            }
        } else {
            BasedataPatrolPointPreset basedataPatrolpointPreset = new BasedataPatrolPointPreset();
            basedataPatrolpointPreset.setPatrolPointId(patrolPointId);
            basedataPatrolpointPreset.setPatrolDeviceCode(deviceCode);
            basedataPatrolpointPreset.setPresetCode(devicePos);
            this.basedataPatrolpointPresetMapper.insertBasedataPatrolPointPreset(basedataPatrolpointPreset);
        }

    }

    private void handleItemNew(DevicePointModelItem item, String SendCode, String convertFlag, String algConvertFlag) {
        String area_id = item.getArea_id();
        String area_name = item.getArea_name();
        String bay_id = item.getBay_id();
        String bay_name = item.getBay_name();
        String main_device_id = item.getMain_device_id();
        String main_device_name = item.getMain_device_name();
        String component_id = item.getComponent_id();
        String component_name = item.getComponent_name();
        String device_id = item.getDevice_id();
        String device_name = item.getDevice_name();
        String device_type = item.getDevice_type();
        String meter_type = item.getMeter_type();
        String appearance_type = item.getAppearance_type();
        String save_type_list = item.getSave_type_list();
        String recognition_type_list = item.getRecognition_type_list();
        String phase = item.getPhase();
        String device_info = item.getDevice_info();
        String data_type = item.getData_type();
        String lower_value = item.getLower_value();
        String upper_value = item.getUpper_value();
        Long main_device_type_id = null;
        Long component_type_id = null;
        Long mainDeviceId = null;
        Long deviceId = null;
        Long stdPatrolPointId = null;
        Long patrolpointId = null;
        BasedataPatrolPoint patrolPointInsert = new BasedataPatrolPoint();
        BasedataPatrolPoint basedataPatrolpoint = new BasedataPatrolPoint();
        basedataPatrolpoint.setPatrolPointCode(device_id);
        List<BasedataPatrolPoint> patrolpointList = this.basedataPatrolPointService.selectBasedataPatrolPointList(basedataPatrolpoint);
        if (null == patrolpointList || patrolpointList.isEmpty()) {
            patrolPointInsert.setPatrolPointCode(device_id);
            patrolPointInsert.setPatrolPointName(device_name);
            patrolPointInsert.setOriginalMainDeviceId(main_device_id);
            patrolPointInsert.setDeviceId(deviceId);
            patrolPointInsert.setCreateTime(DateUtils.getNowDate());
            patrolPointInsert.setCreateBy("sys");
            patrolPointInsert.setOriginalAlgSubtypeIds(recognition_type_list);
            patrolPointInsert.setOriginalDeviceId(component_id);
            patrolPointInsert.setAlgSubtypeIds(recognition_type_list);
            patrolPointInsert.setPointImptLevel("Ⅰ");
            this.setDeviceId(patrolPointInsert, SendCode, main_device_id, component_id, convertFlag);
            this.setAlgIdS(patrolPointInsert, SendCode, recognition_type_list, algConvertFlag);
            BasedataPatrolPoint patrolPointInsertRet = this.basedataPatrolPointService.insertBasedataPatrolPoint(patrolPointInsert);
            patrolpointId = patrolPointInsertRet.getPatrolPointId();
            this.handPointPreset(patrolpointId, item);
        }

    }

    private void saveMainDeviceData(Map<String, List<String>> deviceMap, String sendCode) {
        int count = 0;
        int count1 = 0;
        int count2 = 0;

        for (String deviceKey : deviceMap.keySet()) {
            ++count;
            List deviceList = deviceMap.get(deviceKey);
            BasedataDevice device = new BasedataDevice();
            String deviceId = deviceKey.split(StringUtils.COLON)[0];
            String deviceName = deviceKey.split(StringUtils.COLON)[1];
            String oldAreaId = deviceKey.split(StringUtils.COLON)[2];
            String areaName = deviceKey.split(StringUtils.COLON)[3];
            device.setOldDeviceId(sendCode + "_main_" + deviceId);
            List<BasedataDevice> basedataDeviceList = this.basedataDeviceService.selectBasedataDeviceList(device);
            Long pid = 0L;
            if (CollectionUtils.isEmpty(basedataDeviceList)) {
                ++count1;
                BaseDataArea area = new BaseDataArea();
                area.setOldAreaId(sendCode + "_" + oldAreaId);
                List<BaseDataArea> areaList = this.baseDataAreaService.selectAreaList(area);
                if (!CollectionUtils.isEmpty(areaList)) {
                    BaseDataArea baseDataArea = areaList.get(0);
                    pid = baseDataArea.getAreaId();
                }
                device.setParentId(0L);
                device.setOldAreaName(areaName);
                device.setOldAreaId(sendCode + "_" + oldAreaId);
                device.setStatus("0");
                device.setCreateBy("sys");
                device.setPowerMainEquFlag("Yes");
                device.setAreaId(pid);
                device.setAreaName(areaName);
                device.setDeviceName(deviceName);
                device.setDeviceCode(device.getOldDeviceId() + "_" + RandomUtil.randomNumbers(4));
                this.basedataDeviceService.insertBasedataDevice(device);
            } else {
                ++count2;
                device = basedataDeviceList.get(0);
                device.setDeviceName(deviceName);
                this.basedataDeviceService.updateBasedataDevice(device);
            }

            pid = device.getDeviceId();
            this.saveComponentData(deviceList, device, basedataDeviceList, pid, sendCode);
        }

        System.out.println("shuliang=" + count);
        System.out.println("shuliang1=" + count1);
        System.out.println("shuliang2=" + count2);
    }

    private void saveAreaData(Map<String, List<String>> areaMap, String sendCode) {
        BaseDataArea baseAarea = new BaseDataArea();
        baseAarea.setAreaCode(sendCode);
        List<BaseDataArea> baseAreaList = this.baseDataAreaService.selectAreaList(baseAarea);
        long areaPid = 1L;
        if (CollectionUtils.isEmpty(baseAreaList)) {
            baseAarea.setParentId(areaPid);
            baseAarea.setAreaName(sendCode);
            baseAarea.setAreaType("station_in");
            baseAarea.setStatus("0");
            baseAarea.setCreateBy("sys");
            baseAarea.setAncestors(",1");
            this.baseDataAreaService.insertArea(baseAarea);
            areaPid = baseAarea.getAreaId();
        } else {
            BaseDataArea baseArea = baseAreaList.get(0);
            areaPid = baseArea.getAreaId();
        }

        for (String areaKey : areaMap.keySet()) {
            List bayList = areaMap.get(areaKey);
            BaseDataArea area = new BaseDataArea();
            String areaId = areaKey.split(StringUtils.COLON)[0];
            String areaName = areaKey.split(StringUtils.COLON)[1];
            area.setOldAreaId(sendCode + "_" + areaId);
            List<BaseDataArea> baseDataAreaList = this.baseDataAreaService.selectAreaList(area);
            if (CollectionUtils.isEmpty(baseDataAreaList)) {
                area.setParentId(areaPid);
                area.setAreaName(areaName);
                area.setAreaType("station_in");
                area.setStatus("0");
                area.setCreateBy("sys");
                area.setAncestors("," + areaPid);
                this.baseDataAreaService.insertArea(area);
            } else {
                area = baseDataAreaList.get(0);
                area.setAreaName(areaName);
                this.baseDataAreaService.updateArea(area);
            }

            Long pid = area.getAreaId();
            this.redisTemplate.opsForValue().set(areaId, pid);
            this.saveBayData(bayList, area, baseDataAreaList, pid, sendCode);
        }

    }

    private void saveBayData(List<String> bayList, BaseDataArea area, List<BaseDataArea> baseDataAreaList, Long pid, String sendCode) {
        if (CollectionUtils.isNotEmpty(bayList) && pid != null) {
            String oldPid = area.getOldAreaId();
            bayList.forEach((bay) -> {
                String bayId = bay.split(StringUtils.COLON)[0];
                String bayName = bay.split(StringUtils.COLON)[1];
                BaseDataArea bayData = new BaseDataArea();
                bayData.setOldAreaId(sendCode + "_" + bayId);
                List<BaseDataArea> baseDataBayList = this.baseDataAreaService.selectAreaList(bayData);
                if (CollectionUtils.isEmpty(baseDataBayList)) {
                    bayData.setAreaName(bayName);
                    bayData.setAreaType("bayunit");
                    bayData.setStatus("0");
                    bayData.setCreateBy("sys");
                    bayData.setAncestors(",1," + pid);
                    bayData.setParentId(pid);
                    bayData.setOldParentId(sendCode + "_" + oldPid);
                    this.baseDataAreaService.insertArea(bayData);
                } else {
                    if (baseDataAreaList.size() > 0) {
                        bayData = baseDataAreaList.get(0);
                        bayData.setAreaName(bayName);
                        this.baseDataAreaService.updateArea(bayData);
                    }
                }

                Long areaId = bayData.getAreaId();
                this.redisTemplate.opsForValue().set(bayId, areaId);
            });
        }

    }

    private void saveComponentData(List<String> componentList, BasedataDevice device, List<BasedataDevice> basedataDeviceList, Long pid, String sendCode) {
        if (CollectionUtils.isNotEmpty(componentList) && pid != null) {
            String oldPid = device.getOldAreaId();
            componentList.stream().forEach((bay) -> {
                String componentId = bay.split(StringUtils.COLON)[0];
                String componentName = bay.split(StringUtils.COLON)[1];
                BasedataDevice componentData = new BasedataDevice();
                componentData.setOldDeviceId(sendCode + "_component_" + componentId);
                List<BasedataDevice> baseDataComponentList = this.basedataDeviceService.selectBasedataDeviceList(componentData);
                if (CollectionUtils.isEmpty(baseDataComponentList)) {
                    componentData.setParentId(pid);
                    componentData.setOldAreaName(device.getOldAreaName());
                    componentData.setOldAreaId(sendCode + "_" + device.getOldAreaId());
                    componentData.setStatus("0");
                    componentData.setCreateBy("sys");
                    componentData.setPowerMainEquFlag("No");
                    componentData.setAreaId(device.getAreaId());
                    componentData.setAreaName(device.getAreaName());
                    componentData.setDeviceName(componentName);
                    componentData.setDeviceCode(componentData.getOldDeviceId() + "_" + RandomUtil.randomNumbers(4));
                    this.basedataDeviceService.insertBasedataDevice(componentData);
                } else {
                    componentData = baseDataComponentList.get(0);
                    componentData.setDeviceName(componentName);
                    this.basedataDeviceService.updateBasedataDevice(componentData);
                }

            });
        }

    }
}
