package com.pqs9900.serviceImpl.configuration;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.njcn.enums.DicDataEnum;
import com.njcn.enums.DicDataTypeEnum;
import com.njcn.enums.LogTypeEnum;
import com.njcn.enums.TerminalLogsEnum;
import com.njcn.mapper.configuration.*;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.configuration.*;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.utils.*;
import com.njcn.utils.SM.SM4Utils;
import com.njcn.utils.redis.JedisManager;
import com.pqs9900.controller.business.DeviceController;
import com.pqs9900.util.TerminalUtil;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.util.StringUtil;
import com.njcn.mapper.data.MapMapper;
import com.njcn.mapper.user.DeptsGdMapper;
import com.njcn.mapper.user.DeptsLineMapper;
import com.njcn.mapper.user.DeptsMapper;
import com.njcn.mapper.user.TransFormerMapper;
import com.njcn.pojo.commons.AddResult;
import com.njcn.pojo.commons.device.DeviceInfo;
import com.njcn.pojo.commons.device.LineDetailInfo;
import com.njcn.pojo.commons.device.LineInfo;
import com.njcn.pojo.commons.device.SubInfo;
import com.njcn.pojo.data.ComInformation;
import com.njcn.pojo.data.Maps;
import com.njcn.pojo.data.OfflLog;
import com.njcn.pojo.user.Depts;
import com.njcn.pojo.user.DeptsGd;
import com.njcn.pojo.user.DeptsLine;
import com.njcn.pojo.user.TransFormer;
import com.njcn.shiro.token.TokenManager;
import com.njcn.sso.pojo.user.User;
import com.njcn.utils.redis.RedisCacheUtil;
import com.pqs9900.mapper.HisData.ManaDeviceMapper;
import com.pqs9900.pojo.DataInfo.TranslateState;
import com.pqs9900.service.configuration.ManaDeviceService;
import com.pqs9900.util.TranslateThread.data;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import tk.mybatis.mapper.entity.Example;

@Service
public class ManaDeviceServiceImpl implements ManaDeviceService {
    @Autowired
    private AppConfig appConfig;


    @Autowired
    private RedisCacheUtil redisCacheUtil;


    @Autowired
    private LineMapper lineMapper;

    @Autowired
    private LineDetailMapper lineDetailMapper;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private ProvinceMapper provinceMapper;

    @Resource
    private GDInforMapper gdInforMapper;

    @Resource
    private DeptsLineMapper deptslineMapper;

    @Resource
    private SubStationMapper subStationMapper;

    @Resource
    private SubVoltageMapper subVoltageMapper;

    @Resource
    private MapMapper mapMapper;

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private DeviceDetailInfoMapper deviceDetailInfoMapper;

    @Autowired
    private ComInformationMapper comInformationMapper;

    @Resource
    private DicDataMapper dicDataMapper;

    @Resource
    private DicDataTypeMapper dicDataTypeMapper;

    @Resource
    private NodeInformationMapper nodeInformationMapper;

    @Resource
    private TransFormerMapper transFormerMapper;

    @Autowired
    private DeptsMapper deptsMapper;

    @Autowired
    private OverLimitMapper overLimitMapper;

    @Autowired
    private PushInfoMapper pushInfoMapper;

    @Autowired
    private ManaDeviceMapper manaDeviceMapper;

    @Autowired
    private DevFunctionMapper devFunctionMapper;

    @Resource
    private JedisManager jedisManager;

    @Resource
    private UserLogDetailService userLogDetailService;

    @Resource
    private TerminalLogsMapper terminalLogsMapper;

    @Resource
    private MonitorMapper monitorMapper;


    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(DeviceController.class);

    // 新增项目
    public AddResult saveProjectInfo(String projectName) {
        AddResult result = new AddResult();
        List<Project> projInfo = new ArrayList<>();
        Project tmp = new Project();
        tmp.setName(projectName);
        projInfo = projectMapper.checkName(projectName);
        if (projInfo.size() > 0) {
            result.setMessage("添加失败a");
            result.setIndex(projInfo.get(0).getProjectIndex());
            return result;
        } else {
            Long index = projectMapper.selectMaxIndex();

            if (index == null) {
                index = (long) 1;
            } else {
                index++;
            }

            tmp.setProjectIndex(index);
            try {
                int flag = projectMapper.insert(tmp);
                redisCacheUtil.clearConData();
                result.setMessage("添加成功");
                result.setIndex(index);
                return result;
            } catch (Exception e) {
                result.setMessage("添加失败");
                return result;
            }
        }
    }

    public Project loadProj(Long projIndex) {
        Project proj = new Project();
        proj = projectMapper.selectByPrimaryKey(projIndex);

        return proj;
    }

    public String updateProj(Long projIndex, String name) {
        Project tmp = new Project();

        List<Project> pro = projectMapper.testName(name, projIndex);
        if (pro.size() > 0) {
            return "更新失败a";
        } else {
            tmp = projectMapper.selectByPrimaryKey(projIndex);
            tmp.setName(name);

            try {
                int flag = projectMapper.updateByPrimaryKey(tmp);
                redisCacheUtil.clearConData();
                return "更新成功";
            } catch (Exception e) {
                return "更新失败";
            }
        }
    }

    public String delProj(Long projIndex) {
        Example example = new Example(Province.class);
        example.createCriteria().andEqualTo("projectIndex", projIndex);
        List<Province> pro = provinceMapper.selectByExample(example);

        if (pro.size() > 0) {
            return "删除失败a";
        } else {
            try {
                int flag = projectMapper.deleteByPrimaryKey(projIndex);
                redisCacheUtil.clearConData();

                return "删除成功";
            } catch (Exception e) {
                return "删除失败b";
            }
        }
    }

    // 新增省份
    public AddResult saveProInfo(String proName, Long projectIndex) {
        AddResult result = new AddResult();
        List<Province> proInfo = new ArrayList<>();
        Province tmp = new Province();
        DicData dic = dicDataMapper.queryProIdByname(proName);
        tmp.setName(dic.getDicIndex());
        proInfo = provinceMapper.checkName(dic.getDicIndex(), projectIndex);
        if (proInfo.size() > 0) {
            result.setMessage("添加失败a");
            result.setIndex(proInfo.get(0).getProvinceIndex());
            return result;
        } else {
            Long index = provinceMapper.selectMaxIndex();

            if (index == null) {
                index = (long) 1;
            } else {
                index++;
            }

            tmp.setProvinceIndex(index);
            tmp.setProjectIndex(projectIndex);
            try {
                int flag = provinceMapper.insert(tmp);
                redisCacheUtil.clearConData();
                result.setMessage("添加成功");
                result.setIndex(index);
                return result;
            } catch (Exception e) {
                result.setMessage("添加失败");
                return result;
            }
        }
    }

    public Province loadPro(Long proIndex) {
        Province pro = new Province();
        pro = provinceMapper.selectByPrimaryKey(proIndex);

        return pro;
    }

    public String updatePro(Long proIndex, String name) {
        Province tmp = new Province();

        List<Province> pro = provinceMapper.testName(name, proIndex);
        if (pro.size() > 0) {
            return "更新失败a";
        } else {
            tmp = provinceMapper.selectByPrimaryKey(proIndex);
            tmp.setName(name);

            try {
                int flag = provinceMapper.updateByPrimaryKey(tmp);
                redisCacheUtil.clearConData();
                return "更新成功";
            } catch (Exception e) {
                return "更新失败";
            }
        }
    }

    public String delPro(Long proIndex) {
        Example example = new Example(GDInformation.class);
        example.createCriteria().andEqualTo("provinceIndex", proIndex);
        List<GDInformation> gd = gdInforMapper.selectByExample(example);

        if (gd.size() > 0) {
            return "删除失败a";
        } else {
            try {
                int flag = provinceMapper.deleteByPrimaryKey(proIndex);
                redisCacheUtil.clearConData();

                return "删除成功";
            } catch (Exception e) {
                return "删除失败";
            }
        }
    }

    // 新增供电公司
    public AddResult saveGdInfo(String gdName, Long proIndex) {
        AddResult result = new AddResult();
        List<GDInformation> gdInfo = new ArrayList<>();
        gdInfo = gdInforMapper.testName(gdName, proIndex);
        if (gdInfo.size() > 0) {
            result.setMessage("添加失败a");
            result.setIndex(gdInfo.get(0).getGdIndex());
            return result;
        } else {
            Long index = gdInforMapper.selectMaxIndex();

            if (index == null) {
                index = (long) 1;
            } else {
                index++;
            }

            GDInformation temp = new GDInformation();
            temp.setGdIndex(index);
            temp.setName(gdName);
            temp.setProvinceIndex(proIndex);

//            DeptsGd dpt = new DeptsGd();
//            dpt.setDeptsIndex(dept);
//            dpt.setGDIndex(index);
            try {
                int flag = gdInforMapper.insert(temp);
//                int flag2 = deptsGdMapper.insert(dpt);
                redisCacheUtil.clearConData();
                result.setMessage("添加成功");
                result.setIndex(index);
                return result;
            } catch (Exception e) {
                result.setMessage("添加失败");
                return result;
            }
        }
    }

    // 新增变电站
    public AddResult saveSubInfo(String subName, String gdIndex, Float longitude, Float latitude, String scale) {
        AddResult result = new AddResult();
        List<SubStation> subInfo = new ArrayList<>();
        SubStation temp = new SubStation();
        Maps map = new Maps();

        temp.setName(subName);
        temp.setGdIndex(Long.valueOf(gdIndex));

        subInfo = subStationMapper.select(temp);
        if (subInfo.size() > 0) {
            result.setMessage("添加失败a");
            result.setIndex(subInfo.get(0).getSubIndex());
            return result;
        } else {
            temp.setGdIndex(Long.valueOf(gdIndex));

            Long subIndex = subStationMapper.selectMaxIndex();

            if (subIndex == null) {
                subIndex = (long) 1;
            } else {
                subIndex++;
            }

            temp.setSubIndex(subIndex);
            temp.setScale(scale);

            map.setMapIndex(UUID.randomUUID().toString());
            map.setGdIndex(Long.valueOf(gdIndex));
            map.setSubIndex(Long.valueOf(subIndex));
            map.setLatItude(latitude);
            map.setLongItude(longitude);

            User user = TokenManager.getToken();
            map.setState(Long.valueOf("1"));
            map.setUserIndex(user.getUserIndex());
            map.setUpdateTime(new Date());

            try {
                int flag = subStationMapper.insert(temp);
                int flag1 = mapMapper.insert(map);
                redisCacheUtil.clearConData();

                // Long kind =(long) 1;
                // String tableName = String.format("%5d", subIndex).replace("
                // ", "0");
                // TestProcedures.creatTable(tableName, kind);

                result.setMessage("添加成功");
                result.setIndex(subIndex);
                return result;
            } catch (Exception e) {
                result.setMessage("添加失败");
                return result;
            }
        }
    }

