package com.njcn.serviceimpl.configuration;

import cn.hutool.core.util.StrUtil;
import com.njcn.enums.DicDataTypeEnum;
import com.njcn.mapper.configuration.*;
import com.njcn.mapper.data.LimitRateMapper;
import com.njcn.mapper.system.ThemeMapper;
import com.njcn.pojo.advanced.HarmonicRateInfo;
import com.njcn.pojo.commons.*;
import com.njcn.pojo.commons.device.MachineAccount;
import com.njcn.pojo.commons.runmanage.SteadyResult;
import com.njcn.pojo.commons.runmanage.SteadyTable;
import com.njcn.pojo.configuration.*;
import com.njcn.pojo.data.Legder;
import com.njcn.pojo.jibei.Dnzljczz;
import com.njcn.pojo.jibei.Znycdz;
import com.njcn.pojo.system.Theme;
import com.njcn.pojo.user.Depts;
import com.njcn.pojo.user.Role;
import com.njcn.service.configuration.LineService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;
import com.njcn.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.*;

/**
 * @author hongawen
 * @Date: 2018/11/13 16:20
 */
@Service
public class LineServiceImpls implements LineService {
    private final static Logger logger = LoggerFactory.getLogger(LineServiceImpl.class);

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private LineMapper lineMapper;

    @Autowired
    private LineDetailMapper lineDetailMapper;

    @Autowired
    private LimitRateMapper limitRateMapper;

    @Autowired
    private MonitorMapper monitorMapper;

    @Autowired
    private SubStationMapper subStationMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private OverLimitMapper overLimitMapper;

    @Resource
    private ThemeMapper themeMapper;

    @Autowired
    private AppConfig appConfig;

    //稳态功能页面的数据获取，包括概览以及区域模块中的数据--------start

    /**
     * 概览--》稳态指标合格率
     *
     * @param startTime 起始时间
     * @param endTime   截止时间
     */
    @Override
    public SteadyTypeData getFrequencyDeviation(Date startTime, Date endTime, String overview) {
        //区域
        List<AreaGeneralData> areaGeneralDatas = userUtil.getAreaGeneralRun();
        if (CollectionUtils.isEmpty(areaGeneralDatas)) {
            return null;
        }
        SteadyTypeData steadyTypeData = getSteadyAllData(startTime, endTime, overview, areaGeneralDatas);
        return steadyTypeData;
    }

    /**
     * 区域统计--》稳态指标全部数据
     *
     * @param startTime 起始时间
     * @param endTime   截止时间
     * @param area      指定区域
     */
    @Override
    public SteadyTypeData getAllData(Date startTime, Date endTime, String area) {
        List<AreaGeneralData> areaGeneralDatasTemp = userUtil.getAreaDataByInfoRun(area);
        if (CollectionUtils.isEmpty(areaGeneralDatasTemp)) {
            return null;
        }
        SteadyTypeData steadyTypeData = getSteadyAllData(startTime, endTime, "", areaGeneralDatasTemp);
        return steadyTypeData;
    }


    /**
     * 根据时间、区域获取稳态指标合格率的所有数据
     *
     * @param startTime        起始时间
     * @param endTime          截止时间
     * @param overview         是否为缩略图
     * @param areaGeneralDatas 区域信息
     */
    private SteadyTypeData getSteadyAllData(Date startTime, Date endTime, String overview, List<AreaGeneralData> areaGeneralDatas) {
        SteadyTypeData steadyTypeData = new SteadyTypeData();
        List<Integer> devIndexs = new ArrayList<>();
        if (!CollectionUtils.isEmpty(areaGeneralDatas)) {
            List<SteadyData> area = new ArrayList<>();
            for (AreaGeneralData areaGeneralData : areaGeneralDatas) {
                SteadyData steadyData = getSteadyData(areaGeneralData);
                List<Integer> lineIndexs = areaGeneralData.getLineIndexs();
                if (!CollectionUtils.isEmpty(lineIndexs)) {
                    steadyData = getSteadyByTimeAndLineIndexs(steadyData, lineIndexs, startTime, endTime);
                }
                area.add(steadyData);
                devIndexs.addAll(areaGeneralData.getDeviceIndexs());
            }
            steadyTypeData.setArea(area);
        }

        if (StringUtils.isEmpty(overview)) {
            //电压等级
            List<VoltageData> voltageDatas = userUtil.getVoltageData(devIndexs);
            if (!CollectionUtils.isEmpty(voltageDatas)) {
                List<SteadyData> vol = new ArrayList<>();
                for (VoltageData voltageData : voltageDatas) {
                    if (!CollectionUtils.isEmpty(voltageData.getLineIndexs())) {
                        SteadyData steadyData = new SteadyData();
                        steadyData.setName(voltageData.getVol());
                        steadyData.setMonitors(voltageData.getLineIndexs().size());
                        steadyData = getSteadyByTimeAndLineIndexs(steadyData, voltageData.getLineIndexs(), startTime, endTime);
                        vol.add(steadyData);
                    }
                }
                steadyTypeData.setVol(vol);
            }
            //干扰源类型终
            List<LoadTypeValue> loadTypeValues = userUtil.getLoadTypeValue(devIndexs);
            if (!CollectionUtils.isEmpty(loadTypeValues)) {
                List<SteadyData> loadType = new ArrayList<>();
                for (LoadTypeValue loadTypeValue : loadTypeValues) {
                    if (!CollectionUtils.isEmpty(loadTypeValue.getLineIndexs())) {
                        SteadyData steadyData = new SteadyData();
                        steadyData.setName(loadTypeValue.getType());
                        steadyData.setMonitors(loadTypeValue.getLineIndexs().size());
                        steadyData = getSteadyByTimeAndLineIndexs(steadyData, loadTypeValue.getLineIndexs(), startTime, endTime);
                        loadType.add(steadyData);
                    }
                }
                steadyTypeData.setLoadType(loadType);
            }
        }
        return steadyTypeData;
    }
    /**
     * 初始化稳态实体
     *
     * @param areaGeneralData 区域数据
     */
    private SteadyData getSteadyData(AreaGeneralData areaGeneralData) {
        SteadyData steadyData = new SteadyData();
        steadyData.setName(areaGeneralData.getName());
        steadyData.setAreaIndex(areaGeneralData.getDeptIndex());
        steadyData.setMonitors(areaGeneralData.getMonitors());
        return steadyData;
    }