    /**
     * 保存终端信息
     */
    @Transactional(rollbackFor = Exception.class)
    public AddResult saveDevInfo(DeviceInfo dev) throws Exception {
        AddResult result = new AddResult();
        List<Device> device = new ArrayList<>();
        Device tmp = new Device();

        tmp.setName(dev.getName());
        tmp.setSubIndex(dev.getSubIndex());
        device = deviceMapper.select(tmp);
        if (device.size() > 0) {
            result.setMessage("添加失败a");
            result.setIndex(device.get(0).getDevIndex());
            return result;
        } else {
            Long devIndex = deviceMapper.selectMaxIndex();

            if (devIndex == null) {
                devIndex = (long) 1;
            } else {
                devIndex++;
            }

            tmp.setGdIndex(dev.getGdIndex());
            tmp.setSubIndex(dev.getSubIndex());
            tmp.setDevIndex(devIndex);

            List<Device> ips = deviceMapper.testIP(dev.getIp(), dev.getPortId(), tmp.getGdIndex(), devIndex);
            if (ips.size() > 0) {
                result.setMessage("添加失败b");
                return result;
            }

            if (dev.getDevType() != null) {
                tmp.setDevType(dev.getDevType());
            } else {
                List<DicData> devtypes = this.getdicdata("装置类型");
                tmp.setDevType(devtypes.get(0).getDicIndex());
            }

            if (dev.getIp() != null) {
                tmp.setIp(dev.getIp());
            } else {
                String ip = appConfig.getzOOKEEPER();
                ip = ip.substring(0, ip.lastIndexOf(":"));
                tmp.setIp(ip);
            }

            tmp.setStatus(0);

            tmp.setLogonTime(new Date());
            tmp.setUpdateTime(new Date());
            tmp.setCallFlag(0);

            int cd = appConfig.getCdkeyEncy();
            if (StrUtil.isNotBlank(dev.getSeries())) {
                String series = TerminalUtil.encodeString(cd, dev.getSeries());
                tmp.setSeries(series);
            } else {
                tmp.setSeries("");
            }
            if (StrUtil.isNotBlank(dev.getKey())) {
                String key = TerminalUtil.encodeString(cd, dev.getKey());
                tmp.setKey(key);
            } else {
                tmp.setKey("");
            }
            List<NodeInformation> nodes = this.getNodeInfo();

            if (nodes.size() == 0) {
                result.setMessage("无服务器信息");
                return result;
            }

            NodeInformation tmpNode = new NodeInformation();
            if (dev.getNodeIndex() != null) {
                tmp.setNodeIndex(dev.getNodeIndex());
                tmpNode = nodeInformationMapper.selectByPrimaryKey(dev.getNodeIndex());
            } else {
                tmpNode = nodes.get(0);
                tmp.setNodeIndex(tmpNode.getNodeIndex());
            }

            tmp.setDevFlag(0);

            if (dev.getPortId() != null) {
                tmp.setPortId(dev.getPortId());
            } else {
                tmp.setPortId(Long.valueOf("102"));
            }

            if (dev.getDevmodel() != null) {
                tmp.setDevmodel(dev.getDevmodel());
            } else {
                tmp.setDevmodel(Long.valueOf("1"));
            }

            String systype = TokenManager.getSysType();
            String systypezt = appConfig.getSysTypeZt();
            String systypewt = appConfig.getSysTypeWt();
            if (systype.equals(systypezt)) {
                tmp.setDatatype(Long.valueOf("0"));
            } else {
                tmp.setDatatype(Long.valueOf("2"));
            }

            DeviceDetailInfo detail = new DeviceDetailInfo();
            detail.setDevIndex(devIndex);
            detail.setDevNo(dev.getDevNo());
            detail.setDevLocation(dev.getDevLocation());
            detail.setSim(dev.getSim());

            if (dev.getManufacturer() != null) {
                detail.setManufacturer(dev.getManufacturer());
            } else {
                List<DicData> manufacturer = this.getdicdata("制造厂商");
                detail.setManufacturer(manufacturer.get(0).getDicIndex());
            }
            detail.setCheckFlag(Long.valueOf("0"));

            detail.setThisTimeCheck(new Date());
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.YEAR, 1);
            detail.setNextTimeCheck(cal.getTime());
            detail.setOntime(1); //对时默认开启

            List<DicData> func = this.getdicdata("装置功能");
            if (CollectionUtil.isEmpty(func)) {
                result.setMessage("装置功能字典不可为空");
                return result;
            }
            List<DevFunction> devfunc = new ArrayList<>();
            for (int y = 0; y < func.size(); y++) {
                DevFunction devf = new DevFunction();
                devf.setFucIndex(UUID.randomUUID().toString());
                devf.setDevIndex(devIndex);
                devf.setFucname(func.get(y).getDicIndex());
                devfunc.add(devf);
            }

            PushInfo pushInfo = new PushInfo();
            pushInfo.setPiIndex(UUID.randomUUID().toString());
            pushInfo.setNodeName(tmpNode.getNodeName());
            pushInfo.setNodeIP(tmpNode.getNodeIP());
            pushInfo.setPushType(0L);
            pushInfo.setActType(0L);
            pushInfo.setMyIndex(devIndex);
            pushInfo.setMyName(dev.getName());
            pushInfo.setState(1L);
            pushInfo.setUpdateTime(new Date());


            deviceMapper.insert(tmp);
            deviceDetailInfoMapper.insert(detail);
            pushInfoMapper.insert(pushInfo);
            devFunctionMapper.insertData(devfunc);
            redisCacheUtil.clearConData();

            result.setMessage("添加成功");
            result.setIndex(devIndex);
            return result;

        }
    }

    /**
     * 更新终端信息
     */
    public String updateDeviceInfo(DeviceInfo device, List<String> funcindexs) {
        String name = device.getName();
        Long devIndex = device.getDevIndex();
        Long suvIndex = device.getSubIndex();

        List<Device> dev = deviceMapper.testName(name, suvIndex, devIndex);
        if (dev.size() > 0) {
            return "修改失败a";
        } else {
            Device tmp = deviceMapper.selectByPrimaryKey(device.getDevIndex());
            DeviceDetailInfo detail = deviceDetailInfoMapper.selectByPrimaryKey(device.getDevIndex());
            NodeInformation tmpNode = new NodeInformation();

            Long nodeId = tmp.getNodeIndex(); //原前置id

            if (device.getDevType() != null) {
                tmp.setDevType(device.getDevType());
            }
            if (device.getLogonTime() != null) {
                tmp.setLogonTime(device.getLogonTime());
            }
            if (device.getName() != null) {
                tmp.setName(device.getName());
            }
            if (device.getNodeIndex() != null) {
                tmp.setNodeIndex(device.getNodeIndex());
                tmpNode.setNodeIndex(device.getNodeIndex());
            } else {
                tmpNode.setNodeIndex(tmp.getNodeIndex());
            }

            DicData devtype = dicDataMapper.selectId(tmp.getDevType());
            if (devtype.getDicName().indexOf("_CLD") < 0 && device.getMac() != null) {
                String ip = device.getMac();
                List<Device> ips = deviceMapper.testIP(ip, device.getPortId(), tmp.getGdIndex(), devIndex);
                if (ips.size() > 0) {
                    return "修改失败b";
                }
                tmp.setIp(ip);
            } else {
                if (device.getMac() != null) {
                    List<Device> macs = deviceMapper.testIP(device.getMac(), device.getPortId(), tmp.getGdIndex(), devIndex);
                    if (macs.size() > 0) {
                        return "修改失败b";
                    }
                    tmp.setIp(device.getMac());
                }

                List<DevFunction> devfunction = new ArrayList<>();
                if (funcindexs != null && funcindexs.size() > 0) {
                    for (int y = 0; y < funcindexs.size(); y++) {
                        DevFunction func = new DevFunction();
                        func.setFucIndex(UUID.randomUUID().toString());
                        func.setDevIndex(devIndex);
                        func.setFucname(funcindexs.get(y));
                        devfunction.add(func);
                    }
                    int flag3 = devFunctionMapper.deleteByIndex(devIndex);
                    int flag4 = devFunctionMapper.insertData(devfunction);
                }
            }
            if (device.getPortId() != null) {
                tmp.setPortId(device.getPortId());
            }
            if (device.getDevmodel() != null) {
                tmp.setDevmodel(device.getDevmodel());
            }
            if (device.getDatatype() != null) {
                tmp.setDatatype(device.getDatatype());
            }
            if (device.getCallFlag() != null) {
                tmp.setCallFlag(device.getCallFlag());
            }
            //根据配置文件使用不同加密文件
            int cd = appConfig.getCdkeyEncy();
            if (device.getSeries() != null) {
                if (device.getSeries() == tmp.getSeries()) {
                    tmp.setSeries(device.getSeries());
                } else {
                    String series = TerminalUtil.encodeString(cd, device.getSeries());
                    tmp.setSeries(series);
                }
            }
            if (device.getKey() != null) {
                if (device.getKey() == tmp.getKey()) {
                    tmp.setKey(device.getKey());
                } else {
                    String key = TerminalUtil.encodeString(cd, device.getKey());
                    tmp.setKey(key);
                }
            }

            if (device.getManufacturer() != null) {
                detail.setManufacturer(device.getManufacturer());
            }
            if (device.getNextTimeCheck() != null) {
                detail.setNextTimeCheck(device.getNextTimeCheck());
            }
            if (device.getElectroplate() != null) {
                detail.setElectroplate(device.getElectroplate());
            }
            if (device.getOntime() != null) {
                detail.setOntime(device.getOntime());
            }
            if (device.getContract() != null) {
                detail.setContract(device.getContract());
            }
            if (device.getDevCatena() != null) {
                detail.setDevCatnea(device.getDevCatena());
            }
            if (device.getSim() != null) {
                detail.setSim(device.getSim());
            }

            if (StrUtil.isNotBlank(device.getDevLocation())) {
                detail.setDevLocation(device.getDevLocation());
            }
            if (StrUtil.isNotBlank(device.getDevNo())) {
                detail.setDevNo(device.getDevNo());
            }
            detail.setIsAlarm(device.getIsAlarm());

            tmpNode = nodeInformationMapper.selectByPrimaryKey(tmpNode.getNodeIndex());
            if (tmpNode != null) {
                PushInfo pushInfo = new PushInfo();
                pushInfo.setPiIndex(UUID.randomUUID().toString());
                pushInfo.setNodeName(tmpNode.getNodeName());
                pushInfo.setNodeIP(tmpNode.getNodeIP());
                pushInfo.setPushType(0L);
                pushInfo.setActType(1L);
                pushInfo.setMyIndex(devIndex);
                pushInfo.setMyName(tmp.getName());
                pushInfo.setState(1L);
                pushInfo.setUpdateTime(new Date());
                int flag2 = pushInfoMapper.insert(pushInfo);
            }

            NodeInformation tmpNodehis = nodeInformationMapper.selectByPrimaryKey(nodeId);
            if (tmpNodehis != null) {
                PushInfo pushInfo = new PushInfo();
                pushInfo.setPiIndex(UUID.randomUUID().toString());
                pushInfo.setNodeName(tmpNodehis.getNodeName());
                pushInfo.setNodeIP(tmpNodehis.getNodeIP());
                pushInfo.setPushType(0L);
                pushInfo.setActType(1L);
                pushInfo.setMyIndex(devIndex);
                pushInfo.setMyName(tmp.getName());
                pushInfo.setState(1L);
                pushInfo.setUpdateTime(new Date());
                pushInfoMapper.insert(pushInfo);
            }


            int flag = deviceMapper.updateByPrimaryKey(tmp);
            int flag1 = deviceDetailInfoMapper.updateByPrimaryKey(detail);
            redisCacheUtil.clearConData();
            return "修改成功";
        }

    }

    public String delDeviceInfo(Long devIndex) {
        Device devtmp = deviceMapper.selectByPrimaryKey(devIndex);
        NodeInformation tmpNode = new NodeInformation();

        SubVoltage tmp = new SubVoltage();
        tmp.setDevIndex(devIndex);

        List<SubVoltage> subVoltage = subVoltageMapper.select(tmp);

        tmpNode = nodeInformationMapper.selectByPrimaryKey(devtmp.getNodeIndex());
        if (tmpNode != null) {
            PushInfo pushInfo = new PushInfo();
            pushInfo.setPiIndex(UUID.randomUUID().toString());
            pushInfo.setNodeName(tmpNode.getNodeName());
            pushInfo.setNodeIP(tmpNode.getNodeIP());
            pushInfo.setPushType(0l);
            pushInfo.setActType(2l);
            pushInfo.setMyIndex(devIndex);
            pushInfo.setMyName(devtmp.getName());
            pushInfo.setState(1l);
            pushInfo.setUpdateTime(new Date());
            pushInfoMapper.insert(pushInfo);
        }

        if (subVoltage.size() > 0) {
            return "删除失败a";
        } else {
            DeviceDetailInfo detail = new DeviceDetailInfo();
            try {
                int flag = deviceMapper.deleteByPrimaryKey(devIndex);
                int flag1 = deviceDetailInfoMapper.deleteByPrimaryKey(devIndex);
                int flag3 = devFunctionMapper.deleteByIndex(devIndex);
                redisCacheUtil.clearConData();

                // Long kind =(long) 2;
                // String tableName = String.format("%5d", devIndex).replace("
                // ", "0");
                // TestProcedures.delTable(tableName, kind);

                return "删除成功";
            } catch (Exception e) {
                return "删除失败";
            }
        }
    }

    /**
     * 保存母线信息
     */

    public AddResult saveSubvInfo(String subvName, String gdIndex, String subIndex, String devIndex, int subvnum,
                                  String scale, Long subvModel) {
        AddResult result = new AddResult();

        Long subvIndex = subVoltageMapper.selectMaxSubvIndex();

        if (subvIndex == null) {
            subvIndex = (long) 1;
        } else {
            subvIndex++;
        }

        List<SubVoltage> subv = subVoltageMapper.testName(subvName, Long.valueOf(devIndex), subvIndex);
        if (subv.size() > 0) {
            result.setMessage("添加失败，母线已存在");
            result.setIndex(subv.get(0).getSubvIndex());
            return result;
        }
        SubVoltage tmp = new SubVoltage();
        tmp.setName(subvName);

        SubVoltage temp = new SubVoltage();
        temp.setGdIndex(Long.valueOf(gdIndex));
        temp.setSubIndex(Long.valueOf(subIndex));
        temp.setDevIndex(Long.valueOf(devIndex));
        temp.setSubvNum(subvnum);
        temp.setName(subvName);
        temp.setScale(scale);
        temp.setSubvModel(subvModel);

        temp.setSubvIndex(subvIndex);

        try {
            int flag = subVoltageMapper.insert(temp);
            redisCacheUtil.clearConData();

            // Long kind =(long) 3;
            // String tableName = String.format("%5d", subvIndex).replace(" ",
            // "0");
            // TestProcedures.creatTable(tableName, kind);

            result.setMessage("添加成功");
            result.setIndex(subvIndex);
            return result;
        } catch (Exception e) {
            result.setMessage("添加失败");
            return result;
        }
    }

    @Override
    public int updateDevice(Integer name, Integer devflag) {
        return deviceMapper.updateDevice(name, devflag);
    }

    /**
     * 根据字典类型查询字典数据
     */
    public List<DicData> getdicdata(String dictypeName) {
        List<DicData> result = new ArrayList<>();

        DicType type = dicDataTypeMapper.querybyname(dictypeName);
        if (Objects.nonNull(type)) {
            String typrid = type.getDicTypeIndex();
            result = dicDataMapper.selAll(typrid);
        }
        return result;
    }

    public DeviceInfo loadDevice(Long devIndex) throws Exception {
        DeviceInfo result = new DeviceInfo();
        Device tmp = new Device();
        DeviceDetailInfo temp = new DeviceDetailInfo();

        tmp = deviceMapper.selectByPrimaryKey(devIndex);
        temp = deviceDetailInfoMapper.selectByPrimaryKey(devIndex);

        result.setDevIndex(tmp.getDevIndex());
        result.setCallFlag(tmp.getCallFlag());
        result.setDevFlag(tmp.getDevFlag());
        result.setGdIndex(tmp.getGdIndex());
        result.setElectroplate(temp.getElectroplate());
        result.setContract(temp.getContract());
        result.setDevNo(temp.getDevNo());
        result.setDevLocation(temp.getDevLocation());


        DicData devtype = dicDataMapper.selectId(tmp.getDevType());
        if(Objects.isNull(devtype)){
            logger.error("字典装作型号缺失！"+tmp.getDevType());
        }

        if (devtype.getDicName().indexOf("_CLD") > 0) {
            result.setIp(tmp.getIp());
            result.setIptype("cld");
        } else if (devtype.getDicName().indexOf("_PQDIF") > 0) {  //预留PQDIF类型
            result.setIp(tmp.getIp());
            result.setIptype("pqdif");
        } else {
            String ip = tmp.getIp();
            result.setIp(ip);
            result.setIptype("mms");
        }

        result.setName(tmp.getName());
        result.setNodeIndex(tmp.getNodeIndex());
        result.setStatus(tmp.getStatus());
        result.setSubIndex(tmp.getSubIndex());
        result.setDevType(tmp.getDevType());
        result.setPortId(tmp.getPortId());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String logonTime = sdf.format(tmp.getLogonTime());
        String updateTime = sdf.format(tmp.getUpdateTime());
        String ThisTimeCheck = sdf.format(temp.getThisTimeCheck());
        String NextTimeCheck = sdf.format(temp.getNextTimeCheck());

        result.setLogTime(logonTime);
        result.setUpdTime(updateTime);
        result.setThisTime(ThisTimeCheck);
        result.setNextTime(NextTimeCheck);

        result.setManufacturer(temp.getManufacturer());

        result.setDatatype(tmp.getDatatype());
        result.setDevmodel(tmp.getDevmodel());

        String series = tmp.getSeries();
        String key = tmp.getKey();
        String seriestmp = "";
        String keytmp = "";
        int cdkey = appConfig.getCdkeyEncy();
        if (series != null) {
            try {
                if (cdkey == 0) {
                    byte[] b = new BASE64Decoder().decodeBuffer(series);
                    seriestmp = new String(b);
                } else if (cdkey == 1) {
                    seriestmp = ThreeDes.decryptThreeDes(series);
                } else if (cdkey == 2) {
                    String secretkey = SM4Utils.globalSecretKey;
                    SM4Utils sm4 = new SM4Utils(secretkey);
                    seriestmp = sm4.decryptData_ECB(series);
                }
            } catch (Exception e) {
                logger.error("终端台账识别码秘钥算法解密失败，请联系管理员排查");
                return null;
            }

        }
        if (key != null) {
            try {
                if (cdkey == 0) {
                    byte[] b = new BASE64Decoder().decodeBuffer(key);
                    keytmp = new String(b);
                } else if (cdkey == 1) {
                    keytmp = ThreeDes.decryptThreeDes(key);
                } else if (cdkey == 2) {
                    String secretkey = SM4Utils.globalSecretKey;
                    SM4Utils sm4 = new SM4Utils(secretkey);
                    keytmp = sm4.decryptData_ECB(key);
                }
            } catch (Exception e) {
                logger.error("终端台账识别码秘钥算法解密失败，请联系管理员排查");
                return null;
            }
        }

        if (seriestmp.length() > 0) {
            result.setSeries(seriestmp.trim());
        } else {
            result.setSeries("");
        }

        if (keytmp.length() > 0) {
            result.setKey(keytmp.trim());
        } else {
            result.setKey("");
        }

        List<DevFunction> devfunction = devFunctionMapper.queryByDevIndex(devIndex);
        result.setDevfunction(devfunction);

        result.setDataplan(temp.getDataplan());
        result.setNewtraffic(temp.getNewtraffic());
        result.setOntime(temp.getOntime());
        result.setDevCatena(temp.getDevCatnea());
        result.setSim(temp.getSim());
        result.setIsAlarm(temp.getIsAlarm());

        return result;
    }

    @Override
    public List<NodeInformation> getNodeInfo() {
        List<NodeInformation> result;

        NodeInformation tmp = new NodeInformation();
        tmp.setNodeStatus(Long.valueOf(1));

        result = nodeInformationMapper.select(tmp);

        return result;
    }

    @Override
    public GDInformation loadGd(Long gdIndex) {
        GDInformation result;
        result = gdInforMapper.selectByPrimaryKey(gdIndex);

        return result;
    }

    public String updateGd(Long proIndex, Long gdIndex, String name) {
        GDInformation tmp = new GDInformation();
        tmp.setName(name);

        List<GDInformation> gd = gdInforMapper.testName(name, gdIndex);
        if (gd.size() > 0) {
            return "更新失败a";
        } else {
            tmp.setGdIndex(gdIndex);
            tmp.setProvinceIndex(proIndex);

            try {
                int flag = gdInforMapper.updateByPrimaryKey(tmp);
                redisCacheUtil.clearConData();
                return "更新成功";
            } catch (Exception e) {
                return "更新失败";
            }
        }
    }

    public String delGd(Long gdIndex, String ip) {
        SubStation subtmp = new SubStation();
        subtmp.setGdIndex(gdIndex);
        Device devtmp = new Device();
        devtmp.setGdIndex(gdIndex);
        SubVoltage subvtmp = new SubVoltage();
        subvtmp.setGdIndex(gdIndex);
        Line linetmp = new Line();
        linetmp.setGdIndex(gdIndex);

        DeptsGd dep = new DeptsGd();
        dep.setGDIndex(gdIndex);

        List<SubStation> sub = subStationMapper.select(subtmp);
        List<Device> dev = deviceMapper.select(devtmp);
        List<SubVoltage> subv = subVoltageMapper.select(subvtmp);
        List<Line> line = lineMapper.select(linetmp);

        if (line.size() > 0) {
            for (int i = 0; i < line.size(); i++) {
                delLine(line.get(i).getLineIndex(), ip);
            }
        }
        if (subv.size() > 0) {
            for (int i = 0; i < subv.size(); i++) {
                delSubv(subv.get(i).getSubvIndex());
            }
        }
        if (dev.size() > 0) {
            for (int i = 0; i < dev.size(); i++) {
                delDeviceInfo(dev.get(i).getDevIndex());
            }
        }
        if (sub.size() > 0) {
            for (int i = 0; i < sub.size(); i++) {
                delSub(sub.get(i).getSubIndex());
            }
        }
        try {
            int flag = gdInforMapper.deleteByPrimaryKey(gdIndex);
//            int flag1 = deptsGdMapper.delete(dep);
            redisCacheUtil.clearConData();
            return "删除成功";
        } catch (Exception e) {
            return "删除失败";
        }

    }

    public SubInfo loadSub(Long subIndex) {
        SubInfo result = new SubInfo();
        result = subStationMapper.getSubDetail(subIndex);

        return result;
    }

    public String updateSub(Long gdIndex, Long subIndex, String name, Float longitude, Float latitude,
                            String mapIndex, String scale) {
        SubStation tmp = new SubStation();
        tmp.setName(name);

        List<SubStation> sub = subStationMapper.testName(name, subIndex,gdIndex);
        if (sub.size() > 0) {
            return "更新失败a";
        } else {
            tmp.setGdIndex(gdIndex);
            tmp.setSubIndex(subIndex);
            tmp.setScale(scale);

            try {
                int flag = subStationMapper.updateByPrimaryKey(tmp);

                Maps map = new Maps();
                if (StringUtil.isEmpty(mapIndex)) {
                    map.setMapIndex(UUID.randomUUID().toString());
                    map.setGdIndex(Long.valueOf(gdIndex));
                    map.setSubIndex(Long.valueOf(subIndex));
                    map.setLatItude(latitude);
                    map.setLongItude(longitude);
                    User user = TokenManager.getToken();
                    map.setState(Long.valueOf("1"));
                    map.setUserIndex(user.getUserIndex());
                    map.setUpdateTime(new Date());

                    Example example = new Example(Maps.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("subIndex", subIndex);

                    mapMapper.deleteByExample(example);
                    mapMapper.insert(map);
                } else {
                    map = mapMapper.selectByPrimaryKey(mapIndex);
                    map.setLatItude(latitude);
                    map.setLongItude(longitude);
                    mapMapper.updateByPrimaryKey(map);
                }

                redisCacheUtil.clearConData();
                return "更新成功";
            } catch (Exception e) {
                return "更新失败";
            }
        }
    }

    public String delSub(Long subIndex) {
        Device tmp = new Device();
        tmp.setSubIndex(subIndex);

        TransFormer tf = new TransFormer();
        tf.setSubIndex(subIndex.intValue());

        List<Device> device = deviceMapper.select(tmp);
        List<TransFormer> trans = transFormerMapper.select(tf);

        Maps map = new Maps();
        map.setSubIndex(subIndex);


        if (device.size() > 0) {
            return "删除失败a";
        } else if (trans.size() > 0) {
            return "删除失败c";
        } else {
            try {
                subStationMapper.deleteByPrimaryKey(subIndex);
                Example example = new Example(Maps.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("subIndex", subIndex);

                mapMapper.deleteByExample(example);
                redisCacheUtil.clearConData();


                return "删除成功";
            } catch (Exception e) {
                return "删除失败";
            }
        }
    }

    public SubVoltage loadSubv(Long subvIndex) {
        SubVoltage result = new SubVoltage();
        result = subVoltageMapper.selectByPrimaryKey(subvIndex);

        return result;
    }

    public String updateSubv(String subvName, Long gdIndex, Long subIndex, Long devIndex, Long subvIndex, int subvnum,
                             String scale, Long subvModel) {
        List<SubVoltage> subv = subVoltageMapper.testName(subvName, devIndex, subvIndex);
        if (subv.size() > 0) {
            return "更新失败a";
        }

        SubVoltage tmp = new SubVoltage();

        tmp.setGdIndex(gdIndex);
        tmp.setSubIndex(subIndex);
        tmp.setDevIndex(devIndex);
        tmp.setSubvIndex(subvIndex);
        tmp.setName(subvName);
        tmp.setScale(scale);
        tmp.setSubvNum(subvnum);
        tmp.setSubvModel(subvModel);

        DicData dicScale = dicDataMapper.selectId(scale);
        if (Objects.isNull(dicScale)) {
            return "更新失败";
        }
        String tmpname = dicScale.getDicName();
        float jzcmp = getJZCmp(tmpname);
        float nScale = Float.parseFloat(tmpname.substring(0, tmpname.length() - 2));

        try {
            subVoltageMapper.updateByPrimaryKey(tmp);
            lineMapper.updateScale(scale, jzcmp, nScale * 1000, subvName, subvIndex);
            List<Line> lineList = lineMapper.getLineListBySubVId(subvIndex);
            if (CollectionUtil.isNotEmpty(lineList)) {
                for (Line line : lineList) {
                    // float[] fLimit = COverlimit.GetOverLimit(tmpname, line.getDlcMp(), line.getJzcMp(), line.getXycMp(), line.getDevcMp());

                    OverLimit overlimit = COverlimitUtil.globalAssemble(nScale, line.getXycMp(), line.getDevcMp(), line.getDlcMp());
                    overlimit.setMyIndex(line.getLineIndex());
                    overLimitMapper.deleteByPrimaryKey(line.getLineIndex());
                    overLimitMapper.insert(overlimit);
                }
            }
            redisCacheUtil.clearConData();
            return "更新成功";
        } catch (Exception e) {
            return "更新失败";
        }

    }

    public String delSubv(Long subvIndex) {
        Line tmp = new Line();
        tmp.setSubvIndex(subvIndex);

        List<Line> line = lineMapper.select(tmp);

        if (line.size() > 0) {
            return "删除失败a";
        } else {
            try {
                int flag = subVoltageMapper.deleteByPrimaryKey(subvIndex);
                redisCacheUtil.clearConData();

                // Long kind =(long) 3;
                // String tableName = String.format("%5d", subvIndex).replace("
                // ", "0");
                // TestProcedures.delTable(tableName, kind);

                return "删除成功";
            } catch (Exception e) {
                return "删除失败";
            }
        }
    }

    // 新增监测点
    public AddResult saveLineInfo(Line tmp, String dept, int lineNum,
                                  String monitorID, String pttype, String loadType, int interval, String objName, Integer statFlag,
                                  String businessType,
                                  Integer powerId,
                                  String powerSubstationName,
                                  Integer isGridPoint

    ) {
        AddResult result = new AddResult();
        Long devIndex = tmp.getDevIndex();
        Long index = devIndex * 10 + lineNum;

        List<Line> linetmp = lineMapper.testName(tmp.getName(), tmp.getSubvIndex(), index);
        if (linetmp.size() > 0) {
            result.setMessage("添加失败，监测点已存在");
            result.setIndex(linetmp.get(0).getLineIndex());
            return result;
        }

        Device dev = deviceMapper.selectByPrimaryKey(devIndex);

        Line line = lineMapper.selectByPrimaryKey(index);

        if (line != null) {
            result.setMessage("添加失败a");
            return result;
        } else {
            tmp.setLineIndex(index);

            SubVoltage subv = new SubVoltage();
            subv = subVoltageMapper.selectByPrimaryKey(tmp.getSubvIndex());
            tmp.setSubvName(subv.getName());

            DicData sca = dicDataMapper.selectByPrimaryKey(subv.getScale());
            String scaTmp = sca.getDicName();
            float nScale = Float.parseFloat(scaTmp.substring(0, scaTmp.length() - 2));

            if (tmp.getCt1() == null) {
                tmp.setCt1((float) 300);
            }
            if (tmp.getCt2() == null) {
                tmp.setCt2((float) 5);
            }
            if (tmp.getPt1() == null) {
                tmp.setPt1((float) nScale * 1000);
            }
            if (tmp.getPt2() == null) {
                tmp.setPt2((float) 100);
            }
            if (tmp.getDevcMp() == null) {
                tmp.setDevcMp((float) 10);
            }
            if (tmp.getXycMp() == null) {
                tmp.setXycMp((float) 10);
            }

            DicData scale = dicDataMapper.selectId(subv.getScale());
            String tmpname = scale.getDicName();

            float jzcmp = getJZCmp(tmpname);
            tmp.setJzcMp(jzcmp);


            if (tmp.getDlcMp() == null) {
                tmp.setDlcMp(tmp.getJzcMp());
            }

            tmp.setSubVNo(0);

            tmp.setScale(subv.getScale());

            LineDetail detailTmp = new LineDetail();
            detailTmp.setGdIndex(tmp.getGdIndex());
            detailTmp.setLineIndex(index);
            detailTmp.setSubIndex(tmp.getSubIndex());
            detailTmp.setLineName(tmp.getName());
            if (PubUtils.isBlank(pttype)) {
                detailTmp.setPtType(0);
            } else if (pttype.equals("星型接线")) {
                detailTmp.setPtType(0);
            } else if (pttype.equals("三角型接线")) {
                detailTmp.setPtType(1);
            } else if (pttype.equals("V型接线")) {
                detailTmp.setPtType(2);
            }
            detailTmp.setLastTime(new Date());
            if (interval == 0 || interval == 1) {
                detailTmp.setTInterval(1);
            } else if (interval == 3) {
                detailTmp.setTInterval(3);
            } else if (interval == 5) {
                detailTmp.setTInterval(5);
            } else {
                detailTmp.setTInterval(10);
            }
            if (monitorID != null) {
                detailTmp.setMonitorId(monitorID);
            }

            if (StringUtils.isEmpty(loadType)) {
                List<DicData> loadTypes = this.getdicdata(DicDataTypeEnum.payloadEnum.getName());
                detailTmp.setLoadType(loadTypes.get(0).getDicIndex());
            } else {
                detailTmp.setLoadType(loadType);
            }
            if(StrUtil.isNotBlank(businessType)){
                detailTmp.setBusinessType(businessType);
                detailTmp.setPowerId(powerId);
            }else {
                List<DicData> businessTypes = this.getdicdata("行业类型");
                detailTmp.setBusinessType(businessTypes.get(0).getDicIndex());
                detailTmp.setPowerId(0);
                detailTmp.setRemark("");
            }
            detailTmp.setPowerSubstationName(powerSubstationName);
            detailTmp.setIsGridPoint(isGridPoint);

            if (StringUtils.isEmpty(objName)) {
                SubStation subStation = subStationMapper.selectByPrimaryKey(tmp.getSubIndex());
                objName = subStation.getName() + "_" + subv.getName() + "_" + tmp.getName();
            }
            detailTmp.setObjName(objName);
            if (Objects.isNull(statFlag)) {
                statFlag = 1;
            }
            detailTmp.setStatFlag(statFlag);


            ComInformation com = new ComInformation();
            com.setUpdateTime(new Date());
            com.setLineIndex(index);
            com.setType(0);
            com.setState(1);
            com.setDescription("新增监测点");
            com.setRemark("");


            float fDLRL = tmp.getDlcMp();
            float fJZRL = tmp.getJzcMp();
            float fXYRL = tmp.getXycMp();
            float fSBRL = tmp.getDevcMp();

            OverLimit overlimit = COverlimitUtil.globalAssemble(nScale, fXYRL, fSBRL, fDLRL);
            overlimit.setMyIndex(index);

            overLimitMapper.deleteByPrimaryKey(index);


            NodeInformation tmpNode = new NodeInformation();

            tmpNode = nodeInformationMapper.selectByPrimaryKey(dev.getNodeIndex());
            if (tmpNode != null) {
                PushInfo pushInfo = new PushInfo();
                pushInfo.setPiIndex(UUID.randomUUID().toString());
                pushInfo.setNodeName(tmpNode.getNodeName());
                pushInfo.setNodeIP(tmpNode.getNodeIP());
                pushInfo.setPushType(1L);
                pushInfo.setActType(0L);
                pushInfo.setMyIndex(index);
                pushInfo.setMyName(tmp.getName());
                pushInfo.setState(1L);
                pushInfo.setUpdateTime(new Date());
                pushInfoMapper.insert(pushInfo);
            }

            DeptsLine dpt = new DeptsLine();
            dpt.setDeptsIndex(dept);
            dpt.setLineIndex(index);
            dpt.setSystype(TokenManager.getSysType());
            try {
                lineMapper.insert(tmp);
                lineDetailMapper.insert(detailTmp);
                comInformationMapper.insert(com);
                overLimitMapper.insert(overlimit);
                deptslineMapper.insert(dpt);
                redisCacheUtil.clearConData();

                result.setMessage("添加成功");
                result.setIndex(index);
                return result;
            } catch (Exception e) {
                logger.error(e.getMessage());
                result.setMessage("添加失败");
                return result;
            }
        }
    }

    public String delLine(Long lineIndex, String ip) {
        Line line = lineMapper.selectByPrimaryKey(lineIndex);
        Device dev = deviceMapper.selectByPrimaryKey(line.getDevIndex());

        NodeInformation tmpNode = new NodeInformation();
        tmpNode = nodeInformationMapper.selectByPrimaryKey(dev.getNodeIndex());

        if (tmpNode != null) {
            PushInfo pushInfo = new PushInfo();
            pushInfo.setPiIndex(UUID.randomUUID().toString());
            pushInfo.setNodeName(tmpNode.getNodeName());
            pushInfo.setNodeIP(tmpNode.getNodeIP());
            pushInfo.setPushType(1l);
            pushInfo.setActType(2l);
            pushInfo.setMyIndex(lineIndex);
            pushInfo.setMyName(line.getName());
            pushInfo.setState(1l);
            pushInfo.setUpdateTime(new Date());
            pushInfoMapper.insert(pushInfo);
        }

        DeptsLine dpt = new DeptsLine();
        dpt.setLineIndex(lineIndex);
        dpt.setSystype(TokenManager.getSysType());

        try {
            int flag = lineMapper.deleteByPrimaryKey(lineIndex);
            int flag1 = lineDetailMapper.deleteByPrimaryKey(lineIndex);
            int flag2 = comInformationMapper.delByIndex(lineIndex);
            int flag3 = overLimitMapper.deleteByPrimaryKey(lineIndex);
            int flag5 = deptslineMapper.delete(dpt);

            redisCacheUtil.clearConData();

            String msg = " ;操作历史 ct变比 : " + line.getCt1() + " : " + line.getCt2() + "pt变比 : " + line.getPt1() + ":" + line.getPt2() + "设备容量 : " + line.getDevcMp() + "短路容量 : " + line.getDlcMp() + "基准容量 : " + line.getJzcMp() + "协议容量 : " + line.getXycMp();
            userLogDetailService.getLogSys("删除监测点", "成功", ip, LogTypeEnum.SYSTEM.toString(), 1, msg);
            return "删除成功";
        } catch (Exception e) {
            logger.error(e.getMessage());
            return "删除失败";
        }
    }

    /**
     * 根据监测点id获取监测点详情
     */
    @Override
    public LineDetailInfo loadLine(Long lineIndex) {
        LineDetailInfo result = new LineDetailInfo();
        Line line = lineMapper.selectByPrimaryKey(lineIndex);
        LineDetail detail = lineDetailMapper.selectByPrimaryKey(lineIndex);
        OverLimit limit = overLimitMapper.selectByPrimaryKey(lineIndex);


        result.setLineIndex(lineIndex);
        result.setGdIndex(line.getGdIndex());
        result.setSubIndex(line.getSubIndex());
        result.setSubvIndex(line.getSubvIndex());
        result.setDevIndex(line.getDevIndex());
        result.setName(line.getName());
        result.setPt1(line.getPt1());
        result.setPt2(line.getPt2());
        result.setCt1(line.getCt1());
        result.setCt2(line.getCt2());
        result.setDevcMp(line.getDevcMp());
        result.setDlcMp(line.getDlcMp());
        result.setJzcMp(line.getJzcMp());
        result.setXycMp(line.getXycMp());
        result.setSubVNo(line.getSubVNo());
        result.setScale(line.getScale());
        result.setSubvName(line.getSubvName());
        result.setPtType(detail.getPtType());
        result.setTinterval(detail.getTInterval());
        result.setLoadType(detail.getLoadType());
        result.setBusinessType(detail.getBusinessType());
        result.setPowerId(detail.getPowerId());
        result.setRemark(detail.getRemark());
        result.setMonitorId(detail.getMonitorId());
        result.setVoltageDev(limit.getVoltageDev());
        result.setUvoltageDev(limit.getUvoltageDev());
        result.setObjName(detail.getObjName());
        result.setStatFlag(detail.getStatFlag());
        //电网侧名称为空时，默认以变电站名称显示
        if (StringUtils.isEmpty(detail.getPowerSubstationName())) {
            SubStation subStation = subStationMapper.selectByPrimaryKey(line.getSubIndex());
            if (Objects.nonNull(subStation)) {
                result.setPowerSubstationName(subStation.getName());
            }
        } else {
            result.setPowerSubstationName(detail.getPowerSubstationName());
        }
        result.setCalssificationGrade(detail.getCalssificationGrade());
        result.setSuperiorsSubstation(detail.getSuperiorsSubstation());
        result.setHangLine(detail.getHangLine());
        result.setOwner(detail.getOwner());
        result.setOwnerDuty(detail.getOwnerDuty());
        result.setOwnerTel(detail.getOwnerTel());
        result.setWiringDiagram(detail.getWiringDiagram());
        result.setIsGridPoint(detail.getIsGridPoint());
        result.setStatus(line.getStatus());
        return result;
    }

    @Override
    public String updateLine(Line line, LineDetail detail, String voltage, String uvoltage, String ip) {
        int all = 0; //记录修改参数标识 大于0时候标识修改了 ct pt 容量标识
        String name = line.getName();
        Long lineIndex = line.getLineIndex();
        Line tmp = lineMapper.selectByPrimaryKey(line.getLineIndex());

        StringBuilder stringHis = new StringBuilder();
        StringBuilder stringNow = new StringBuilder();
        LineInfo lineInfo = lineMapper.getLineObject(lineIndex.intValue());
        if (Objects.nonNull(lineInfo)) {

            if (Objects.nonNull(line.getCt1()) && Objects.nonNull(line.getPt1())) {
                String str = TokenManager.getNickname() + "修改了" + lineInfo.getGdName() + " - " + lineInfo.getSubName() + " - " + lineInfo.getDevName() + " - " + lineInfo.getName() + " - " + "监测点的参数;";
                stringHis.append(str + "操作历史,");
                stringNow.append("修改后参数,");
                if (Math.abs(tmp.getCt1() - line.getCt1()) != 0 || tmp.getCt2() - line.getCt2() != 0) {
                    stringHis.append("ct变比: " + tmp.getCt1() + " : " + tmp.getCt2() + ";");
                    stringNow.append("ct变比: " + line.getCt1() + ":" + line.getCt2() + ";");
                    all++;
                }
                if (Math.abs(tmp.getPt1() - line.getPt1()) != 0 || tmp.getPt2() - line.getPt2() != 0) {
                    stringHis.append("pt变比: " + tmp.getPt1() + " : " + tmp.getPt2() + ";");
                    stringNow.append("pt变比: " + line.getPt1() + ":" + line.getPt2() + ";");
                    all++;
                }

                if (Math.abs(tmp.getDevcMp() - line.getDevcMp()) != 0) {
                    stringHis.append("设备容量: " + tmp.getDevcMp() + ";");
                    stringNow.append("设备容量: " + line.getDevcMp() + ";");
                    all++;
                }
                if (Math.abs(tmp.getDlcMp() - line.getDlcMp()) != 0) {
                    stringHis.append("短路容量: " + tmp.getDlcMp() + ";");
                    stringNow.append("短路容量: " + line.getDlcMp() + ";");
                    all++;
                }

                if (Math.abs(tmp.getXycMp() - line.getXycMp()) != 0) {
                    stringHis.append("协议容量: " + tmp.getXycMp() + ";");
                    stringNow.append("协议容量: " + line.getXycMp() + ";");
                    all++;
                }

            }
        }

        LineDetail temp = lineDetailMapper.selectByPrimaryKey(lineIndex);
        if (tmp == null) {
            return "更新失败";
        }

        List<Line> list = lineMapper.testName(name, tmp.getSubvIndex(), lineIndex);
        if (list.size() > 0) {
            return "更新失败a";
        }

        if (line.getName() != null) {
            tmp.setName(line.getName());
        }
        if (line.getDlcMp() != null) {
            tmp.setDlcMp(line.getDlcMp());
        }
        if (line.getXycMp() != null) {
            tmp.setXycMp(line.getXycMp());
        }
        if (line.getDevcMp() != null) {
            tmp.setDevcMp(line.getDevcMp());
        }
        if (line.getCt1() != null) {
            tmp.setCt1(line.getCt1());
        }
        if (line.getCt2() != null) {
            tmp.setCt2(line.getCt2());
        }
        if (line.getPt1() != null) {
            tmp.setPt1(line.getPt1());
        }
        if (line.getPt2() != null) {
            tmp.setPt2(line.getPt2());
        }

        tmp.setDlcMp(line.getDlcMp());
        tmp.setStatus(line.getStatus());


        SubVoltage subv = new SubVoltage();
        subv = subVoltageMapper.selectByPrimaryKey(tmp.getSubvIndex());

        DicData sca = dicDataMapper.selectByPrimaryKey(subv.getScale());
        String scaTmp = sca.getDicName();
        float nScale = Float.parseFloat(scaTmp.substring(0, scaTmp.length() - 2));


        OverLimit overlimit = COverlimitUtil.globalAssemble(nScale, line.getXycMp(), line.getDevcMp(), line.getDlcMp());
        overlimit.setMyIndex(line.getLineIndex());


        if (StringUtils.isEmpty(voltage)) {
            overlimit.setVoltageDev(overlimit.getVoltageDev());
        } else {
            overlimit.setVoltageDev(Float.parseFloat(voltage));
        }
        if (StringUtils.isEmpty(voltage)) {
            overlimit.setUvoltageDev(overlimit.getUvoltageDev());
        } else {
            overlimit.setUvoltageDev(Float.parseFloat(uvoltage));
        }


        if (detail.getLineName() != null) {
            temp.setLineName(detail.getLineName());
        }
        if (!StringUtils.isEmpty(detail.getPowerSubstationName())) {
            temp.setPowerSubstationName(detail.getPowerSubstationName());
        }
        if (detail.getPtType() != null) {
            temp.setPtType(detail.getPtType());
        }
        if (detail.getTInterval() != null) {
            temp.setTInterval(detail.getTInterval());
        }
        if (detail.getLoadType() != null) {
            temp.setLoadType(detail.getLoadType());
        }
        if (detail.getBusinessType() != null) {
            temp.setBusinessType(detail.getBusinessType());
        }
        if (detail.getPowerId() != null) {
            temp.setPowerId(detail.getPowerId());
        }
        if (detail.getRemark() != null) {
            temp.setRemark(detail.getRemark());
        } else {
            temp.setRemark("");
        }
        if (detail.getMonitorId() != null) {
            temp.setMonitorId(detail.getMonitorId());
        } else if (temp.getMonitorId() == null) {
            temp.setMonitorId("");
        }

        temp.setObjName(detail.getObjName());

        if (detail.getStatFlag() != null) {
            temp.setStatFlag(detail.getStatFlag());
        }


        temp.setLastTime(new Date());
        temp.setCalssificationGrade(detail.getCalssificationGrade());
        temp.setSuperiorsSubstation(detail.getSuperiorsSubstation());
        temp.setHangLine(detail.getHangLine());
        temp.setOwner(detail.getOwner());
        temp.setOwnerDuty(detail.getOwnerDuty());
        temp.setOwnerTel(detail.getOwnerTel());
        temp.setIsGridPoint(detail.getIsGridPoint());

        Device dev = deviceMapper.selectByPrimaryKey(tmp.getDevIndex());
        NodeInformation tmpNode = new NodeInformation();

        tmpNode = nodeInformationMapper.selectByPrimaryKey(dev.getNodeIndex());

        if (tmpNode != null) {
            PushInfo pushInfo = new PushInfo();
            pushInfo.setPiIndex(UUID.randomUUID().toString());
            pushInfo.setNodeName(tmpNode.getNodeName());
            pushInfo.setNodeIP(tmpNode.getNodeIP());
            pushInfo.setPushType(1L);
            pushInfo.setActType(1L);
            pushInfo.setMyIndex(tmp.getLineIndex());
            pushInfo.setMyName(tmp.getName());
            pushInfo.setState(1L);
            pushInfo.setUpdateTime(new Date());
            pushInfoMapper.insert(pushInfo);
        }

        try {
            lineMapper.updateByPrimaryKey(tmp);
            lineDetailMapper.updateByPrimaryKey(temp);
            overLimitMapper.updateByPrimaryKey(overlimit);
            redisCacheUtil.clearConData();

            if (all > 0) {
                TerminalLogs terminalLogs = new TerminalLogs();
                terminalLogs.setLogsIndex(UUID.randomUUID().toString());
                terminalLogs.setObjIndex(lineIndex.toString());
                terminalLogs.setTerminalDescribe(stringHis.toString() + stringNow.toString());
                terminalLogs.setTerminalType(TerminalLogsEnum.lineLogs.getTerminalIndex());
                terminalLogs.setUpdateTime(new Date());
                terminalLogs.setUserIndex(TokenManager.getUserId());
                terminalLogsMapper.insert(terminalLogs);
            }

            return "更新成功";
        } catch (Exception e) {
            return "更新失败";
        }
        // }
    }

    @Override
    public String updateLine(Integer lineId, String lineName) {
        Line line = lineMapper.selectByPrimaryKey(lineId.longValue());
        List<Line> list = lineMapper.testName(lineName, line.getSubvIndex(), lineId.longValue());
        if (list.size() > 0) {
            return "存在同名监测点";
        }

        Line linePO = new Line();
        linePO.setName(lineName);
        linePO.setLineIndex(line.getLineIndex());
        lineMapper.updateByPrimaryKeySelective(linePO);

        return "更新监测点成功";
    }

    public LineInfo loadLineInfo(Long lineIndex) {
        LineInfo lineInfo = new LineInfo();
        Line line = lineMapper.selectByPrimaryKey(lineIndex);

        GDInformation gd = gdInforMapper.selectByPrimaryKey(line.getGdIndex());
        lineInfo.setGdName(gd.getName());

        SubStation sub = subStationMapper.selectByPrimaryKey(line.getSubIndex());
        lineInfo.setSubName(sub.getName());

        Device dev = deviceMapper.selectByPrimaryKey(line.getDevIndex());
        lineInfo.setDevName(dev.getName());

        SubVoltage subv = subVoltageMapper.selectByPrimaryKey(line.getSubvIndex());
        lineInfo.setSubvName(subv.getName());

        lineInfo.setName(line.getName());

        return lineInfo;
    }

    public List<Depts> loadDept(Long proIndex) {
        List<Depts> result = new ArrayList<>();
        result = deptsMapper.getAllDeptByPro(proIndex);

        return result;
    }

   /* private float getfJZRL(String scale) {

        if (scale.equals("6kV") || scale.equals("10kV")) {
            return (float) 100;
        } else if (scale.equals("20kV")) {
            return (float) 200;
        } else if (scale.equals("35kV")) {
            return (float) 250;
        } else if (scale.equals("66kV")) {
            return (float) 500;
        } else if (scale.equals("110kV")) {
            return (float) 750;
        } else if (scale.equals("220kV")) {
            return (float) 2000;
        } else if (scale.equals("330kV")) {
            return (float) 3000;
        } else if (scale.equals("500kV")) {
            return (float) 4500;
        } else if (scale.equals("750kV")) {
            return (float) 7000;
        } else if (scale.equals("1000kV")) {
            return (float) 9000;
        } else {
            return (float) 10;
        }


    }*/

    @Override
    public void insertOFFlog(OfflLog offlLog) {
        manaDeviceMapper.insertOFFlog(offlLog);
    }

    @Override
    public List<data> getDataInfo() {
        return manaDeviceMapper.getDataInfo();
    }

    @Override
    public void updateOFFlog(Date startTime, Date endTime, String year, int state, String name, int id, Date updateTime, int allCount, int realCount, String offlDescribe) {
        String temp = dealStringParam(id + "");
        manaDeviceMapper.updateOFFlog(startTime, endTime, year, state, name, Integer.parseInt(temp), updateTime, allCount, realCount, offlDescribe);
    }


    public int getCount(int id, String filename, Integer state) {
        return manaDeviceMapper.getCount(id, filename, state);
    }

    public List<TranslateState> getTranslateState(Date start, Date end) {
        return manaDeviceMapper.getTranslateState(start, end);
    }

    public void export(OutputStream outputStream) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("导入模板");
        XSSFSheet hideSheet = workbook.createSheet("hiddenSheet");

        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue("批量导入模板（请严格按照模板标准填入数据,带*表示必填）");
        row = sheet.createRow(1);
        int cellId = 0;
        cell = row.createCell(cellId++);
        cell.setCellValue("*项目名称");
        cell = row.createCell(cellId++);
        cell.setCellValue("*省份");
        cell = row.createCell(cellId++);
        cell.setCellValue("*所属公司");
        cell = row.createCell(cellId++);
        cell.setCellValue("*所属部门");
        cell = row.createCell(cellId++);
        cell.setCellValue("*变电站名称");
        cell = row.createCell(cellId++);
        cell.setCellValue("*变电站电压等级");
        cell = row.createCell(cellId++);
        cell.setCellValue("*经度");
        cell = row.createCell(cellId++);
        cell.setCellValue("*纬度");
        cell = row.createCell(cellId++);
        cell.setCellValue("*装置编号");
        cell = row.createCell(cellId++);
        cell.setCellValue("*IP地址");
        cell = row.createCell(cellId++);
        cell.setCellValue("*终端厂家");
        cell = row.createCell(cellId++);
        cell.setCellValue("*终端模型");
        cell = row.createCell(cellId++);
        cell.setCellValue("*终端型号");
        cell = row.createCell(cellId++);
        cell.setCellValue("*所属前置机名称");
        cell = row.createCell(cellId++);
        cell.setCellValue("*端口号");
        cell = row.createCell(cellId++);
        cell.setCellValue("识别码");
        cell = row.createCell(cellId++);
        cell.setCellValue("秘钥");
        cell = row.createCell(cellId++);
        cell.setCellValue("*母线名称");
        cell = row.createCell(cellId++);
        cell.setCellValue("*母线号(1-6)");
        cell = row.createCell(cellId++);
        cell.setCellValue("*电压等级(单位:V)");
        cell = row.createCell(cellId++);
        cell.setCellValue("*监测点名称");
        cell = row.createCell(cellId++);
        cell.setCellValue("*监测点号(1-6,不可重复)");
        cell = row.createCell(cellId++);
        cell.setCellValue("*PT变比");
        cell = row.createCell(cellId++);
        cell.setCellValue("*CT变比");
        cell = row.createCell(cellId++);
        cell.setCellValue("*短路容量");
        cell = row.createCell(cellId++);
        cell.setCellValue("*设备容量");
        cell = row.createCell(cellId++);
        cell.setCellValue("*协议容量");
        cell = row.createCell(cellId++);
        cell.setCellValue("*接线类型");
        cell = row.createCell(cellId++);
        cell.setCellValue("*测量间隔(分钟)");
        cell = row.createCell(cellId++);
        cell.setCellValue("*" + DicDataTypeEnum.payloadEnum.getName());
        cell = row.createCell(cellId++);
        cell.setCellValue("国网ID");
        cell = row.createCell(cellId++);
        cell.setCellValue("监测点对象");
        cell = row.createCell(cellId++);
        cell.setCellValue("是否参与统计");
        cell = row.createCell(cellId++);
        cell.setCellValue("*文件名");

        List<String> l0 = manaDeviceMapper.getProName();
        String[] list0 = new String[l0.size()];
        l0.toArray(list0);
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list0, 2, 1002, 1, 1, "$I$1:$I$", "hidden", 8, 1);

        List<String> l1 = manaDeviceMapper.getDeptsInfo(); //所属部门
        String[] list1 = new String[l1.size()];
        l1.toArray(list1);
        //sheet.addValidationData(setDataValidation(sheet, list1, 2, 1002, 2, 2));
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list1, 2, 1002, 3, 3, "$A$1:$A$", "hidden0", 0, 1);

        List<String> l5 = manaDeviceMapper.getVoltage(); //电压等级
        String[] list5 = new String[l5.size()];
        l5.toArray(list5);
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list5, 2, 1002, 5, 5, "$K$1:$K$", "hidden10", 10, 1);

        List<String> l2 = manaDeviceMapper.getFacs(); //终端厂家
        String[] list2 = new String[l2.size()];
        l2.toArray(list2);
        //sheet.addValidationData(setDataValidation(sheet, list2, 2, 1002, 10, 10));
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list2, 2, 1002, 10, 10, "$B$1:$B$", "hidden1", 1, 1);

        String[] list = {"离线"}; //终端模型
        //sheet.addValidationData(setDataValidation(sheet, list, 2, 1002, 19, 19));
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list, 2, 1002, 11, 11, "$C$1:$C$", "hidden2", 2, 1);

        List<String> l3 = manaDeviceMapper.getTypes();   //终端型号
        String[] list3 = new String[l3.size()];
        l3.toArray(list3);
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list3, 2, 1002, 12, 12, "$D$1:$D$", "hidden3", 3, 1);

        List<String> l4 = manaDeviceMapper.getNodes(); //所属前置机
        String[] list4 = new String[l4.size()];
        l4.toArray(list4);
        //sheet.addValidationData(setDataValidation(sheet, list4, 2, 1002, 21, 21));
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list4, 2, 1002, 13, 13, "$E$1:$E$", "hidden4", 4, 1);

        //sheet.addValidationData(setDataValidation(sheet, list4, 2, 1002, 21, 21));
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list5, 2, 1002, 19, 19, "$F$1:$F$", "hidden5", 5, 1);

        String[] list6 = {"星型接线", "三角型接线", "V型接线"}; //终端模型
        //sheet.addValidationData(setDataValidation(sheet, list, 2, 1002, 19, 19));
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list6, 2, 1002, 27, 27, "$G$1:$G$", "hidden6", 6, 1);

        String[] list7 = {"1", "3", "5", "10"}; //间隔时间
        //sheet.addValidationData(setDataValidation(sheet, list, 2, 1002, 19, 19));
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list7, 2, 1002, 28, 28, "$H$1:$H$", "hidden7", 7, 0);

        List<String> l8 = manaDeviceMapper.getLoadType(); //干扰源类型
        String[] list8 = new String[l8.size()];
        l8.toArray(list8);
        //sheet.addValidationData(setDataValidation(sheet, list4, 2, 1002, 21, 21));
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list8, 2, 1002, 29, 29, "$J$1:$J$", "hidden9", 9, 1);

        String[] list32 = {"参与统计", "不参与统计"}; //统计类型
        XSSFSetDropDownAndHidden(workbook, sheet, hideSheet, list32, 2, 1002, 32, 32, "$G$1:$G$", "hidden32", 10, 1);

        workbook.write(outputStream);
        workbook.close();
    }

    public void downDevPloy(OutputStream outputStream) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("批量导入模板");
        XSSFSheet hideSheet = workbook.createSheet("sheet2");
        XSSFSheet hideSheet1 = workbook.createSheet("sheet3");

        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = row.createCell(0);

        cell.setCellValue("批量导入模板（请严格按照模板标准填入数据,带*表示必填）");
        row = sheet.createRow(1);
        int cellId = 0;
        Font red = workbook.createFont();
        red.setColor(Font.COLOR_RED);

        cell = row.createCell(cellId++);
        XSSFRichTextString c24 = new XSSFRichTextString("*项目名称");
        c24.applyFont(0, 1, red);
        cell.setCellValue(c24);

        cell = row.createCell(cellId++);
        XSSFRichTextString c1 = new XSSFRichTextString("*省份");
        c1.applyFont(0, 1, red);
        cell.setCellValue(c1);

        cell = row.createCell(cellId++);
        XSSFRichTextString c2 = new XSSFRichTextString("*供电公司");
        c2.applyFont(0, 1, red);
        cell.setCellValue(c2);

        cell = row.createCell(cellId++);
        XSSFRichTextString c3 = new XSSFRichTextString("*所属部门");
        c3.applyFont(0, 1, red);
        cell.setCellValue(c3);

        cell = row.createCell(cellId++);
        XSSFRichTextString c4 = new XSSFRichTextString("*变电站");
        c4.applyFont(0, 1, red);
        cell.setCellValue(c4);

        cell = row.createCell(cellId++);
        XSSFRichTextString ca = new XSSFRichTextString("*变电站电压等级");
        ca.applyFont(0, 1, red);
        cell.setCellValue(ca);

        cell = row.createCell(cellId++);
        XSSFRichTextString c5 = new XSSFRichTextString("*经度");
        c5.applyFont(0, 1, red);
        cell.setCellValue(c5);

        cell = row.createCell(cellId++);
        XSSFRichTextString c6 = new XSSFRichTextString("*纬度");
        c6.applyFont(0, 1, red);
        cell.setCellValue(c6);

        cell = row.createCell(cellId++);
        XSSFRichTextString c16 = new XSSFRichTextString("*装置名称");
        c16.applyFont(0, 1, red);
        cell.setCellValue(c16);

        cell = row.createCell(cellId++);
        XSSFRichTextString c12 = new XSSFRichTextString("*IP地址");
        c12.applyFont(0, 1, red);
        cell.setCellValue(c12);

        cell = row.createCell(cellId++);
        XSSFRichTextString c11 = new XSSFRichTextString("*厂家");
        c11.applyFont(0, 1, red);
        cell.setCellValue(c11);

        cell = row.createCell(cellId++);
        XSSFRichTextString c20 = new XSSFRichTextString("*终端模型");
        c20.applyFont(0, 1, red);
        cell.setCellValue(c20);

        cell = row.createCell(cellId++);
        XSSFRichTextString c21 = new XSSFRichTextString("*终端型号");
        c21.applyFont(0, 1, red);
        cell.setCellValue(c21);

        cell = row.createCell(cellId++);
        XSSFRichTextString c22 = new XSSFRichTextString("*所属前置机名称");
        c22.applyFont(0, 1, red);
        cell.setCellValue(c22);

        cell = row.createCell(cellId++);
        XSSFRichTextString c23 = new XSSFRichTextString("*端口号");
        c23.applyFont(0, 1, red);
        cell.setCellValue(c23);

        cell = row.createCell(cellId++);
        XSSFRichTextString d3 = new XSSFRichTextString("SIM卡号");
        cell.setCellValue(d3);

        cell = row.createCell(cellId++);
        XSSFRichTextString d1 = new XSSFRichTextString("监测装置安装位置");
        cell.setCellValue(d1);

        cell = row.createCell(cellId++);
        XSSFRichTextString d2 = new XSSFRichTextString("监测厂家设备编号");
        cell.setCellValue(d2);

        cell = row.createCell(cellId++);
        cell.setCellValue("识别码");

        cell = row.createCell(cellId++);
        cell.setCellValue("秘钥");

        cell = row.createCell(cellId++);
        XSSFRichTextString c7 = new XSSFRichTextString("*母线名称");
        c7.applyFont(0, 1, red);
        cell.setCellValue(c7);

        cell = row.createCell(cellId++);
        XSSFRichTextString c8 = new XSSFRichTextString("*母线号(1-6)");
        c8.applyFont(0, 1, red);
        cell.setCellValue(c8);

        cell = row.createCell(cellId++);
        XSSFRichTextString c15 = new XSSFRichTextString("*电压等级");
        c15.applyFont(0, 1, red);
        cell.setCellValue(c15);

        cell = row.createCell(cellId++);
        XSSFRichTextString c9 = new XSSFRichTextString("*监测点名称");
        c9.applyFont(0, 1, red);
        cell.setCellValue(c9);

        cell = row.createCell(cellId++);
        XSSFRichTextString c10 = new XSSFRichTextString("*监测点号(1-6,不可重复)");
        c10.applyFont(0, 1, red);
        cell.setCellValue(c10);

        cell = row.createCell(cellId++);
        XSSFRichTextString c13 = new XSSFRichTextString("*PT变比");
        c13.applyFont(0, 1, red);
        cell.setCellValue(c13);

        cell = row.createCell(cellId++);
        XSSFRichTextString c14 = new XSSFRichTextString("*CT变比");
        c14.applyFont(0, 1, red);
        cell.setCellValue(c14);

        cell = row.createCell(cellId++);
        XSSFRichTextString c17 = new XSSFRichTextString("*短路容量(默认值10)");
        c17.applyFont(0, 1, red);
        cell.setCellValue(c17);

        cell = row.createCell(cellId++);
        XSSFRichTextString c18 = new XSSFRichTextString("*设备容量(默认值10)");
        c18.applyFont(0, 1, red);
        cell.setCellValue(c18);

        cell = row.createCell(cellId++);
        XSSFRichTextString c19 = new XSSFRichTextString("*协议容量(默认值10)");
        c19.applyFont(0, 1, red);
        cell.setCellValue(c19);

        cell = row.createCell(cellId++);
        XSSFRichTextString c25 = new XSSFRichTextString("*接线类型");
        c25.applyFont(0, 1, red);
        cell.setCellValue(c25);

        cell = row.createCell(cellId++);
        XSSFRichTextString c26 = new XSSFRichTextString("*测量间隔(分钟)");
        c26.applyFont(0, 1, red);
        cell.setCellValue(c26);

        cell = row.createCell(cellId++);
        XSSFRichTextString c28 = new XSSFRichTextString("*干扰源类型");
        c28.applyFont(0, 1, red);
        cell.setCellValue(c28);




        cell = row.createCell(cellId++);
        XSSFRichTextString d4 = new XSSFRichTextString("行业类型");
        cell.setCellValue(d4);

        cell = row.createCell(cellId++);
        XSSFRichTextString d5 = new XSSFRichTextString("监测点性质");
        cell.setCellValue(d5);

        cell = row.createCell(cellId++);
        XSSFRichTextString d6 = new XSSFRichTextString("电网侧变电站");
        cell.setCellValue(d6);

        cell = row.createCell(cellId++);
        XSSFRichTextString d7 = new XSSFRichTextString("是否并网点");
        cell.setCellValue(d7);

        cell = row.createCell(cellId++);
        XSSFRichTextString d8 = new XSSFRichTextString("监测点运行状态");
        cell.setCellValue(d8);

        cell = row.createCell(cellId++);
        cell.setCellValue("国网ID");

        cell = row.createCell(cellId++);
        cell.setCellValue("监测点对象");

        cell = row.createCell(cellId++);
        cell.setCellValue("是否参与统计");

        List<String> l0 = manaDeviceMapper.getProName();
        String[] list0 = new String[l0.size()];
        l0.toArray(list0);
        sheet.addValidationData(setDataValidation(sheet, list0, 2, 1002, 1, 1));

        List<String> l1 = manaDeviceMapper.getDeptsInfo(); //所属部门
        String[] list1 = new String[l1.size()];
        l1.toArray(list1);
        for (int i = 0; i < l1.size(); i++) {
            XSSFRow row0 = hideSheet1.createRow(i);
            XSSFCell cell0 = row0.createCell(0);
            cell0.setCellValue(l1.get(i));
        }
        String strFormula1 = "sheet3!$A$1:$A$100";
        XSSFDataValidationConstraint constraint1 = new XSSFDataValidationConstraint(ValidationType.LIST, strFormula1);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions1 = new CellRangeAddressList(2, 1002, 3, 3);
        // 数据有效性对象
        DataValidationHelper help1 = new XSSFDataValidationHelper((XSSFSheet) sheet);
        DataValidation validation1 = help1.createValidation(constraint1, regions1);
        sheet.addValidationData(validation1);

        List<String> l5 = manaDeviceMapper.getScale();
        String[] list5 = new String[l5.size()];
        l5.toArray(list5);
        sheet.addValidationData(setDataValidation(sheet, list5, 2, 1002, 5, 5));

        List<String> l2 = manaDeviceMapper.getFacs();
        String[] list2 = new String[l2.size()];
        l2.toArray(list2);
        sheet.addValidationData(setDataValidation(sheet, list2, 2, 1002, 10, 10));

        String[] list = {"实际终端", "虚拟终端", "离线终端"};
        sheet.addValidationData(setDataValidation(sheet, list, 2, 1002, 11, 11));

        String[] list6 = {"星型接线", "三角型接线", "V型接线"};
        sheet.addValidationData(setDataValidation(sheet, list6, 2, 1002, 30, 30));

        String[] list7 = {"1", "3", "5", "10"};
        sheet.addValidationData(setDataValidation(sheet, list7, 2, 1002, 31, 31));

        List<String> l3 = manaDeviceMapper.getTypes();
        String[] list3 = new String[l3.size()];
        l3.toArray(list3);
        for (int i = 0; i < l3.size(); i++) {
            XSSFRow row0 = hideSheet.createRow(i);
            XSSFCell cell0 = row0.createCell(0);
            cell0.setCellValue(l3.get(i));
        }
        String strFormula = "sheet2!$A$1:$A$100";
        XSSFDataValidationConstraint constraint = new XSSFDataValidationConstraint(ValidationType.LIST, strFormula);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(2, 1002, 12, 12);
        // 数据有效性对象
        DataValidationHelper help = new XSSFDataValidationHelper((XSSFSheet) sheet);
        DataValidation validation = help.createValidation(constraint, regions);
        sheet.addValidationData(validation);

        List<String> l4 = manaDeviceMapper.getNodes();
        String[] list4 = new String[l4.size()];
        l4.toArray(list4);
        sheet.addValidationData(setDataValidation(sheet, list4, 2, 1002, 13, 13));

        sheet.addValidationData(setDataValidation(sheet, list5, 2, 1002, 22, 22));

        List<String> l8 = manaDeviceMapper.getLoadType();
        String[] list8 = new String[l8.size()];
        l8.toArray(list8);
        sheet.addValidationData(setDataValidation(sheet, list8, 2, 1002, 32, 32));

        String[] list32 = {"参与统计", "不参与统计"};
        sheet.addValidationData(setDataValidation(sheet, list32, 2, 1002, 40, 40));

        //行业类型
        List<String> hyes = manaDeviceMapper.getDic("行业类型");
        String[] hy = new String[hyes.size()];
        hyes.toArray(hy);
        sheet.addValidationData(setDataValidation(sheet, hy, 2, 1002, 33, 33));

        //监测点性质
        String[] xzs = {"电网侧", "非电网侧", "电网侧(新能源)", "非电网侧(新能源)", "上送国网", "PCC"};
        sheet.addValidationData(setDataValidation(sheet, xzs, 2, 1002, 34, 34));
        String[] isLine = {"否", "是"};
        sheet.addValidationData(setDataValidation(sheet, isLine, 2, 1002, 36, 36));
        String[] isRunLine = {"投运", "检修","退运"};
        sheet.addValidationData(setDataValidation(sheet, isRunLine, 2, 1002, 37, 37));

        for (int x = 0; x < 41; x++) {
            sheet.setColumnWidth(x, 20 * 256);
        }
        workbook.write(outputStream);
        workbook.close();
    }

    public DataValidation setDataValidation(XSSFSheet sheet, String[] textList, int firstRow, int endRow, int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        // 加载下拉列表内容
        DataValidationConstraint constraint = helper.createExplicitListConstraint(textList);
        constraint.setExplicitListValues(textList);

        // 设置数据有效性加载在哪个单元格上。
        // 四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList((short) firstRow, (short) endRow, (short) firstCol, (short) endCol);

        // 数据有效性对象
        DataValidation data_validation = helper.createValidation(constraint, regions);

        return data_validation;
    }

    public void XSSFSetDropDownAndHidden(XSSFWorkbook workbook, XSSFSheet sheet, XSSFSheet hideSheet, String[] formulaString, int firstRow, int endRow, int firstCol, int endCol, String range, String name, int cellId, int type) {
        Name category1Name = workbook.createName();
        category1Name.setNameName(name);

        if (type == 1) { //单元格类型为字符型
            for (int i = 0; i < formulaString.length; i++) {
                if (hideSheet.getRow(i) != null) {
                    hideSheet.getRow(i).createCell(cellId).setCellValue(formulaString[i]);
                } else {
                    hideSheet.createRow(i).createCell(cellId).setCellValue(formulaString[i]);
                }
            }
        } else if (type == 0) { //单元格类型为数值型
            for (int i = 0; i < formulaString.length; i++) {
                if (hideSheet.getRow(i) != null) {
                    hideSheet.getRow(i).createCell(cellId).setCellValue(Integer.parseInt(formulaString[i]));
                } else {
                    hideSheet.createRow(i).createCell(cellId).setCellValue(Integer.parseInt(formulaString[i]));
                }
            }
        }


        category1Name.setRefersToFormula("hiddenSheet!" + range + formulaString.length);
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createFormulaListConstraint(name);
        CellRangeAddressList addressList = new CellRangeAddressList((short) firstRow, (short) endRow, (short) firstCol, (short) endCol);
        DataValidation dataValidation = helper.createValidation(constraint, addressList);

        if (dataValidation instanceof XSSFDataValidation) {
            // 数据校验
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }

        sheet.addValidationData(dataValidation);
        workbook.setSheetHidden(1, true);
    }

    @Override
    public List<TranslateState> judgetranslate(Date time) {
        return manaDeviceMapper.judgetranslate(time);
    }

    @Override
    public void deleteTranslate(String guid) {
        TranslateState translateState = manaDeviceMapper.getBaseInfo(guid);
        translateState = dealTranslateStateParam(translateState);

        if (translateState != null) {
            manaDeviceMapper.deleteTableDataFlicker(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataFluc(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataHAI(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataHAV(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataHAP(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataHAQ(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataHAS(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataHarmrateI(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataHarmrateV(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataI(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataV(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataINI(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataINV(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());
            manaDeviceMapper.deleteTableDataPLT(translateState.getLineindex(), translateState.getStartTime(), translateState.getEndTime());

            manaDeviceMapper.delOfflog(guid);
        }
    }

    @Override
    public TranslateState queryimportLoading() {
        return manaDeviceMapper.queryimportLoading();
    }

    private String dealStringParam(String param) {
        jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, "ManaDeviceServiceImpldealStringParam", param, RedisDB.SHORT_TIME);
        String result = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, "ManaDeviceServiceImpldealStringParam");
        jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, "ManaDeviceServiceImpldealStringParam");
        return result;
    }

    private TranslateState dealTranslateStateParam(TranslateState param) {
        JSONObject jsonObject = JSONObject.fromObject(param);
        jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, "ManaDeviceServiceImpldealdealdealTranslateStateParamParam", jsonObject.toString(), RedisDB.SHORT_TIME);
        String result = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, "ManaDeviceServiceImpldealdealdealTranslateStateParamParam");
        jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, "ManaDeviceServiceImpldealdealdealTranslateStateParamParam");
        JSONObject strObject = JSONObject.fromObject(result);
        return (TranslateState) JSONObject.toBean(strObject, TranslateState.class);
    }

    @Override
    public void updateAllLimit() {
        List<Line> lines = lineMapper.selectAll();
        for (Line line : lines) {
            DicData sca = dicDataMapper.selectByPrimaryKey(line.getScale());
            String scaTmp = sca.getDicName();
            float nScale = Float.parseFloat(scaTmp.substring(0, scaTmp.length() - 2));

            //float[] fLimit = COverlimit.GetOverLimit(scaTmp, line.getDlcMp(), line.getJzcMp(), line.getXycMp(), line.getDevcMp());
            OverLimit overlimit = COverlimitUtil.globalAssemble(nScale, line.getXycMp(), line.getDevcMp(), line.getDlcMp());
            overlimit.setMyIndex(line.getLineIndex());

            OverLimit over = overLimitMapper.selectByPrimaryKey(line.getLineIndex());
            try {
                if (over == null) {
                    overLimitMapper.insert(overlimit);
                } else {
                    overLimitMapper.updateByPrimaryKey(overlimit);
                }
            } catch (Exception e) {
                logger.error(e.toString());
            }
        }
    }


    /**
     * 根据电压等级获取基准短路容量
     */
    public static float getJZCmp(String tmpname) {
        float capValue = 3.141592f;

        float voltageLevel = Float.parseFloat(tmpname.substring(0, tmpname.length() - 2));
        if (voltageLevel < DicDataEnum.KV06.getValue()) {
            capValue = 10;
        } else if (voltageLevel >= DicDataEnum.KV06.getValue() && voltageLevel < DicDataEnum.KV20.getValue()) {
            capValue = 100;
        } else if (voltageLevel >= DicDataEnum.KV20.getValue() && voltageLevel < DicDataEnum.KV35.getValue()) {
            capValue = 200;
        } else if (voltageLevel >= DicDataEnum.KV35.getValue() && voltageLevel < DicDataEnum.KV66.getValue()) {
            capValue = 250;
        } else if (voltageLevel >= DicDataEnum.KV66.getValue() && voltageLevel < DicDataEnum.KV110.getValue()) {
            capValue = 500;
        } else if (voltageLevel >= DicDataEnum.KV110.getValue() && voltageLevel < DicDataEnum.KV220.getValue()) {
            capValue = 750;
        } else if (voltageLevel >= DicDataEnum.KV220.getValue() && voltageLevel < DicDataEnum.KV330.getValue()) {
            capValue = 2000;
        } else if (voltageLevel >= DicDataEnum.KV330.getValue() && voltageLevel < DicDataEnum.KV500.getValue()) {
            capValue = 3000;
        } else if (voltageLevel >= DicDataEnum.KV500.getValue() && voltageLevel < DicDataEnum.KV750.getValue()) {
            capValue = 7000;
        } else if (voltageLevel >= DicDataEnum.KV750.getValue() && voltageLevel < DicDataEnum.KV1000.getValue()) {
            capValue = 9000;
        }
        return capValue;
    }


    @Override
    public Integer reCalOverLimit(){
        List<Line> lineDetailList = lineMapper.selectAll();
        int count = 0;
        for(Line line :lineDetailList){
            DicData dicData = dicDataMapper.selectId(line.getScale());
            float voltageLevel = Float.parseFloat(dicData.getDicName().substring(0, dicData.getDicName().indexOf("kV")));
            OverLimit overLimit = COverlimitUtil.globalAssemble(voltageLevel,line.getXycMp(),line.getDevcMp(),line.getDlcMp());
            overLimit.setMyIndex(line.getLineIndex());
            overLimitMapper.updateByPrimaryKey(overLimit);
            count++;
        }
        return count;
    }

    @Override
    public int addMonitor(String monitorId) {
        Monitor monitor = new Monitor();
        monitor.setMonitorId(monitorId);
        Monitor m = monitorMapper.selectOne(monitor);
        if (Objects.isNull(m)){
            monitor.setUpdateDate(new Date());
            return monitorMapper.insert(monitor);
        } else {
            return 0;
        }
    }

    @Override
    public String findMaxDeviceName(Long gdIndex) {
        String name = deviceMapper.findMaxDeviceName(gdIndex);
        return incrementString(name);
    }

    public String incrementString(String str) {
        // 查找最后一个非数字字符的位置
        int lastIndex = str.length() - 1;
        while (lastIndex >= 0 && Character.isDigit(str.charAt(lastIndex))) {
            lastIndex--;
        }
        // 如果没有找到非数字字符，说明整个字符串都是数字
        if (lastIndex == -1) {
            // 直接将字符串转换为整数，递增，再转回字符串
            return String.valueOf(Long.parseLong(str) + 1);
        }
        // 提取出数字部分
        String numberPart = str.substring(lastIndex + 1);
        // 将数字部分转换为整数，递增，再转回字符串
        long number = Long.parseLong(numberPart) + 1;
        String incrementedNumberPart = String.format("%0" + numberPart.length() + "d", number);
        // 将递增后的数字部分拼接到原字符串的非数字部分
        return str.substring(0, lastIndex + 1) + incrementedNumberPart;
    }

}