    /**
     * 根据时间获取所有监测点下的稳态各项指标的数据
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private SteadyData getSteadyByTimeAndLineIndexs(SteadyData steadyData, List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return new SteadyData();//全部是3.1415，代表无监测点无数据
        }
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        int size = lineIndexTemp.size();
        try {
            if (size > 1000) {
                int times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                    //需要区分频率偏差、三相电压不平衡与其他指标的获取方式
                    SteadyData tempT = limitRateMapper.getsteadDataByT(tempIndexs, startTime, endTime);
                    //合并数据
                    steadyData = mergeSteady(steadyData, tempT);
                    tempIndexs.clear();
                }
            } else {
                //需要区分频率偏差、三相电压不平衡与其他指标的获取方式
                SteadyData tempT = limitRateMapper.getsteadDataByT(lineIndexTemp, startTime, endTime);
                steadyData = mergeSteady(steadyData, tempT);
            }
        } catch (Exception e) {
            logger.error("获取各项指标数据发生异常，异常是"+e.getMessage());
        }
        return getSteadyAcc(steadyData);
    }


    /**
     * 合并数据
     *
     * @param steadyData 原始稳态实体
     */
    private SteadyData mergeSteady(SteadyData steadyData, SteadyData tempT) {
        if (tempT == null) {
            return steadyData;
        } else {
            if (steadyData.getAllTime() == 0) {
                steadyData.setAllTime(tempT.getAllTime());
            } else {
                steadyData.setAllTime(steadyData.getAllTime() + tempT.getAllTime());
            }
            if (steadyData.getFrequency() == 3.1415f) {
                steadyData.setFrequency(tempT.getFrequency());
            } else {
                steadyData.setFrequency(steadyData.getFrequency() + tempT.getFrequency());
            }

            if (steadyData.getuBalance() == 3.1415f) {
                steadyData.setuBalance(tempT.getuBalance());
            } else {
                steadyData.setuBalance(steadyData.getuBalance() + tempT.getuBalance());
            }

            if (steadyData.getVoltageDeviation() == 3.1415f) {
                steadyData.setVoltageDeviation(tempT.getVoltageDeviation());
            } else {
                steadyData.setVoltageDeviation(steadyData.getVoltageDeviation() + tempT.getVoltageDeviation());
            }

            if (steadyData.getAllFlicker() == 3.1415f) {
                steadyData.setAllFlicker(tempT.getAllFlicker());
            } else {
                steadyData.setAllFlicker(steadyData.getAllFlicker() + tempT.getAllFlicker());
            }

            if (steadyData.getFlicker() == 3.1415f) {
                steadyData.setFlicker(tempT.getFlicker());
            } else {
                steadyData.setFlicker(steadyData.getFlicker() + tempT.getFlicker());
            }

            if (steadyData.getiNeg() == 3.1415f) {
                steadyData.setiNeg(tempT.getiNeg());
            } else {
                steadyData.setiNeg(steadyData.getiNeg() + tempT.getiNeg());
            }
            if (steadyData.getInUharm() == 3.1415f) {
                steadyData.setInUharm(tempT.getInUharm());
            } else {
                steadyData.setInUharm(steadyData.getInUharm() + tempT.getInUharm());
            }

            if (steadyData.getHarmVoltage() == 3.1415f) {
                steadyData.setHarmVoltage(tempT.getHarmVoltage());
            } else {
                steadyData.setHarmVoltage(steadyData.getHarmVoltage() + tempT.getHarmVoltage());
            }

            if (steadyData.getHarmElec() == 3.1415f) {
                steadyData.setHarmElec(tempT.getHarmElec());
            } else {
                steadyData.setHarmElec(steadyData.getHarmElec() + tempT.getHarmElec());
            }
        }
        return steadyData;
    }


    /**
     * 根据查询出来的数据，计算出每个指标的合格率
     *
     * @param steadyData 稳态指标数据实体
     */
    private SteadyData getSteadyAcc(SteadyData steadyData) {
        if (steadyData.getAllTime() == 0 || steadyData.getAllTime() < 0) {
            steadyData.setVoltageDeviation(3.14159f);
            steadyData.setuBalance(3.14159f);
            steadyData.setFlicker(3.14159f);
            steadyData.setOddVoltage(3.14159f);
            steadyData.setEvenVoltage(3.14159f);
            steadyData.setOddElectric(3.14159f);
            steadyData.setEvenElectric(3.14159f);
            steadyData.setFrequency(3.14159f);
            steadyData.setuAberrance(3.14159f);
            steadyData.setHarmVoltage(3.14159f);
            steadyData.setHarmElec(3.14159f);
            //负序电流
            steadyData.setiNeg(3.14159f);
            //间谐波
            steadyData.setInUharm(3.14159f);
            return steadyData;
        } else {
            float allTime = steadyData.getAllTime();
            //冀北二期  谐波电流 谐波电压 负序电流 间谐波电压含有率 start
            steadyData.setHarmVoltage(getAcceptlityByData(allTime, steadyData.getHarmVoltage()));
            steadyData.setHarmElec(getAcceptlityByData(allTime, steadyData.getHarmElec()));
            steadyData.setiNeg(getAcceptlityByData(allTime, steadyData.getiNeg()));
            steadyData.setInUharm(getAcceptlityByData(allTime, steadyData.getInUharm()));
            //冀北二期  谐波电流 谐波电压 负序电流 间谐波电压含有率 end
            steadyData.setVoltageDeviation(getAcceptlityByData(allTime, steadyData.getVoltageDeviation()));
            steadyData.setuBalance(getAcceptlityByData(allTime, steadyData.getuBalance()));
            steadyData.setFlicker(getAcceptlityByData(steadyData.getAllFlicker(), steadyData.getFlicker()));
            steadyData.setOddVoltage(getAcceptlityByData(allTime, steadyData.getOddVoltage()));
            steadyData.setEvenVoltage(getAcceptlityByData(allTime, steadyData.getEvenVoltage()));
            steadyData.setOddElectric(getAcceptlityByData(allTime, steadyData.getOddElectric()));
            steadyData.setEvenElectric(getAcceptlityByData(allTime, steadyData.getEvenElectric()));
            steadyData.setFrequency(getAcceptlityByData(allTime, steadyData.getFrequency()));
            steadyData.setuAberrance(getAcceptlityByData(allTime, steadyData.getuAberrance()));
        }
        return steadyData;
    }

    //计算合格率结果
    private float getAcceptlityByData(float allTime, float data) {
        float result;
        if (Objects.equals(data,3.1415f)) {
            result = 3.14159f;
        } else {
            float accpet = allTime - data;
            if (accpet < 0) {
                accpet = 0;
            }
            if(allTime == 0){
                return 100.0f;
            }
            float num = accpet / allTime;
            // 格式化小数
            DecimalFormat df = new DecimalFormat("0.00");
            result = Float.parseFloat(df.format(num * 100));
        }
        return result;
    }

    //计算谐波电压合格率结果
    private float getAcceptlityByDataHarmVlotage(float allTime, float uAberrance, float eventVlotage, float oddVoltage) {
        float accpet = allTime*3 - uAberrance - eventVlotage - oddVoltage;
        if (accpet < 0) {
            accpet = 0;
        }
        float num = accpet / (allTime*3);
        DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
        return Float.valueOf(df.format(num * 100));
    }

    //计算谐波电流合格率结果
    private float getAcceptlityByDataHarmElec(float allTime, float eventElec, float oddElec) {
        float accpet = allTime*2 - eventElec - oddElec;
        if (accpet < 0) {
            accpet = 0;
        }
        float num = accpet / (allTime*2);
        DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
        return Float.valueOf(df.format(num * 100));
    }



    //稳态功能页面的数据获取，包括概览以及区域模块中的数据--------end

    /**
     * 获取稳态越限详情数据
     *
     * @param startTime 起始时间
     * @param endTime   截止时间
     * @param area      部门索引
     */
    @Override
    public List<SteadyTable> getSteadyOutOfLimitData(Date startTime, Date endTime, String area) {
        List<Integer> lineIndexs = userUtil.getAllLineIndexs(area);
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return null;
        }
        List<SteadyTable> steadyTables = getSteadyData(lineIndexs, startTime, endTime);
        if (CollectionUtils.isEmpty(steadyTables)) {
            return null;
        }
//        List<SteadyTable> resultTable = new ArrayList<>();
//        //筛选数据，只保留存在指标越限的记录
//        for (SteadyTable steadyTable : steadyTables) {
//            if (steadyTable.getHarmElec() < 60.0f || steadyTable.getHarmVoltage() < 60.0f || steadyTable.getFlicker() < 60.0f || steadyTable.getFrequency() < 60.0f|| steadyTable.getuBalance() < 60.0f || steadyTable.getVoltageDeviation() < 60.0f|| steadyTable.getiNeg() < 60.0f|| steadyTable.getInUharm() < 60.0f) {
//                resultTable.add(steadyTable);
//            }
//        }
        return steadyTables;
    }

    @Override
    public List<HarmonicRateInfo> getHarmonicRate(Date startTime, Date endTime) {
        List<AreaGeneralData> areaGeneral = userUtil.getAreaGeneral();
        List<Integer> ll = new ArrayList<>();

        for (AreaGeneralData depts : areaGeneral) {
            List<Integer> listLineIndex = depts.getLineIndexs(); // 获取监测点ID
            ll.addAll(listLineIndex);
        }

        HashSet<Integer> hashSet = new HashSet<>(ll);
        List<Integer> list = new ArrayList<>(hashSet);

        if (list.size() == 0) {  //如果未绑定监测点，做此操作
            List<HarmonicRateInfo> list1 = new ArrayList<>();
            return list1;
        }
        return limitRateMapper.getHarmonicRate(startTime, endTime, list);
    }

    @Override
    public int getRole(String url) {
        List<Role> list = userUtil.getRoles(TokenManager.getUserId());
        List<String> listRole = new ArrayList<>();

        if (list == null || list.size() == 0) {
            return 0;
        }

        for (Role role : list) {
            listRole.add(role.getRoleIndex());
        }

        return lineMapper.getRole(url, listRole) > 0 ? 1 : 0;
    }

    @Override
    public MachineAccount getLineName(Integer lineId) {
        return lineMapper.getLineName(lineId);
    }

    /**
     * 国网台账获取监测点的数据信息
     */
    @Override
    public Monitor loadgwLine(String lineIndex, String monitorId) {
        Monitor monitor = new Monitor();
        monitor.setMonitorId(monitorId);
        monitor = monitorMapper.selectByPrimaryKey(monitor);
        if (null == monitor) {
            return null;
        }
        Line line = new Line();
        line.setLineIndex(Long.parseLong(lineIndex));
        line = lineMapper.selectByPrimaryKey(line);
        OverLimit overLimit = new OverLimit();
        overLimit.setMyIndex(Long.parseLong(lineIndex));
        overLimit = overLimitMapper.selectByPrimaryKey(overLimit);
        if (null != overLimit) {
            monitor.setVoltageDev(overLimit.getVoltageDev());
            monitor.setUvoltageDev(overLimit.getUvoltageDev());
        }
        monitor.setLine(line);
        return monitor;
    }

    /**
     * 采用jdbc源生的方式获取国网变电站的数据
     *
     * @param subIndex 变电站索引
     */
    @Override
    public Znycdz loadgwSubstation(String subIndex) throws SQLException, IOException, ClassNotFoundException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet;
        Znycdz znycdz = null;
        try {
            //先根据变电站索引获取变电站名称
            SubStation subStation = new SubStation();
            subStation.setSubIndex(Long.parseLong(subIndex));
            subStation = subStationMapper.selectByPrimaryKey(subStation);
            if (null == subStation) {
                return null;
            }
            Properties pros = PubUtils.readProperties(getClass().getClassLoader(),"java.properties");
            String driverClass = "oracle.jdbc.driver.OracleDriver";
            String url = pros.get("JIBEI_URL").toString();
            String username = pros.get("JIBEI_Name").toString();
            String pwd = pros.get("JIBEI_PWD").toString();
            Class.forName(driverClass);
            connection = DriverManager.getConnection(url, username, pwd);
            String subName = subStation.getName();
            String sql = "SELECT t.* FROM T_SB_ZNYC_DZ t where t.bdzmc = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, subName);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                znycdz = new Znycdz();
                znycdz.setObjId(resultSet.getString(1));
                znycdz.setSbbm(resultSet.getString(2));
                znycdz.setDxmpyxkid(resultSet.getString(3));
                znycdz.setBdzmc(resultSet.getString(4));
                znycdz.setYxbh(resultSet.getString(5));
                znycdz.setSsds(resultSet.getString(6));
                znycdz.setYwdw(resultSet.getString(7));
                znycdz.setWhbz(resultSet.getString(8));
                znycdz.setZcxz(resultSet.getString(9));
                znycdz.setZcdw(resultSet.getString(10));
                znycdz.setDydj(resultSet.getString(11));
                znycdz.setYxzt(resultSet.getString(12));
                znycdz.setTyrq(resultSet.getTimestamp(13));
                znycdz.setDzlx(resultSet.getString(14));
                znycdz.setSfdw(resultSet.getString(15));
                znycdz.setZbfs(resultSet.getString(16));
                znycdz.setBzfs(resultSet.getString(17));
                znycdz.setSfsnz(resultSet.getString(18));
                znycdz.setWhdj(resultSet.getString(19));
                znycdz.setZlssrl(resultSet.getInt(20));
                znycdz.setZz(resultSet.getString(21));
                znycdz.setZdmj(resultSet.getInt(22));
                znycdz.setJzmj(resultSet.getInt(23));
                znycdz.setHb(resultSet.getInt(24));
                znycdz.setDqtz(resultSet.getString(25));
                znycdz.setLxdh(resultSet.getString(26));
                znycdz.setJddz(resultSet.getInt(27));
                znycdz.setBz(resultSet.getString(28));
                znycdz.setFwfs(resultSet.getString(29));
                znycdz.setSfdljzw(resultSet.getString(30));
                znycdz.setSfdxz(resultSet.getString(31));
                znycdz.setZycd(resultSet.getString(32));
                znycdz.setPbts(resultSet.getInt(33));
                znycdz.setPbzrl(resultSet.getInt(34));
                znycdz.setWgbcrl(resultSet.getInt(35));
                znycdz.setXblx(resultSet.getString(36));
                znycdz.setSfjyhw(resultSet.getString(37));
                znycdz.setDjsj(resultSet.getTimestamp(38));
                znycdz.setSbzr(resultSet.getString(39));
                znycdz.setZcdwmc(resultSet.getString(40));
                znycdz.setWhbzmc(resultSet.getString(41));
                znycdz.setSbzrmc(resultSet.getString(42));
                znycdz.setSsdsmc(resultSet.getString(43));
                znycdz.setYwdwmc(resultSet.getString(44));
                znycdz.setBdzjc(resultSet.getString(45));
                znycdz.setZgddgxq(resultSet.getString(46));
                znycdz.setSfmznjy(resultSet.getString(47));
                znycdz.setSfjravc(resultSet.getString(48));
                znycdz.setSfjrgzxxycxt(resultSet.getString(49));
                znycdz.setSfjzjk(resultSet.getString(50));
                znycdz.setZcbh(resultSet.getString(51));
                znycdz.setSfznbdz(resultSet.getString(52));
                znycdz.setBdzzyjb(resultSet.getString(53));
                znycdz.setHlzlx(resultSet.getString(54));
                znycdz.setSszlxt(resultSet.getString(55));
                znycdz.setSfnw(resultSet.getString(56));
                znycdz.setTuiyrq(resultSet.getTimestamp(57));
                znycdz.setXh(resultSet.getString(58));
                znycdz.setSccj(resultSet.getString(59));
                znycdz.setCcbh(resultSet.getString(60));
                znycdz.setCcrq(resultSet.getTimestamp(61));
                znycdz.setEddy(resultSet.getString(62));
                znycdz.setEddl(resultSet.getString(63));
                znycdz.setSblx(resultSet.getString(64));
                znycdz.setSbpbs(resultSet.getString(65));
                znycdz.setGcbh(resultSet.getString(66));
                znycdz.setSjdw(resultSet.getString(67));
                znycdz.setSgdw(resultSet.getString(68));
                znycdz.setGcmc(resultSet.getString(69));
                znycdz.setJldw(resultSet.getString(70));
                znycdz.setSbzjfs(resultSet.getString(71));
                znycdz.setDydjmc(resultSet.getString(72));
                znycdz.setRecordtimestamp(resultSet.getTimestamp(73));
                znycdz.setRecordstatus(resultSet.getString(74));
                znycdz.setBdzqljmc(resultSet.getString(75));
                znycdz.setYwdwqljmc(resultSet.getString(76));
                znycdz.setWhbzqljmc(resultSet.getString(77));
                znycdz.setZcdwqljmc(resultSet.getString(78));
                znycdz.setZcxzmc(resultSet.getString(79));
                znycdz.setDydjfw(resultSet.getString(80));
                znycdz.setDydjfwmc(resultSet.getString(81));
                znycdz.setYxztmc(resultSet.getString(82));
                znycdz.setSsdsqljmc(resultSet.getString(83));
                znycdz.setSszlxtqljmc(resultSet.getString(84));
                znycdz.setSccjmc(resultSet.getString(85));
                znycdz.setLx(resultSet.getString(86));
                znycdz.setZyfl(resultSet.getString(87));
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                logger.error(e.getMessage());
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                logger.error(e.getMessage());
            }
        }
        return znycdz;
    }

    /**
     * 采用jdbc源生的方式获取国网终端的数据
     *
     * @param devIndex 终端索引
     */
    @Override
    public Dnzljczz loadgwDevice(String devIndex) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet;
        Dnzljczz dnzljczz = null;
        try {
            //先根据装置索引获取出装置IP
            Device device = new Device();
            device.setDevIndex(Long.parseLong(devIndex));
            device = deviceMapper.selectByPrimaryKey(device);
            if (null == device) {
                return null;
            }
            Properties pros = PubUtils.readProperties(getClass().getClassLoader(),"java.properties");
            String driverClass = "oracle.jdbc.driver.OracleDriver";
            String url = pros.get("JIBEI_URL").toString();
            String username = pros.get("JIBEI_Name").toString();
            String pwd = pros.get("JIBEI_PWD").toString();
            Class.forName(driverClass);
            connection = DriverManager.getConnection(url, username, pwd);
            String ip1 = device.getIp();
            String sql = "SELECT t.* FROM T_SB_ZXJCZZ_DNZLJCZZ t where t.ip1 = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, ip1);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                dnzljczz = new Dnzljczz();
                dnzljczz.setObjId(resultSet.getString(1));
                dnzljczz.setZzmc(resultSet.getString(2));
                dnzljczz.setZzbh(resultSet.getString(3));
                dnzljczz.setZzlb(resultSet.getString(4));
                dnzljczz.setSszf(resultSet.getString(5));
                dnzljczz.setSsds(resultSet.getString(6));
                dnzljczz.setYwdw(resultSet.getString(7));
                dnzljczz.setWhbz(resultSet.getString(8));
                dnzljczz.setYxzt(resultSet.getString(9));
                dnzljczz.setZzjb(resultSet.getString(10));
                dnzljczz.setZzxh(resultSet.getString(11));
                dnzljczz.setSccj(resultSet.getString(12));
                dnzljczz.setCcrq(resultSet.getTimestamp(13));
                dnzljczz.setCcbh(resultSet.getString(14));
                dnzljczz.setTyrq(resultSet.getTimestamp(15));
                dnzljczz.setJcjdrq(resultSet.getTimestamp(16));
                dnzljczz.setSspg(resultSet.getString(17));
                dnzljczz.setZzdydy(resultSet.getString(18));
                dnzljczz.setClxhsrxs(resultSet.getString(19));
                dnzljczz.setDyxhsrtds(resultSet.getString(20));
                dnzljczz.setDlxhsrtds(resultSet.getString(21));
                dnzljczz.setCckhyprl(resultSet.getString(22));
                dnzljczz.setDsfs(resultSet.getString(23));
                dnzljczz.setSbzr(resultSet.getString(24));
                dnzljczz.setSbzrmc(resultSet.getString(25));
                dnzljczz.setPbh(resultSet.getString(26));
                dnzljczz.setPmc(resultSet.getString(27));
                dnzljczz.setPglx(resultSet.getString(28));
                dnzljczz.setIp1(resultSet.getString(29));
                dnzljczz.setMac1(resultSet.getString(30));
                dnzljczz.setZwym1(resultSet.getString(31));
                dnzljczz.setWg1(resultSet.getString(32));
                dnzljczz.setDk1(resultSet.getString(33));
                dnzljczz.setZcxz(resultSet.getString(34));
                dnzljczz.setZcdw(resultSet.getString(35));
                dnzljczz.setZcdwmc(resultSet.getString(36));
                dnzljczz.setZcbh(resultSet.getString(37));
                dnzljczz.setGcbh(resultSet.getString(38));
                dnzljczz.setGcmc(resultSet.getString(39));
                dnzljczz.setSbzjfs(resultSet.getString(40));
                dnzljczz.setWbsms(resultSet.getString(41));
                dnzljczz.setWbsbm(resultSet.getString(42));
                dnzljczz.setSbbm(resultSet.getString(43));
                dnzljczz.setDjsj(resultSet.getTimestamp(44));
                dnzljczz.setBz(resultSet.getString(45));
                dnzljczz.setFbzt(resultSet.getString(46));
                dnzljczz.setXghsbmc(resultSet.getString(47));
                dnzljczz.setErpwbsbm(resultSet.getString(48));
                dnzljczz.setSsdsmc(resultSet.getString(49));
                dnzljczz.setYwdwmc(resultSet.getString(50));
                dnzljczz.setWhbzmc(resultSet.getString(51));
                dnzljczz.setSccjmc(resultSet.getString(52));
                dnzljczz.setZcxzmc(resultSet.getString(53));
                dnzljczz.setRecordtimestamp(resultSet.getTimestamp(54));
                dnzljczz.setRecordstatus(resultSet.getString(55));
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                logger.error(e.getMessage());
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                logger.error(e.getMessage());
            }
        }
        return dnzljczz;
    }

    /**
     * 运行管理--》稳态指标列表
     *
     * @param area      区域
     * @param startTime 起始时间	 * @param endTime 截止时间
     */
    @Override
    public SteadyResult getSteadyData(Date startTime, Date endTime, String area) {
        SteadyResult steadyResult = new SteadyResult();
        List<Integer> lineIndexs = userUtil.getAllLineIndexs(area);
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return null;
        }
        List<SteadyTable> steadyTables = getSteadyData(lineIndexs, startTime, endTime);
        steadyResult.setSteadyTableList(steadyTables);
        steadyResult.setAllCount(lineIndexs.size());
        steadyResult.setRealCount(steadyTables.size());
        return steadyResult;
    }

    //分片1000监测点获取稳态指标合格率数据
    public List<SteadyTable> getSteadyData(List<Integer> lineIndexs, Date startTime, Date endTime) {
        List<SteadyTable> steadyTables = new ArrayList<>();
        if (lineIndexs.size() > 1000) {
            int times = lineIndexs.size();
            for (int i = 1; i <= times; i++) {
                if (lineIndexs.size() > 1000) {
                    List<Integer> tempIndexs = lineIndexs.subList(0, 1000);
                    List<SteadyTable> tempDatasT = limitRateMapper.getSteadyDataByT(tempIndexs, startTime, endTime);
                    steadyTables.addAll(tempDatasT);
                    tempIndexs.clear();
                } else {
                    List<SteadyTable> tempDatasT = limitRateMapper.getSteadyDataByT(lineIndexs, startTime, endTime);
                    steadyTables.addAll(tempDatasT);
                }
            }
        } else {
            steadyTables = limitRateMapper.getSteadyDataByT(lineIndexs, startTime, endTime);
        }
//        if(!CollectionUtils.isEmpty(steadyTables)){
//            for (SteadyTable steadyTable:steadyTables) {
//                steadyTable.setHarmVoltage(getHarmVoltageValue(steadyTable.getuAberrance(),steadyTable.getOddVoltage(),steadyTable.getEvenVoltage()));
//                steadyTable.setHarmElec(getHarmElecValue(steadyTable.getOddElectric(),steadyTable.getEvenElectric()));
//            }
//        }
        return steadyTables;
    }


    private float getValue(float temp) {
        if (temp > 100) {
            return 100;
        } else if (temp < 0) {
            return 0;
        } else {
            return PubUtils.floatRound(2,temp);
        }
    }

    private float getHarmVoltageValue(float uAberrance,float oddVoltage,float evenVoltage) {
        float value=uAberrance+oddVoltage+evenVoltage;
        value=value/3;
        return getValue(value);

    }

    private float getHarmElecValue(float oddElectric,float evenElectric) {
        float value=oddElectric+evenElectric;
        value=value/2;
        return getValue(value);
    }


    /**
     * 根据查询结果计算出合格率
     *
     * @param simpleValue 查询结果
     */
    private String getAcceptlity(SimpleValue simpleValue) {
        if (null == simpleValue || null == simpleValue.getCountAll() || simpleValue.getCountAll() == 0) {
            return "0";
        } else {
            int accpet = simpleValue.getCountAll() - simpleValue.getCountOnline();
            float num = Float.valueOf(accpet) / Float.valueOf(simpleValue.getCountAll());
            DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
            return df.format(num * 100);
        }
    }


    /**
     * 根据监测点索引、时间获取频率偏差的合格率
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private String getAcceptByLineIndexsAndTime(List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0";
        }
        SimpleValue simpleValue = new SimpleValue();
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        Integer size = lineIndexTemp.size();
        try {
            if (size > 1000) {
                Integer times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    if (size > 1000) {
                        List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                        SimpleValue temp = limitRateMapper.getFrequencyDevitaion(tempIndexs, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                        size = size - 1000;
                    } else {
                        SimpleValue temp = limitRateMapper.getFrequencyDevitaion(lineIndexTemp, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                    }
                }
            } else {
                simpleValue = limitRateMapper.getFrequencyDevitaion(lineIndexTemp, startTime, endTime);
            }
        } catch (Exception e) {
            logger.error("redis缓存的存取出现异常，方法为：getAcceptByLineIndexsAndTime");
        }
        return getAcceptlity(simpleValue);
    }

    /**
     * 根据监测点索引、时间获取电压不平衡数据合格率
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private String getUBalaneByLineIndexsAndTime(List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0";
        }
//		String key="getAcceptByLineIndexsAndTime"+userUtil.getSysType()+startTime.toString()+endTime.toString()+lineIndexs.toString();
        SimpleValue simpleValue = new SimpleValue();
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        Integer size = lineIndexTemp.size();
        try {
            //todo...添加缓存
            if (size > 1000) {
                Integer times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    if (size > 1000) {
                        List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                        SimpleValue temp = limitRateMapper.getUBalane(tempIndexs, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                        size = size - 1000;
                    } else {
                        SimpleValue temp = limitRateMapper.getUBalane(lineIndexTemp, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                    }
                }
            } else {
                simpleValue = limitRateMapper.getUBalane(lineIndexTemp, startTime, endTime);
            }
        } catch (Exception e) {
            logger.error("redis缓存的存取出现异常，方法为：getUBalaneByLineIndexsAndTime");
        }
        return getAcceptlity(simpleValue);
    }

    /**
     * 根据监测点索引、时间获取电压畸变率合格率
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private String getUAberranceByLineIndexsAndTime(List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0";
        }
//		String key="getAcceptByLineIndexsAndTime"+userUtil.getSysType()+startTime.toString()+endTime.toString()+lineIndexs.toString();
        SimpleValue simpleValue = new SimpleValue();
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        Integer size = lineIndexTemp.size();
        try {
            //todo...添加缓存
            if (size > 1000) {
                Integer times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    if (size > 1000) {
                        List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                        SimpleValue temp = limitRateMapper.getUAberrance(tempIndexs, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                        size = size - 1000;
                    } else {
                        SimpleValue temp = limitRateMapper.getUAberrance(lineIndexTemp, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                    }
                }
            } else {
                simpleValue = limitRateMapper.getUAberrance(lineIndexTemp, startTime, endTime);
            }
        } catch (Exception e) {
            logger.error("redis缓存的存取出现异常，方法为：getUAberranceByLineIndexsAndTime");
        }
        return getAcceptlity(simpleValue);
    }

    /**
     * 根据监测点索引、时间获取电压偏差合格率
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private String getVoltageDeviationByLineIndexsAndTime(List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0";
        }
//		String key="getAcceptByLineIndexsAndTime"+userUtil.getSysType()+startTime.toString()+endTime.toString()+lineIndexs.toString();
        SimpleValue simpleValue = new SimpleValue();
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        Integer size = lineIndexTemp.size();
        try {
            //todo...添加缓存
            if (size > 1000) {
                Integer times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    if (size > 1000) {
                        List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                        SimpleValue temp = limitRateMapper.getVoltageDeviation(tempIndexs, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                        size = size - 1000;
                    } else {
                        SimpleValue temp = limitRateMapper.getVoltageDeviation(lineIndexTemp, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                    }
                }
            } else {
                simpleValue = limitRateMapper.getVoltageDeviation(lineIndexTemp, startTime, endTime);
            }
        } catch (Exception e) {
            logger.error("redis缓存的存取出现异常，方法为：getUAberranceByLineIndexsAndTime");
        }
        return getAcceptlity(simpleValue);
    }

    /**
     * 根据监测点索引、时间获取闪变合格率
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private String getFlickerByLineIndexsAndTime(List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0";
        }
//		String key="getAcceptByLineIndexsAndTime"+userUtil.getSysType()+startTime.toString()+endTime.toString()+lineIndexs.toString();
        SimpleValue simpleValue = new SimpleValue();
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        Integer size = lineIndexTemp.size();
        try {
            //todo...添加缓存
            if (size > 1000) {
                Integer times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    if (size > 1000) {
                        List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                        SimpleValue temp = limitRateMapper.getFlicker(tempIndexs, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                        size = size - 1000;
                    } else {
                        SimpleValue temp = limitRateMapper.getFlicker(lineIndexTemp, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                    }
                }
            } else {
                simpleValue = limitRateMapper.getFlicker(lineIndexTemp, startTime, endTime);
            }
        } catch (Exception e) {
            logger.error("redis缓存的存取出现异常，方法为：getUAberranceByLineIndexsAndTime");
        }
        return getAcceptlity(simpleValue);
    }

    /**
     * 根据监测点索引、时间获取奇次电压合格率
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private String getOddVoltageByLineIndexsAndTime(List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0";
        }
//		String key="getAcceptByLineIndexsAndTime"+userUtil.getSysType()+startTime.toString()+endTime.toString()+lineIndexs.toString();
        SimpleValue simpleValue = new SimpleValue();
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        Integer size = lineIndexTemp.size();
        try {
            //todo...添加缓存
            if (size > 1000) {
                Integer times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    if (size > 1000) {
                        List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                        SimpleValue temp = limitRateMapper.getOddVoltage(tempIndexs, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                        size = size - 1000;
                    } else {
                        SimpleValue temp = limitRateMapper.getOddVoltage(lineIndexTemp, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                    }
                }
            } else {
                simpleValue = limitRateMapper.getOddVoltage(lineIndexTemp, startTime, endTime);
            }
        } catch (Exception e) {
            logger.error("redis缓存的存取出现异常，方法为：getUAberranceByLineIndexsAndTime");
        }
        return getAcceptlity(simpleValue);
    }


    /**
     * 根据监测点索引、时间获取偶次电压合格率
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private String getEvenVoltageByLineIndexsAndTime(List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0";
        }
//		String key="getAcceptByLineIndexsAndTime"+userUtil.getSysType()+startTime.toString()+endTime.toString()+lineIndexs.toString();
        SimpleValue simpleValue = new SimpleValue();
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        Integer size = lineIndexTemp.size();
        try {
            //todo...添加缓存
            if (size > 1000) {
                Integer times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    if (size > 1000) {
                        List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                        SimpleValue temp = limitRateMapper.getEventVoltage(tempIndexs, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                        size = size - 1000;
                    } else {
                        SimpleValue temp = limitRateMapper.getEventVoltage(lineIndexTemp, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                    }
                }
            } else {
                simpleValue = limitRateMapper.getEventVoltage(lineIndexTemp, startTime, endTime);
            }
        } catch (Exception e) {
            logger.error("redis缓存的存取出现异常，方法为：getUAberranceByLineIndexsAndTime");
        }
        return getAcceptlity(simpleValue);
    }

    /**
     * 根据监测点索引、时间获取奇次电流合格率
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private String getOddElectricByLineIndexsAndTime(List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0";
        }
//		String key="getAcceptByLineIndexsAndTime"+userUtil.getSysType()+startTime.toString()+endTime.toString()+lineIndexs.toString();
        SimpleValue simpleValue = new SimpleValue();
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        Integer size = lineIndexTemp.size();
        try {
            //todo...添加缓存
            if (size > 1000) {
                Integer times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    if (size > 1000) {
                        List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                        SimpleValue temp = limitRateMapper.getOddElectric(tempIndexs, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                        size = size - 1000;
                    } else {
                        SimpleValue temp = limitRateMapper.getOddElectric(lineIndexTemp, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                    }
                }
            } else {
                simpleValue = limitRateMapper.getOddElectric(lineIndexTemp, startTime, endTime);
            }
        } catch (Exception e) {
            logger.error("redis缓存的存取出现异常，方法为：getUAberranceByLineIndexsAndTime");
        }
        return getAcceptlity(simpleValue);
    }

    /**
     * 根据监测点索引、时间获取偶次电流合格率
     *
     * @param lineIndexs 监测点索引
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private String getEvenElectricByLineIndexsAndTime(List<Integer> lineIndexs, Date startTime, Date endTime) {
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0";
        }
//		String key="getAcceptByLineIndexsAndTime"+userUtil.getSysType()+startTime.toString()+endTime.toString()+lineIndexs.toString();
        SimpleValue simpleValue = new SimpleValue();
        List<Integer> lineIndexTemp = new ArrayList<>(lineIndexs);
        Integer size = lineIndexTemp.size();
        try {
            //todo...添加缓存
            if (size > 1000) {
                Integer times = size / 1000 + 1;
                for (int i = 0; i < times; i++) {
                    if (size > 1000) {
                        List<Integer> tempIndexs = lineIndexTemp.subList(0, 1000);
                        SimpleValue temp = limitRateMapper.getEventElectric(tempIndexs, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                        size = size - 1000;
                    } else {
                        SimpleValue temp = limitRateMapper.getEventElectric(lineIndexTemp, startTime, endTime);
                        simpleValue = userUtil.mergeSim(simpleValue, temp);
                    }
                }
            } else {
                simpleValue = limitRateMapper.getEventElectric(lineIndexTemp, startTime, endTime);
            }
        } catch (Exception e) {
            logger.error("redis缓存的存取出现异常，方法为：getUAberranceByLineIndexsAndTime");
        }
        return getAcceptlity(simpleValue);
    }


    public SteadyData getSteady(Date startTime, Date endTime, Long lineIndex) {
        SteadyData acceptabilityAllData = new SteadyData();
        List<Integer> lineIndexs = new ArrayList<>();
        lineIndexs.add(lineIndex.intValue());

        SteadyData steady = new SteadyData();
        acceptabilityAllData = getSteadyByTimeAndLineIndexs(steady, lineIndexs, startTime, endTime);
        return acceptabilityAllData;
    }

    public List<SteadyData> getSteadyTB(Date startTime, Date endTime, Date laststartTime, Date lastendTime, Long lineIndex) {
        List<SteadyData> result = new ArrayList<>();
        List<Integer> lineIndexs = new ArrayList<>();
        lineIndexs.add(lineIndex.intValue());

        SteadyData tmp1 = new SteadyData();
        SteadyData tmp2 = new SteadyData();

        SteadyData steady = new SteadyData();
        SteadyData steady1 = new SteadyData();
        tmp1 = getSteadyByTimeAndLineIndexs(steady, lineIndexs, startTime, endTime);
        tmp2 = getSteadyByTimeAndLineIndexs(steady1, lineIndexs, laststartTime, lastendTime);

        result.add(tmp1);
        result.add(tmp2);
        return result;
    }

    @Override
    public Line selectLineByIndex(Long lineId) {
        Line line = new Line();
        line.setLineIndex(lineId);
        line = lineMapper.selectOne(line);
        return line;
    }


    @Override
    public List<Legder> getLedger(String area, String voltage, String factory, String type, String appear, String nature) {
        //获取主题名称
        SimpleValue simpleValue = getThemeInfo();
        String theme = simpleValue.getName();

        if (nature == null) {
            nature = "-1";
        }
        //根据用户信息获取部门index
        Depts depts = userUtil.getDeptsByUser(TokenManager.getToken());
        List<Legder> legderList = new ArrayList<>();

        //获取部门信息且获取监测点信息
        List<String> listArea = new ArrayList<>();

        if (area == null || area.equals("-1,")) {
            listArea = null;
        } else {
            condition(area, listArea);
        }

        List<Depts> listDepts = lineMapper.getSubDeptsIndex(depts.getDeptsIndex(), listArea);

        if (listDepts == null || listDepts.size() == 0) { //没有子部门
            listDepts.add(depts);
        }

        for (Depts depts1 : listDepts) {
            Legder legder = new Legder();
            legder.setAreaIndex(depts1.getDeptsIndex());

            if (depts1.getCustomDept() == 0) {
                legder.setAreaName(depts1.getAreaName() == null ? depts1.getArea() : depts1.getAreaName());
            } else {
                legder.setAreaName(depts1.getDeptsName());
            }

            List<Integer> list = lineMapper.getDeptsLineIndex(depts1.getDeptsIndex(), userUtil.getSysType(),true);

            if (list == null || list.size() == 0) { //如果没有数据作为子部门再查一次
                list = lineMapper.getDeptsLineIndexs(depts1.getDeptsIndex(), userUtil.getSysType(),true);
            }

            if (list != null && list.size() > 0) {
                //获取电压等级统计结果 暂时不考虑超过1000个监测点
                List<Legder.pData> pDataList = new ArrayList<>();
                List<String> listVoltage = new ArrayList<>();

                if (voltage == null || voltage.equals("-1,")) {
                    listVoltage = null;
                } else {
                    condition(voltage, listVoltage);
                }

                //获取干扰源类型终统计结果
                List<String> listType = new ArrayList<>();

                if (type == null || type.equals("-1,")) {
                    listType = null;
                } else {
                    condition(type, listType);
                }

                //获取终端厂家统计结果
                List<String> listFactory = new ArrayList<>();

                if (factory == null || factory.equals("-1,")) {
                    listFactory = null;
                } else {
                    condition(factory, listFactory);
                }

                if (list.size() > 1000) {
                    int times = ((list.size() % 1000 == 0) ? list.size() / 1000 : (list.size() / 1000 + 1));

                    for (int i = 1; i <= times; i++) {
                        if (list.size() > 1000) {
                            List<Integer> temp = list.subList(0, 1000);
                            translatedata(legder, lineMapper.getVoltageData(temp, listVoltage, Integer.parseInt(nature)), "电压等级", pDataList);
                            translatedata(legder, lineMapper.getTypeData(temp, listType, Integer.parseInt(nature)), DicDataTypeEnum.payloadEnum.getName(), pDataList);
                            translatedata(legder, lineMapper.getFactoryData(temp, listFactory, Integer.parseInt(nature)), "终端厂家", pDataList);
                            //获取国网上报统计结果
                            mointer(lineMapper.getMonitorData(temp, appear, Integer.parseInt(nature)), pDataList, appear,theme);
                            temp.clear();
                        } else {
                            translatedata(legder, lineMapper.getVoltageData(list, listVoltage, Integer.parseInt(nature)), "电压等级", pDataList);
                            translatedata(legder, lineMapper.getTypeData(list, listType, Integer.parseInt(nature)), DicDataTypeEnum.payloadEnum.getName(), pDataList);
                            translatedata(legder, lineMapper.getFactoryData(list, listFactory, Integer.parseInt(nature)), "终端厂家", pDataList);
                            //获取国网上报统计结果
                            mointer(lineMapper.getMonitorData(list, appear, Integer.parseInt(nature)), pDataList, appear,theme);
                        }
                    }
                } else {
                    translatedata(legder, lineMapper.getVoltageData(list, listVoltage, Integer.parseInt(nature)), "电压等级", pDataList);
                    translatedata(legder, lineMapper.getTypeData(list, listType, Integer.parseInt(nature)), DicDataTypeEnum.payloadEnum.getName(), pDataList);
                    translatedata(legder, lineMapper.getFactoryData(list, listFactory, Integer.parseInt(nature)), "终端厂家", pDataList);
                    //获取国网上报统计结果
                    mointer(lineMapper.getMonitorData(list, appear, Integer.parseInt(nature)), pDataList, appear,theme);
                }

                legder.setList(pDataList);
                legderList.add(legder);
            }
        }

        return legderList;
    }

    private void condition(String str, List<String> list) {
        String[] array = str.split(",");

        for (int i = 0; i < array.length; i++) {
            list.add(array[i]);
        }
    }

    //获取主题
    private SimpleValue getThemeInfo() {
        SimpleValue simpleValue=new SimpleValue();
        Theme theme = new Theme();
        theme.setState(1);
        theme.setActive(1);
        theme=themeMapper.selectOne(theme);
        if(null==theme){
            //返回国网绿
            simpleValue.setValue("#006565");
            simpleValue.setName("国网");
        }else{
            simpleValue.setValue(theme.getThemeColor());
            simpleValue.setName(theme.getThemeDesc());
        }
        return simpleValue;
    }

    private void mointer(List<Legder.Data> dataList, List<Legder.pData> pDataList, String appear, String theme) {
        if (pDataList.size() == 0) {
            Legder.Data data = new Legder.Data();
            List<Legder.Data> list = new ArrayList<>();
            data.setDicIndex("0");
            data.setDicName(theme+"上报");
            Legder.Data data1 = new Legder.Data();
            data1.setDicIndex("1");
            data1.setDicName("非"+theme+"上报");

            for (Legder.Data d : dataList) {
                if (d.getDicIndex() != null) {
                    data.setSubCount(data.getSubCount() + d.getSubCount());
                    data.setGdCount(data.getGdCount() + d.getGdCount());
                    data.setLineCount(data.getLineCount() + d.getLineCount());
                } else {
                    data1.setSubCount(data1.getSubCount() + d.getSubCount());
                    data1.setGdCount(data1.getGdCount() + d.getGdCount());
                    data1.setLineCount(data1.getLineCount() + d.getLineCount());
                }
            }

            if ((appear == null || appear.equals("-1"))) {
                list.add(data);
                list.add(data1);
            } else if (appear.equals("0")) {
                list.add(data);
            } else if (appear.equals("1")) {
                list.add(data1);
            }

            Legder.pData pData = new Legder().new pData();
            pData.setName(theme+"上报");
            pData.setList(list);
            pDataList.add(pData);
        } else {
            Iterator<Legder.pData> iterator1 = pDataList.iterator();
            while (iterator1.hasNext()) {
                Legder.pData p = iterator1.next();

                if (p.getName().equals(theme+"上报")) {
                    for (Legder.pData pData : pDataList) {
                        if (pData.getName().equals(theme+"上报")) {
                            for (Legder.Data data : dataList) {
                                for (Legder.Data d : pData.getList()) {
                                    if ((data.getDicIndex() != null && d.getDicIndex().equals("0")) || (data.getDicIndex() == null && d.getDicIndex().equals("1"))) {
                                        d.setGdCount(d.getGdCount().intValue() + data.getGdCount().intValue());
                                        d.setSubCount(d.getSubCount().intValue() + data.getSubCount().intValue());
                                        d.setLineCount(d.getLineCount().intValue() + data.getLineCount().intValue());
                                    }
                                }
                            }
                        }
                    }

                    break;
                } else if (!iterator1.hasNext()) {
                    Legder.Data data = new Legder.Data();
                    List<Legder.Data> list = new ArrayList<>();
                    data.setDicIndex("0");
                    data.setDicName(theme+"上报");
                    Legder.Data data1 = new Legder.Data();
                    data1.setDicIndex("1");
                    data1.setDicName("非"+theme+"上报");

                    for (Legder.Data d : dataList) {
                        if (d.getDicIndex() != null) {
                            data.setSubCount(data.getSubCount() + d.getSubCount());
                            data.setGdCount(data.getGdCount() + d.getGdCount());
                            data.setLineCount(data.getLineCount() + d.getLineCount());
                        } else {
                            data1.setSubCount(data1.getSubCount() + d.getSubCount());
                            data1.setGdCount(data1.getGdCount() + d.getGdCount());
                            data1.setLineCount(data1.getLineCount() + d.getLineCount());
                        }
                    }

                    if ((appear == null || appear.equals("-1"))) {
                        list.add(data);
                        list.add(data1);
                    } else if (appear.equals("0")) {
                        list.add(data);
                    } else if (appear.equals("1")) {
                        list.add(data1);
                    }

                    Legder.pData pData = new Legder().new pData();
                    pData.setName(theme+"上报");
                    pData.setList(list);
                    pDataList.add(pData);
                    break;
                }
            }
        }
    }

    private void translatedata(Legder legder, List<Legder.Data> dataList, String name, List<Legder.pData> pDataList) {
        if (pDataList.size() == 0) {
            if (dataList != null && dataList.size() > 0) {
                Legder.pData pData = new Legder().new pData();
                pData.setName(name);
                pData.setList(dataList);
                pDataList.add(pData);
            }
        } else {
            Iterator<Legder.Data> iterator = dataList.iterator();
            Iterator<Legder.pData> iterator1 = pDataList.iterator();

            while (iterator1.hasNext()) {
                Legder.pData pData = iterator1.next();

                if (pData.getName().equals(name)) {
                    int length = pData.getList().size();

                    while (iterator.hasNext()) {
                        Legder.Data data = iterator.next();

                        if (length == 0) {
                            pData.getList().add(data);
                        }

                        for (int i = 0; i < length; i++) {
                            Legder.Data d = pData.getList().get(i);

                            if (d.getDicName().equals(data.getDicName())) {
                                d.setGdCount(d.getGdCount().intValue() + data.getGdCount().intValue());
                                d.setSubCount(d.getSubCount().intValue() + data.getSubCount().intValue());
                                d.setLineCount(d.getLineCount().intValue() + data.getLineCount().intValue());
                                break;
                            } else if (i == length - 1) {
                                pData.getList().add(data);
                            }
                        }
                    }

                    break;
                } else if (!iterator1.hasNext()) {
                    Legder.pData p = new Legder().new pData();
                    p.setName(name);
                    p.setList(dataList);
                    pDataList.add(p);
                    break;
                }
            }
        }
    }


    @Override
    public String queryWiringDiagram(Integer lineId, HttpServletResponse response) {
        LineDetail lineDetail = lineDetailMapper.selectByPrimaryKey(lineId.longValue());
        if (Objects.nonNull(lineDetail)) {
            String imgUrl = lineDetail.getWiringDiagram();
            if (StrUtil.isNotBlank(imgUrl)) {
                try {

                    FileImageInputStream in = null;
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    try {
                        //建一个空的字节数组
                        byte[] result = null;
                        in = new FileImageInputStream(new File(appConfig.getTmppath() + File.separator + "LineWireDiagram"+File.separator+imgUrl));
                        byte[] buf = new byte[1024];
                        //用来定义一个准备接收图片总长度的局部变量
                        int len;
                        //将流的内容读取到buf内存中
                        while ((len = in.read(buf)) > 0) {
                            //将buf内存中的内容从0开始到总长度输出出去
                            out.write(buf, 0, len);
                        }
                        //将out中的流内容拷贝到一开始定义的字节数组中
                        result = out.toByteArray();
                        //通过util包中的Base64类对字节数组进行base64编码
                        String base64 = Base64.getEncoder().encodeToString(result);
                        String s = base64.replaceAll("\n", "").replaceAll("\r", "");
                        String substring = imgUrl.substring(imgUrl.lastIndexOf('.')+1);
                        return "data:image/" + substring + ";base64,"+s;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    return "查看主接线图失败";
                }
            }else {
                return "暂无主接线图";
            }
        }
        return "查看主接线图失败";
    }
}
