package com.pqs9000.controller.business;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.security.interfaces.RSAPrivateKey;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.security.auth.login.AccountException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.njcn.enums.LogTypeEnum;
import com.njcn.mapper.user.UserMapper;
import com.njcn.pojo.commons.device.*;
import com.njcn.pojo.configuration.*;
import com.njcn.pojo.user.UserDetail;
import com.njcn.utils.*;
import com.njcn.utils.redis.JedisManager;
import com.pqs9000.pojo.report.*;
import com.pqs9000.pojo.report.enumReport.EnumPass;
import com.pqs9000.service.data.RealTimeDataService;
import com.pqs9000.service.data.VersionService;
import com.pqs9000.service.report.*;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.njcn.mapper.configuration.GDInforMapper;
import com.njcn.mapper.configuration.LineMapper;
import com.njcn.mapper.configuration.OverLimitMapper;
import com.njcn.mapper.configuration.ReportModelMapper;
import com.njcn.mapper.data.OfflLogMapper;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.commons.SimpleValue;
import com.njcn.pojo.commons.SteadyData;
import com.njcn.pojo.data.EventDetail;
import com.njcn.pojo.data.OfflLog;
import com.njcn.service.configuration.DeviceService;
import com.njcn.service.configuration.HistoryResultService;
import com.njcn.service.configuration.LineService;
import com.njcn.service.configuration.TreeService;
import com.njcn.service.data.EventDetailService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.sso.pojo.user.User;
import com.pqs9000.pojo.common.PowerQualityData;
import com.pqs9000.service.common.HarmIService;
import com.pqs9000.service.common.HarmonicService;
import com.pqs9000.service.data.AssesService;
import com.pqs9000.util.TransformTime;
import com.pqs9000.util.Kafka.JavaKafkaConsumer;
import com.pqs9000.util.Kafka.JavaKafkaProducer;

import net.sf.json.JSONArray;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

@Controller
@RequestMapping(value = "device")
public class DeviceController {
    private JavaKafkaProducer javaKafkaProducer = null;
    private JavaKafkaConsumer javaKafkaConsumer = null;
    ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private AppConfig appConfig;
    private static final Logger logger = LoggerFactory.getLogger(DeviceController.class);

    @Resource
    private TreeService getDeviceTree;

    @Autowired
    COverlimit cOverlimit;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private AssesService assesService;

    @Autowired
    private VersionService versionService;

    @Autowired
    private OverLimitMapper overLimitMapper;

    @Autowired
    private UserUtil userUtil;


    @Autowired
    private HarmonicService harmonicService;

    @Autowired
    GDInforMapper gdInforMapper;

    @Autowired
    OfflLogMapper offlLogMapper;

    @Autowired
    ReportModelMapper reportModelMapper;

    @Autowired
    LineMapper lineMapper;

    @Autowired
    HistoryResultService historyResultService;

    @Autowired
    private EventDetailService eventDetailService;

    @Autowired
    private LineService lineService;

    @Autowired
    private SocketClient socketClient;

    @Autowired
    private HarmIService harmIService;

    @Autowired
    UserLogDetailService userLog;

    @Autowired
    private GetOverLimitDataService getOverLimitDataService;

    @Autowired
    private GetVirtualDataService getVirtualDataService;

    @Autowired
    private GetPowerDataService getPowerDataService;

    @Autowired
    private GetFlickerDataService getFlickerDataService;

    @Autowired
    private GetDistortionDataService getDistortionDataService;

    @Autowired
    private GetVdeviationDataService getVdeviationDataService;

    @Autowired
    private GetFrequencyDataService getFrequencyDataService;

    @Autowired
    private GetThreephaseDataService getThreephaseDataService;

    @Autowired
    private GetVoltageRateService getVoltageRateService;

    @Autowired
    private GetICurrentService getICurrentService;

    @Autowired
    private GetInharmService getInharmService;

    @Autowired
    private GetVoltage getVoltage;

    @Autowired
    private GetInegDataService getInegDataService;

    @Autowired
    private UserMapper userMapper;

    @Resource
    private RealTimeDataService realTimeDataService;

    @Autowired
    JedisManager jedisManager;

    @Autowired
    private ExcelReportService excelReportService;

    /**
     * 终端树
     *
     * @return
     */
    @RequestMapping(value = "tree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getTree(String startTime, String endTime) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "tree");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }

        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceTree.getNodeTreedata(user.getLoginName(), datePojo.getStartTime(), datePojo.getEndTime());
            result = PubUtils.assignmentResult(data, 200, "获取设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取设备树信息失败");
        }
        return result;
    }

    /**
     * 终端树
     *
     * @return
     */
    @RequestMapping(value = "nodetree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getNodeTree(String startTime, String endTime) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "tree");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }

        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceTree.getNodeTreedata(user.getLoginName(), datePojo.getStartTime(), datePojo.getEndTime());
            result = PubUtils.assignmentResult(data, 200, "获取设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取设备树信息失败");
        }
        return result;
    }

    /**
     * 电压等级终端树
     *
     * @return
     */
    @RequestMapping(value = "scaleTree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult devTypeTree(String startTime, String endTime) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "tree");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }

        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceTree.getScaleTree(user.getLoginName(), datePojo.getStartTime(), datePojo.getEndTime());
            result = PubUtils.assignmentResult(data, 200, "获取设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取设备树信息失败");
        }
        return result;
    }

    /**
     * 厂家终端树
     *
     * @return
     */
    @RequestMapping(value = "mancTree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult mancTree(String startTime, String endTime) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "tree");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }

        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceTree.getMancTree(user.getLoginName(), datePojo.getStartTime(), datePojo.getEndTime());
            result = PubUtils.assignmentResult(data, 200, "获取设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取设备树信息失败");
        }
        return result;
    }

    /**
     * 干扰源类型终终端树
     *
     * @return
     */
    @RequestMapping(value = "loadTypeTree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult loadTypeTree(String startTime, String endTime) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "tree");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }

        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceTree.getLoadTypeTree(user.getLoginName(), datePojo.getStartTime(), datePojo.getEndTime());
            result = PubUtils.assignmentResult(data, 200, "获取设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取设备树信息失败");
        }
        return result;
    }

    /**
     * 国网上报终端树
     *
     * @return
     */
    @RequestMapping(value = "monitorTree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult monitorTree(String startTime, String endTime) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "tree");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }

        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceTree.getMonitorTree(user.getLoginName(), datePojo.getStartTime(), datePojo.getEndTime());
            result = PubUtils.assignmentResult(data, 200, "获取设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取设备树信息失败");
        }
        return result;
    }

    /**
     * 离线终端树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "offLinetree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getOffLineTree(HttpServletRequest request) {
        HttpResult result;
        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceTree.getOffLineTree(user.getLoginName(), 1);
            result = PubUtils.assignmentResult(data, 200, "获取离线设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取离线设备树信息失败");
        }
        return result;
    }

    /**
     * 年份终端树
     *
     * @return
     */
    @RequestMapping(value = "yeartree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult yeartree(HttpServletRequest request) {
        HttpResult result;
        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceTree.getOffYearTree(user.getLoginName());
            result = PubUtils.assignmentResult(data, 200, "获取离线设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取离线设备树信息失败");
        }
        return result;
    }

    /**
     * 干扰源类型终端树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "loadtypetree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult loadtypetree(HttpServletRequest request) {
        HttpResult result;
        User user = TokenManager.getToken();
        List<Tree> data;
        try {
            data = getDeviceTree.getOffTypeTree(user.getLoginName());
            result = PubUtils.assignmentResult(data, 200, "获取离线设备树信息成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "获取离线设备树信息失败");
        }
        return result;
    }

    @RequestMapping(value = "yxzt", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getYxzt(HttpServletRequest request, String startTime, String endTime, Long lineIndex) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getYxzt");

        List<Float> yxzt = new ArrayList<>();
        String onlineRate;
        String company;

        if (!datePojo.getValidity()) {
            result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
            return result;
        }
        try {
            List<Integer> lineIndexs = new ArrayList<>();
            lineIndexs.add(lineIndex.intValue());

            SimpleValue sim = null;
            if (CollectionUtils.isEmpty(lineIndexs)) {
                company = "0.00";
            } else {
                sim = userUtil.selectIntegralityByLineIndexAndTime(lineIndexs, datePojo.getStartTime(), datePojo.getEndTime());
            }
            if (null == sim || sim.getCountAll() == null || sim.getCountAll() == 0) {
                company = "0.00";
            } else {
                float num = (float) sim.getCountOnline() / sim.getCountAll();
                DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
                company = df.format(num * 100);
            }

            onlineRate = deviceService.getDeviceOnline(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            if (onlineRate == null) {
                yxzt.add(Float.parseFloat("0"));
            } else {
                yxzt.add(Float.parseFloat(onlineRate));
            }

            if (company == null) {
                yxzt.add(Float.parseFloat("0"));
            } else {
                yxzt.add(Float.parseFloat(company));
            }
            result = PubUtils.assignmentResult(yxzt, 200, "获取终端在线率数据成功");
            userLog.getLog("查询稳态运行状态", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            userLog.getLog("查询稳态运行状态", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("获取终端运行数据失败,方法名：getOnlineRate");
            result = PubUtils.assignmentResult(null, 500, "获取终端在线率数据失败");
        }
        return result;
    }

    @RequestMapping(value = "yxztTB", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getYxztTB(String startTime, String endTime, String laststartTime, String lastendTime, Long lineIndex) {
        HttpResult result;
        DatePojo datePojo;
        DatePojo lastdatePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getYxzt");
        lastdatePojo = PubUtils.validateDate(laststartTime, lastendTime, "getYxzt");

        List<Float> yxzt = new ArrayList<>();
        String onlineRate, onlineRate1;
        String company, company1;

        if (!datePojo.getValidity()) {
            result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
            return result;
        }
        try {
            List<Integer> lineIndexs = new ArrayList<>();
            lineIndexs.add(lineIndex.intValue());

            SimpleValue sim = null;
            if (CollectionUtils.isEmpty(lineIndexs)) {
                company = "0.00";
            } else {
                sim = userUtil.selectIntegralityByLineIndexAndTime(lineIndexs, datePojo.getStartTime(), datePojo.getEndTime());
            }
            if (null == sim || sim.getCountAll() == null || sim.getCountAll() == 0) {
                company = "0.00";
            } else {
                float num = (float) sim.getCountOnline() / sim.getCountAll();
                DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
                company = df.format(num * 100);
            }

            onlineRate = deviceService.getDeviceOnline(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            if (onlineRate == null) {
                yxzt.add(Float.parseFloat("0"));
            } else {
                yxzt.add(Float.parseFloat(onlineRate));
            }

            if (company == null) {
                yxzt.add(Float.parseFloat("0"));
            } else {
                yxzt.add(Float.parseFloat(company));
            }

            SimpleValue sim1 = null;
            if (CollectionUtils.isEmpty(lineIndexs)) {
                company1 = "0.00";
            } else {
                sim1 = userUtil.selectIntegralityByLineIndexAndTime(lineIndexs, lastdatePojo.getStartTime(), lastdatePojo.getEndTime());
            }
            if (null == sim1 || sim1.getCountAll() == null || sim1.getCountAll() == 0) {
                company1 = "0.00";
            } else {
                float num1 = (float) sim1.getCountOnline() / sim1.getCountAll();
                DecimalFormat df1 = new DecimalFormat("0.00");// 格式化小数
                company1 = df1.format(num1 * 100);
            }

            onlineRate1 = deviceService.getDeviceOnline(lastdatePojo.getStartTime(), lastdatePojo.getEndTime(), lineIndex);
            if (onlineRate1 == null) {
                yxzt.add(Float.parseFloat("0"));
            } else {
                yxzt.add(Float.parseFloat(onlineRate1));
            }

            if (company1 == null) {
                yxzt.add(Float.parseFloat("0"));
            } else {
                yxzt.add(Float.parseFloat(company1));
            }

            result = PubUtils.assignmentResult(yxzt, 200, "获取终端在线率数据成功");
        } catch (Exception e) {
            logger.error("获取终端运行数据失败,方法名：getOnlineRate");
            result = PubUtils.assignmentResult(null, 500, "获取终端在线率数据失败");
        }
        return result;
    }

    /***
     * 终端统计
     */
    @RequestMapping(value = "getSbtj", method = RequestMethod.POST)
    @ResponseBody
    public SbtjData getSbtj(HttpServletRequest request) throws JsonProcessingException, AccountException {
        SbtjData result = new SbtjData();
        List<DeviceDetail> model = new ArrayList<DeviceDetail>();
        List<DeviceDetail> area = new ArrayList<DeviceDetail>();
        List<DeviceDetail> factory = new ArrayList<DeviceDetail>();

        List<List> mo = new ArrayList<List>();
        List<List> ar = new ArrayList<List>();
        List<List> fa = new ArrayList<List>();

        model = deviceService.getDevtype();
        userLog.getLog("查询终端型号", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        for (int i = 0; i < model.size(); i++) {
            List<String> a = new ArrayList<String>();
            a.add(model.get(i).getDevType());
            a.add(model.get(i).getyAxis().toString());
            mo.add(a);
        }

        factory = deviceService.getManufacturer();
        userLog.getLog("查询终端厂家", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        for (int i = 0; i < factory.size(); i++) {
            List<String> b = new ArrayList<String>();
            b.add(factory.get(i).getManufacturer());
            b.add(factory.get(i).getyAxis().toString());
            fa.add(b);
        }

        area = deviceService.getArea();
        userLog.getLog("查询区域统计", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        for (int i = 0; i < area.size(); i++) {
            List<String> c = new ArrayList<String>();
            c.add(area.get(i).getArea());
            c.add(area.get(i).getyAxis().toString());
            ar.add(c);
        }

        result.setModel(mo);
        result.setArea(ar);
        result.setFactory(fa);

        return result;
    }

    /**
     * 概览--》在线率
     *
     * @param startTime 起始时间
     * @param endTime   截止时间
     */
    @PostMapping("onlineRate")
    @ResponseBody
    public HttpResult getOnlineRate(String startTime, String endTime, Long lineIndex) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getOnlineRate");
        if (!datePojo.getValidity()) {
            result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
            return result;
        }
        String data;
        try {
            data = deviceService.getDeviceOnline(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            result = PubUtils.assignmentResult(data, 200, "获取终端在线率数据成功");
        } catch (Exception e) {
            logger.error("获取终端运行数据失败,方法名：getOnlineRate");
            result = PubUtils.assignmentResult(null, 500, "获取终端在线率数据失败");
        }
        return result;
    }

    /*
     * 运行状态
     */
    @RequestMapping(value = "runInfo", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getRunInfo(String lineIndex, String startTime, String endTime) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getGeneralData");
        if (!datePojo.getValidity()) {
            result = PubUtils.assignmentResult(null, 500, "解析前台传递的时间有误");
            return result;
        }
        List<Communication> communications;
        try {
            communications = deviceService.getRunInfo(Long.valueOf(lineIndex), datePojo.getStartTime(), datePojo.getEndTime());
            result = PubUtils.assignmentResult(communications, 200, "获取数据成功");
        } catch (Exception e) {
            logger.error("方法名：getRunInfo，异常为：" + e);
            result = PubUtils.assignmentResult(null, 500, "获取数据失败");
        }
        return result;
    }

    /*
     * 稳态指标合格率
     */
    @PostMapping("steady")
    @ResponseBody
    public HttpResult getSteady(HttpServletRequest request, String startTime, String endTime, Long lineIndex) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "steady");
        if (!datePojo.getValidity() || lineIndex == null) {
            result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
            return result;
        }
        SteadyData data;
        try {
            data = lineService.getSteady(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            result = PubUtils.assignmentResult(data, 200, "获取稳态合格率数据成功");
            userLog.getLog("查询稳态合格率", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            userLog.getLog("查询稳态合格率", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("获取终端运行数据失败,方法名：steady");
            result = PubUtils.assignmentResult(null, 500, "获取终端在线率数据失败");
        }
        return result;
    }

    @PostMapping("steadyTB")
    @ResponseBody
    public HttpResult getSteadyTB(String startTime, String endTime, String laststartTime, String lastendTime, Long lineIndex) {
        HttpResult result;
        DatePojo datePojo, lastdatePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "steadyTB");
        lastdatePojo = PubUtils.validateDate(laststartTime, lastendTime, "steadyTB");
        if (!datePojo.getValidity() || lineIndex == null) {
            result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
            return result;
        }
        List<SteadyData> data = new ArrayList<>();
        try {
            data = lineService.getSteadyTB(datePojo.getStartTime(), datePojo.getEndTime(), lastdatePojo.getStartTime(), lastdatePojo.getEndTime(), lineIndex);
            result = PubUtils.assignmentResult(data, 200, "获取终端在线率数据成功");
        } catch (Exception e) {
            logger.error("获取终端运行数据失败,方法名：steady");
            result = PubUtils.assignmentResult(null, 500, "获取终端在线率数据失败");
        }
        return result;
    }

    @RequestMapping(value = "integrality", method = RequestMethod.POST)
    @ResponseBody
    public String getIntegrality(String lineIndex, String startTime, String endTime) {
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getIntegrality");

        List<Integer> lineIndexs = new ArrayList<>();
        lineIndexs.add(Integer.valueOf(lineIndex));

        SimpleValue sim;
        if (CollectionUtils.isEmpty(lineIndexs)) {
            return "0.00";
        } else {
            sim = userUtil.selectIntegralityByLineIndexAndTime(lineIndexs, datePojo.getStartTime(), datePojo.getEndTime());
        }
        if (null == sim || sim.getCountAll() == null || sim.getCountAll() == 0) {
            return "0.00";
        }
        float num = (float) sim.getCountOnline() / sim.getCountAll();
        DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
        return df.format(num * 100);
    }

    @RequestMapping(value = "getPttype", method = RequestMethod.POST)
    @ResponseBody
    public List<Integer> getPttype(String obj) {
        List<Map<String, Object>> list = null;
        JSONArray jsonArray = JSONArray.fromObject(obj);
        String points = (String) jsonArray.getJSONObject(0).get("point");
        String[] pointid = points.split(",");
        List<Integer> listw = new ArrayList<Integer>();
        int point;
        for (int i = 0; i < pointid.length; i++) {
            if (StringUtils.isEmpty(pointid[i])) {
                continue;
            }
            point = Integer.parseInt(pointid[i]);
            int pttype = deviceService.getConnect(Long.valueOf(point));
            listw.add(pttype);
        }
        return listw;
    }

    //获取暂降事件
    @RequestMapping(value = "getZjCf", method = RequestMethod.POST)
    @ResponseBody
    public List<List> getZjCf(String obj, String startTime, String endTime, Long lineIndex
    ) {
        int num = 0;
        JSONArray json = JSONArray.fromObject(obj); //使用net.sf.json.JSONObject对象来解析json
        List<List> listw = new ArrayList<List>();
        String startT = (String) json.getJSONObject(0).get("startAllTime");
        startTime = startT;                      //获取时间段的开始时间
        String endT = (String) json.getJSONObject(0).get("endAllTime");
        endTime = endT;
        String start = (String) json.getJSONObject(0).get("start");
        String end = (String) json.getJSONObject(0).get("end");
        String point = (String) json.getJSONObject(0).get("point");
        String[] pointid = null;
        try {
            int g = 0;
            pointid = point.split(",");
            g = pointid.length;
            for (int j = 0; j < pointid.length; j++) {
                lineIndex = Long.valueOf(pointid[j]);
                List<EventDetail> eventDetails = eventDetailService.queryZj(startTime, endTime, start,
                        end, lineIndex);
                if (!eventDetails.isEmpty()) {
                    List<List> lists = new ArrayList<List>();
                    for (int i = 0; i < eventDetails.size(); i++) {
                        List<String> list1 = new ArrayList<>();
                        list1.add(eventDetails.get(i).getEventDetailIndex());
                        list1.add(String.valueOf(eventDetails.get(i).getTimeId().getTime()));
                        list1.add(String.valueOf(g));
                        lists.add(list1);
                    }
                    listw.add(lists);
                } else {
                    listw.add(null);
                }
            }
        } catch (Exception e) {
            logger.error("获取暂降事件异常，异常是" + e.toString());
        }
        return listw;
    }

    //获取限值
    @RequestMapping(value = "getXz", method = RequestMethod.POST)
    @ResponseBody
    public OverLimtResult getXz(String obj, Long lineIndex, String number) {
        OverLimtResult result = new OverLimtResult();
        JSONArray json = JSONArray.fromObject(obj); //使用net.sf.json.JSONObject对象来解析json
        String point = (String) json.getJSONObject(0).get("point");
        String[] pointid = point.split(",");
        try {
            for (int j = 0; j < pointid.length; j++) {
                lineIndex = Long.valueOf(pointid[j]);
                Example example = new Example(OverLimit.class);
                example.createCriteria().andEqualTo("myIndex", lineIndex);
                List<OverLimit> overLimit = overLimitMapper.selectByExample(example);

                if (!overLimit.isEmpty()) {
                    for (int i = 0; i < overLimit.size(); i++) {
                        List<Float> list = new ArrayList<>();
                        list.add(overLimit.get(i).getFreqDev());//频率限值
                        list.add(overLimit.get(i).getUbalance());//三相不平衡度限值
                        list.add(overLimit.get(i).getFlicker());//闪变限值
                        list.add(overLimit.get(i).getUaberrance());//电压畸变限值
                        list.add(overLimit.get(i).getVoltageDev());//电压偏差限值

                        list.add(overLimit.get(i).getUharm_2());//2次谐波电压限值
                        list.add(overLimit.get(i).getUharm_3());//3次谐波电压限值
                        list.add(overLimit.get(i).getUharm_4());//4次谐波电压限值
                        list.add(overLimit.get(i).getUharm_5());//5次谐波电压限值
                        list.add(overLimit.get(i).getUharm_6());//6次谐波电压限值
                        list.add(overLimit.get(i).getUharm_7());//7次谐波电压限值
                        list.add(overLimit.get(i).getUharm_8());//8次谐波电压限值
                        list.add(overLimit.get(i).getUharm_9());//9次谐波电压限值
                        list.add(overLimit.get(i).getUharm_10());//10次谐波电压限值
                        list.add(overLimit.get(i).getUharm_11());//11次谐波电压限值
                        list.add(overLimit.get(i).getUharm_12());//12次谐波电压限值
                        list.add(overLimit.get(i).getUharm_13());//13次谐波电压限值
                        list.add(overLimit.get(i).getUharm_14());//14次谐波电压限值
                        list.add(overLimit.get(i).getUharm_15());//15次谐波电压限值
                        list.add(overLimit.get(i).getUharm_16());//16次谐波电压限值
                        list.add(overLimit.get(i).getUharm_17());//17次谐波电压限值
                        list.add(overLimit.get(i).getUharm_18());//18次谐波电压限值
                        list.add(overLimit.get(i).getUharm_19());//19次谐波电压限值
                        list.add(overLimit.get(i).getUharm_20());//20次谐波电压限值
                        list.add(overLimit.get(i).getUharm_21());//21次谐波电压限值
                        list.add(overLimit.get(i).getUharm_22());//22次谐波电压限值
                        list.add(overLimit.get(i).getUharm_23());//23次谐波电压限值
                        list.add(overLimit.get(i).getUharm_24());//24次谐波电压限值
                        list.add(overLimit.get(i).getUharm_25());//25次谐波电压限值

                        list.add(overLimit.get(i).getIharm_2());//2次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_3());//3次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_4());//4次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_5());//5次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_6());//6次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_7());//7次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_8());//8次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_9());//9次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_10());//10次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_11());//11次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_12());//12次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_13());//13次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_14());//14次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_15());//15次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_16());//16次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_17());//17次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_18());//18次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_19());//19次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_20());//20次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_21());//21次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_22());//22次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_23());//23次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_24());//24次谐波幅值限值
                        list.add(overLimit.get(i).getIharm_25());//25次谐波幅值限值

                        list.add(overLimit.get(i).getInUharm_1());//0.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_2());//1.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_3());//2.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_4());//3.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_5());//4.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_6());//5.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_7());//6.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_8());//7.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_9());//8.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_10());//9.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_11());//10.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_12());//11.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_13());//12.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_14());//13.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_15());//14.5次间谐波含有率限值
                        list.add(overLimit.get(i).getInUharm_16());//15.5次间谐波含有率限值

                        list.add(overLimit.get(i).getiNeg());//负序电流限值
                        list.add(overLimit.get(i).getUvoltageDev());//电压下偏差限值

                        result.getData().add(list);
                    }
                } else {
                    result.getData().add(null);
                }
            }
        } catch (Exception e) {
            logger.error("获取限值异常，异常是" + e.toString());
        }
        result.setMsg("200");
        return result;
    }

    /**
     * @return com.njcn.pojo.configuration.HistoryResult
     * @Author denghuajun
     * @Description //TODO 获取历史数据
     * @Date 2018/9/26 10:13
     * @Param [request, startTime, endTime, lineIndex, type, number]
     **/
    @RequestMapping(value = "getHistoryResult", method = RequestMethod.POST)
    @ResponseBody
    public HistoryResult getHistoryResult(HttpServletRequest request, String obj, String startTime, String endTime, Long lineIndex, String type,
                                          String number) throws AccountException {
        int num = 0;
        int dataType = 0;
        HistoryResult result = new HistoryResult();
        JSONArray json = JSONArray.fromObject(obj); //使用net.sf.json.JSONObject对象来解析json
        List<List> listw = new ArrayList<List>();
        String o = (String) json.getJSONObject(0).get("condition");
        String[] condition = null;
        String startT = (String) json.getJSONObject(0).get("startTime");
        startTime = startT;                      //获取时间段的开始时间
        String endT = (String) json.getJSONObject(0).get("endTime");
        endTime = endT;
        String start = (String) json.getJSONObject(0).get("start");
        String end = (String) json.getJSONObject(0).get("end");
        condition = o.split(",");
        String point = (String) json.getJSONObject(0).get("point");
        String[] pointid = null;
        if(ObjectUtil.isNotNull(json.getJSONObject(0).get("dataType"))){
            dataType = Integer.parseInt(json.getJSONObject(0).get("dataType").toString());
        }

        //进行时间判断
        int flagday = appConfig.getReportday()+30; //默认30天之内查_表,大于30天查_take表
        String beginQuery = (String) json.getJSONObject(0).get("startAllTime");
        String endQuery  = (String) json.getJSONObject(0).get("endAllTime");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date flagbegin=null;
        Date flagend=null;
        try {
            flagbegin = sdf.parse(beginQuery+" "+start);
            flagend = sdf.parse(endQuery+" "+end);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int flag = (int) ((flagend.getTime()-flagbegin.getTime())/(1000*3600*24));
        int target = 1;
        if(flag>=flagday){
            target =0;
        }
        try {
            int g = 0;
            pointid = point.split(",");
            g = pointid.length;
            for (int j = 0; j < pointid.length; j++) {
                lineIndex = Long.valueOf(pointid[j]);
                for (int i = 0; i < condition.length; i++) {
                    HistoryResult resultTemp = new HistoryResult();
                    //datePojo=PubUtils.ChooseDate(startTime,endTime,"[-getHistoryData");
                    if (Integer.parseInt(condition[i]) == 41 || Integer.parseInt(condition[i]) == 42|| Integer.parseInt(condition[i]) == 44|| Integer.parseInt(condition[i]) == 45|| Integer.parseInt(condition[i]) == 46|| Integer.parseInt(condition[i]) == 47|| Integer.parseInt(condition[i]) == 48) {
                        number = String.valueOf(json.getJSONObject(0).get("harmonic"));
                    } else if (Integer.parseInt(condition[i]) == 43) {
                        number = String.valueOf(json.getJSONObject(0).get("inHarmonic"));
                    }
                    switch (Integer.parseInt(condition[i])) {
                        case 11:
                            type = "getXVrValue";                //相电压有效值
                            break;
                        case 12:
                            type = "getLVrValue";                //线电压有效值
                            break;
                        case 13:
                            type = "getDypc";                //电压偏差
                            break;
                        case 15:
                            type = "getSxbphd";                //三相电压不平衡度
                            break;
                        case 16:
                            type = "getBphdy";                //电压不平衡
                            break;
                        case 17:
                            type = "getDyzjbl";                //电压总谐波畸变率
                            break;
                        case 21:
                            type = "getDlyxz";                //电流有效值
                            break;
                        case 22:
                            type = "getDlzjbl";                //电流总谐波畸变率
                            break;
                        case 23:
                            type = "getFxdl";                //负序电流
                            break;
                        case 31:
                            type = "getPl";                //频率
                            break;
                        case 41:
                            if (number.equalsIgnoreCase("1")) {
                                type = "getJbhyl";
                            } else {
                                type = "getXbhyl";                //谐波电压含有率(N次谐波)
                            }
                            break;
                        case 42:
                            type = "getXbdlfz";                //谐波电流幅值
                            break;
                        case 43:
                            type = "getJxbhyl";                //简谐波电压含有率
                            break;
                        case 44:
                            type ="getXbVXj";                 //谐波电压相角
                            break;
                        case 45:
                            type ="getXbIXj";                 //谐波电流相角
                            break;
                        case 46:
                            type ="getXbYgGl";                 //谐波有功功率
                            break;
                        case 47:
                            type ="getXbWgGl";                 //谐波无功功率
                            break;
                        case 48:
                            type ="getXbSzGl";                 //谐波视在功率
                            break;
                        case 51:
                            type = "getYggl";                //三相有功功率
                            break;
                        case 52:
                            type = "getWggl";                //三相无功功率
                            break;
                        case 53:
                            type = "getSzgl";                //三相视在功率
                            break;
                        case 54:
                            type = "getYgzgl";                //三相有功总功率
                            break;
                        case 55:
                            type = "getWgzgl";                //三相无功总功率
                            break;
                        case 56:
                            type = "getSzzgl";                //三相视在总功率
                            break;
                        case 57:
                            type = "getSzglys";                //视在功率因数
                            break;
                        case 58:
                            type = "getWyglys";                //位移功率因数
                            break;
                        case 59:
                            type = "getZSzglys";                //总视在功率因数
                            break;
                        case 60:
                            type = "getZWyglys";                //总位移功率因数
                            break;
                        case 61:
                            type = "getDssb";                //短时电压闪变
                            break;
                        case 62:
                            type = "getCssb";                //长时电压闪变
                            break;
                        case 63:
                            type = "getDybd";                //电压波动
                            break;
                        default:
                            break;
                    }
                    num += 1;
                    //xuyang_add number增加正则判断，只能读取非0的正整数
                    String pattern = "^\\+?[1-9][0-9]*$";
                    if (!StringUtil.isEmpty(number) && !Pattern.matches(pattern, number)) {
                        break;
                    } else {
                        resultTemp = historyResultService.getHistroyResult(startTime, endTime, lineIndex, start, end, type, number, num, g, Integer.parseInt(condition[i]),target,dataType);
                        if (num == 2) {
                            result.setData2(resultTemp.getData2());
                        } else if (num == 3) {
                            result.setData3(resultTemp.getData3());
                        } else if (num == 1) {
                            result.setData1(resultTemp.getData1());
                        }
                        result.setData4(resultTemp.getData4());
                    }
                }
            }
            result.setMsg(String.valueOf(num));
            result.setMsg1(String.valueOf(g));
            userLog.getLog("查询稳态趋势对比", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            userLog.getLog("查询稳态趋势对比", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("获取历史数据异常，异常是" + e.toString());
        }
        return result;
    }

    private void transformData(List<ReportTarget> list, List<ReportValue> listValue, List<Pass> listOverlimit, boolean b,Float lowLimit) {
        int offset = 1;//b ? 3 : 1;
        int i = 0;
        for (int index = 0; index < listValue.size(); index += offset) {
            ReportTarget reportTarget = new ReportTarget();
            reportTarget.setList(listValue.subList(index, index + offset));
            Float overLimit = listOverlimit.get(0).getOverLimit();
            reportTarget.setOverLimit(overLimit);

            switch (listOverlimit.get(0).getCode()) {
                case 1:
                    for (int k = 0; k < reportTarget.getList().size(); k++) {
                        if (null == reportTarget.getList().get(k).getFmaxValue()) {
                            break;
                        } else if (reportTarget.getList().get(k).getFmaxValue().floatValue() > overLimit.floatValue()) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else {
                            reportTarget.setPass(EnumPass.PASS.getCode());
                        }
                    }
                    break;
                case 2:
                    for (int k = 0; k < reportTarget.getList().size(); k++) {
                        if (null == reportTarget.getList().get(k).getMinValue()) {
                            break;
                        } else if (reportTarget.getList().get(k).getMinValue().floatValue() > overLimit.floatValue()) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else {
                            reportTarget.setPass(EnumPass.PASS.getCode());
                        }
                    }
                    break;
                case 3:
                    for (int k = 0; k < reportTarget.getList().size(); k++) {
                        if (null == reportTarget.getList().get(k).getMeanValue()) {
                            break;
                        } else if (reportTarget.getList().get(k).getMeanValue().floatValue() > overLimit.floatValue()) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else {
                            reportTarget.setPass(EnumPass.PASS.getCode());
                        }
                    }
                    break;
                case 4:
                    for (int k = 0; k < reportTarget.getList().size(); k++) {
                        if (null == reportTarget.getList().get(k).getCp95Value()) {
                            break;
                        } else if (reportTarget.getList().get(k).getCp95Value().floatValue() > overLimit.floatValue()) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else {
                            reportTarget.setPass(EnumPass.PASS.getCode());
                        }
                    }
                    break;
                case 6:
                    for (int k = 0; k < reportTarget.getList().size(); k++) {
                        if (null == reportTarget.getList().get(k).getFmaxValue() || null == reportTarget.getList().get(k).getMinValue()) {
                            break;
                        } else if (reportTarget.getList().get(k).getFmaxValue().floatValue()  < lowLimit.floatValue()  || reportTarget.getList().get(k).getFmaxValue().floatValue()  > overLimit.floatValue() ) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else if (reportTarget.getList().get(k).getMinValue().floatValue()  < lowLimit.floatValue()  || reportTarget.getList().get(k).getMinValue().floatValue()  > overLimit.floatValue() ) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else {
                            reportTarget.setPass(EnumPass.PASS.getCode());
                        }
                    }
                    break;
                default:
                    break;
            }

            i++;
            list.add(reportTarget);
        }
    }

    @PostMapping("getHistoryTableData")
    @ResponseBody
    public HttpResult getHistoryTableData(String startTime, String endTime, String lineId, String type, String index, String harmonicInHarms) {
        String[] arrays = lineId.split(",");
        String[] array = type.split(",");
        String[] indexs;
        String[] harmonicInHarm;
        int[] lineIds = new int[arrays.length];
        int[] types = new int[array.length];
        int[] inde = new int[1];
        int[] inharm = new int[1];
        HttpResult httpResult = new HttpResult();

        for (int i = 0; i < arrays.length; i++) {
            lineIds[i] = Integer.parseInt(arrays[i]);
        }

        for (int i = 0; i < array.length; i++) {
            types[i] = Integer.parseInt(array[i]);
        }

        if (!index.equals("")) {
            indexs = index.split(",");
            inde = new int[indexs.length];

            //xuyang_update 对传入参数进行正则判断
            for (int i = 0; i < inde.length; i++) {
                String pattern = "^\\+?[1-9][0-9]*$";
                if (!Pattern.matches(pattern, String.valueOf(indexs[i]))) {
                    httpResult.setBody("");
                    httpResult.setCode(500);
                    httpResult.setMessage("参数异常");
                    return httpResult;
                } else {
                    inde[i] = Integer.parseInt(indexs[i]);
                }
            }
        }

        if (harmonicInHarms != null && !harmonicInHarms.equals("")) {
            harmonicInHarm = harmonicInHarms.split(",");
            inharm = new int[harmonicInHarm.length];

            //xuyang_update 对传入参数进行正则判断
            for (int i = 0; i < inharm.length; i++) {
                String pattern = "^\\+?[1-9][0-9]*$";
                if (!Pattern.matches(pattern, String.valueOf(harmonicInHarm[i]))) {
                    httpResult.setBody("");
                    httpResult.setCode(500);
                    httpResult.setMessage("参数异常");
                    return httpResult;
                } else {
                    inharm[i] = Integer.parseInt(harmonicInHarm[i]);
                }
            }
        }

        Condition tempCondition = new Condition(appConfig);
        List<HistoryTableData> list = new ArrayList<>();
        TransformTime transformTime = new TransformTime(startTime, endTime);
        try {
            transformTime.string2Date();
        } catch (Exception e) {
            httpResult.setBody(null);
            httpResult.setCode(500);
            httpResult.setMessage("前台时间解析不正确");
            return httpResult;
        }
        tempCondition.setStart(transformTime.getStart());
        tempCondition.setEnd(transformTime.getEnd());
        tempCondition.setB();
        String userId = TokenManager.getUserId();
        String key = userId + "DeviceControllergetHistoryTableData";
        saveConditionData(tempCondition, key);
        for (int j = 0; j < lineIds.length; j++) {
            tempCondition = getConditionData(key);
            tempCondition.setPointIndex(lineIds[j]);
            HistoryTableData historyTableData = new HistoryTableData();
            MachineAccount machineAccount = lineService.getLineName(lineIds[j]);
            historyTableData.setName(machineAccount.getName());
            historyTableData.setPttype(machineAccount.getPttype());
            historyTableData.setLineId(lineIds[j]);
            historyTableData.setBdName(machineAccount.getSubName());
            historyTableData.setVoltage(machineAccount.getScale());
            OverLimit over = overLimitMapper.selectByPrimaryKey((long) lineIds[j]);
            OverLimitInfo overLimitInfo;
            try {
                if (over == null) {
                    cOverlimit.addOverLimit(lineIds[j], machineAccount.getScale());
                }
            } catch (Exception e) {
                break;
            }
            overLimitInfo = getOverLimitDataService.getOverLimitData(tempCondition); //获取必要参数
            tempCondition.setCount(overLimitInfo.getCount());
            tempCondition.setPltCount(overLimitInfo.getPltCount());
            tempCondition.setPstCount(overLimitInfo.getPstCount());
            saveConditionData(tempCondition, key);
            //电压下偏差
            Float low = overLimitInfo.getOverLimitRate().get(0).getUvoltageDev();
            for (int i = 0; i < types.length; i++) {
                HistoryTableData.data data;
                List<ReportTarget> list1;
                Condition condition = getConditionData(key);
                switch (types[i]) {
                    case 21: //电流有效值
                        data = new HistoryTableData().new data();
                        list1 = new ArrayList<>();
                        data.setTargetName("电流有效值");
                        data.setUnit("A");
                        data.setTypeId(21);
                        transformData(list1, getVirtualDataService.getVirtualData(condition, "i"), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 11: //相电压有效值
                        data = new HistoryTableData().new data();
                        data.setTargetName("相电压有效值");
                        data.setUnit("kV");
                        data.setTypeId(11);
                        list1 = new ArrayList<>();
                        transformData(list1, getVirtualDataService.getVirtualData(condition, "v"), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 12: //线电压有效值
                        data = new HistoryTableData().new data();
                        data.setTargetName("线电压有效值");
                        data.setUnit("kV");
                        data.setTypeId(12);
                        list1 = new ArrayList<>();
                        transformData(list1, getVirtualDataService.getVVirtualData(condition), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, true, low);
                        data.setList(list1);
                        data.getList().get(0).getList().get(0).setPhaseType("AB");
                        data.getList().get(0).getList().get(1).setPhaseType("BC");
                        data.getList().get(0).getList().get(2).setPhaseType("CA");
                        historyTableData.setData(data);
                        break;
                    case 51: //有功功率
                        data = new HistoryTableData().new data();
                        data.setTargetName("三相有功功率");
                        data.setUnit("kW");
                        data.setTypeId(51);
                        list1 = new ArrayList<>();
                        transformData(list1, getPowerDataService.getPower(condition, "P"), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 52: //无功功率
                        data = new HistoryTableData().new data();
                        data.setTargetName("三相无功功率");
                        data.setUnit("kVar");
                        data.setTypeId(52);
                        list1 = new ArrayList<>();
                        transformData(list1, getPowerDataService.getPower(condition, "Q"), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 53: //视在功率
                        data = new HistoryTableData().new data();
                        data.setTargetName("三相视在功率");
                        data.setUnit("kVA");
                        data.setTypeId(53);
                        list1 = new ArrayList<>();
                        transformData(list1, getPowerDataService.getPower(condition, "S"), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 61: //短时电压闪变
                        data = new HistoryTableData().new data();
                        data.setTargetName("短时电压闪变");
                        data.setUnit("/");
                        data.setTypeId(61);
                        list1 = new ArrayList<>();
                        transformData(list1, getFlickerDataService.getPFlickerData(condition), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 62: //长时电压闪变
                        data = new HistoryTableData().new data();
                        data.setTargetName("长时电压闪变");
                        data.setUnit("/");
                        data.setTypeId(62);
                        list1 = new ArrayList<>();
                        transformData(list1, getFlickerDataService.getLLFlickerData(condition), new ArrayList<Pass>() {{
                            add(new Pass(overLimitInfo.getOverLimitRate().get(0).getFlicker(), EnumPass.MAX.getCode()));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 17: //电压总谐波畸变率
                        data = new HistoryTableData().new data();
                        data.setTargetName("电压总谐波畸变率");
                        data.setUnit("%");
                        data.setTypeId(17);
                        list1 = new ArrayList<>();
                        transformData(list1, getDistortionDataService.getDistortionData(condition, "V"), new ArrayList<Pass>() {{
                            add(new Pass(overLimitInfo.getOverLimitRate().get(0).getUaberrance(), EnumPass.CP95.getCode()));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 22: //电流总谐波畸变率
                        data = new HistoryTableData().new data();
                        data.setTargetName("电流总谐波畸变率");
                        data.setUnit("%");
                        data.setTypeId(22);
                        list1 = new ArrayList<>();
                        transformData(list1, getDistortionDataService.getDistortionData(condition, "I"), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 23: //负序电流
                        data = new HistoryTableData().new data();
                        data.setTargetName("负序电流");
                        data.setUnit("A");
                        data.setTypeId(23);
                        list1 = new ArrayList<>();
                        transformData(list1, getInegDataService.getInegData(condition), new ArrayList<Pass>() {{
                            add(new Pass(overLimitInfo.getOverLimitRate().get(0).getiNeg(), EnumPass.MAX.getCode()));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 13: //电压偏差
                        data = new HistoryTableData().new data();
                        data.setTargetName("电压偏差");
                        data.setUnit("%");
                        data.setTypeId(13);
                        list1 = new ArrayList<>();
                        transformData(list1, getVdeviationDataService.getVdeviationData(condition), new ArrayList<Pass>() {{
                            add(new Pass(overLimitInfo.getOverLimitRate().get(0).getVoltageDev(), EnumPass.MAX_AND_MIN.getCode()));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 31: //频率
                        data = new HistoryTableData().new data();
                        data.setTargetName("频率偏差");
                        data.setUnit("Hz");
                        data.setTypeId(31);
                        list1 = new ArrayList<>();
                        transformData(list1, getFrequencyDataService.getFreqData(condition), new ArrayList<Pass>() {{
                            add(new Pass(overLimitInfo.getOverLimitRate().get(0).getFreqDev(), EnumPass.MAX.getCode()));
                        }}, false, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 16://电压不平衡
                        List<ReportValue> list2 = getThreephaseDataService.getThreephase(condition);
                        data = new HistoryTableData().new data();
                        data.setTargetName("正序电压");
                        data.setUnit("kV");
                        data.setTypeId(16);
                        list1 = new ArrayList<>();
                        transformData(list1, list2.subList(1, 2), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, false, low);
                        data.setList(list1);
                        historyTableData.setData(data);

                        data = new HistoryTableData().new data();
                        data.setTargetName("负序电压");
                        data.setUnit("V");
                        list1 = new ArrayList<>();
                        transformData(list1, list2.subList(2, 3), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, false, low);
                        data.setList(list1);
                        historyTableData.setData(data);

                        data = new HistoryTableData().new data();
                        data.setTargetName("零序电压");
                        data.setUnit("V");
                        list1 = new ArrayList<>();
                        transformData(list1, list2.subList(3, 4), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, false, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 15://三相电压不平衡度
                        data = new HistoryTableData().new data();
                        List<ReportValue> listResult = getThreephaseDataService.getHThreephase(condition);
                        data.setTargetName("三相电压不平衡度");
                        data.setUnit("%");
                        data.setTypeId(15);
                        list1 = new ArrayList<>();
                        transformData(list1, listResult, new ArrayList<Pass>() {{
                            add(new Pass(overLimitInfo.getOverLimitRate().get(0).getUbalance(), EnumPass.CP95.getCode()));
                        }}, false, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                    case 41: //谐波电压含有率
                        for (int k = 0; k < inde.length; k++) {
                            condition.setTimes(inde[k]);
                            data = new HistoryTableData().new data();
                            List<ReportValue> list3 = getVoltageRateService.getHVoltageRate(condition);
                            data.setTargetName(inde[k] + "次谐波电压");
                            data.setTimeId(inde[k]);
                            data.setUnit("%");
                            data.setTypeId(41);
                            list1 = new ArrayList<>();
                            int m = inde[k] - 2;
                            transformData(list1, list3, new ArrayList<Pass>() {{
                                add(new Pass(overLimitInfo.getOverLimitRate().get(0).getVHarmList().get(m), EnumPass.CP95.getCode()));
                            }}, false, low);
                            data.setList(list1);
                            historyTableData.setData(data);
                        }
                        break;
                    case 42://谐波电流幅值
                        for (int k = 0; k < inde.length; k++) {
                            condition.setTimes(inde[k]);
                            data = new HistoryTableData().new data();
                            List<ReportValue> list3 = getICurrentService.getHICurrent(condition);
                            data.setTargetName(inde[k] + "次谐波电流");
                            data.setTimeId(inde[k]);
                            data.setUnit("%");
                            data.setTypeId(42);
                            list1 = new ArrayList<>();
                            int m = inde[k] - 2;
                            transformData(list1, list3, new ArrayList<Pass>() {{
                                add(new Pass(overLimitInfo.getOverLimitRate().get(0).getIHarmList().get(m), EnumPass.CP95.getCode()));
                            }}, false, low);
                            data.setList(list1);
                            historyTableData.setData(data);
                        }

                        break;
                    case 43://间谐波电压含有率
                        for (int k = 0; k < inharm.length; k++) {
                            condition.setTimes(inharm[k]);
                            data = new HistoryTableData().new data();
                            List<ReportValue> list3 = getInharmService.getHInharm(condition);
                            data.setTargetName(inharm[k] - 0.5 + "次间谐波电压含有率");
                            data.setTimeId(inharm[k]);
                            data.setUnit("%");
                            data.setTypeId(43);
                            list1 = new ArrayList<>();
                            int m = inharm[k];
                            transformData(list1, list3, new ArrayList<Pass>() {{
                                add(new Pass(overLimitInfo.getOverLimitRate().get(0).getInHarmList().get(m-1), EnumPass.CP95.getCode()));
                            }}, false, low);
                            data.setList(list1);
                            historyTableData.setData(data);
                        }

                        break;
                    case 63://电压波动
                        data = new HistoryTableData().new data();
                        data.setTargetName("电压波动");
                        data.setUnit("%");
                        data.setTypeId(63);
                        list1 = new ArrayList<>();
                        transformData(list1, getVoltage.getVoltageData(condition), new ArrayList<Pass>() {{
                            add(new Pass(null));
                        }}, true, low);
                        data.setList(list1);
                        historyTableData.setData(data);
                        break;
                }
            }

            list.add(historyTableData);
        }

        httpResult.setBody(list);
        httpResult.setCode(200);
        httpResult.setMessage("获取数据成功");
        return httpResult;
    }

    @PostMapping("qualityAssess")
    @ResponseBody
    public HttpResult qualityAssess(HttpServletRequest request, String startTime, String endTime, Long lineIndex) {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "qualityAssess");
        if (!datePojo.getValidity() || lineIndex == null) {
            result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
            return result;
        }
        PowerQualityData data;
        try {
            data = assesService.qualityAssess(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            result = PubUtils.assignmentResult(data, 200, "监测点获取电能质量评估数据成功");
            userLog.getLog("查询稳态质量评估", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "监测点获取电能质量评估数据失败");
            userLog.getLog("查询稳态质量评估", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        }
        return result;
    }

    @PostMapping("qualityAssessTB")
    @ResponseBody
    public HttpResult qualityAssessTB(String startTime, String endTime, String laststartTime, String lastendTime, Long lineIndex) {
        HttpResult result;
        DatePojo datePojo;
        DatePojo lastdatePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "qualityAssessTB");
        lastdatePojo = PubUtils.validateDate(laststartTime, lastendTime, "qualityAssessTB");
        if (!datePojo.getValidity() || !lastdatePojo.getValidity() || lineIndex == null) {
            result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
            return result;
        }
        PowerQualityData data;
        try {
            data = assesService.qualityAssessTB(datePojo.getStartTime(), datePojo.getEndTime(), lastdatePojo.getStartTime(), lastdatePojo.getEndTime(), lineIndex);
            result = PubUtils.assignmentResult(data, 200, "监测点获取电能质量评估数据成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 200, "监测点获取电能质量评估数据失败");
        }
        return result;
    }

    @RequestMapping(value = "getZj", method = RequestMethod.POST)
    @ResponseBody
    public List<EventDetail> getzj(String obj) {
        List<EventDetail> eventDetails = new ArrayList<>();
        JSONArray json = JSONArray.fromObject(obj); //使用net.sf.json.JSONObject对象来解析json
        String o = (String) json.getJSONObject(0).get("condition");
        String[] condition = null;
        Long lineIndex = null;
        String startTime = null;
        String endTime = null;
        String start = (String) json.getJSONObject(0).get("start");
        String end = (String) json.getJSONObject(0).get("end");
        condition = o.split(",");
        String point = (String) json.getJSONObject(0).get("point");
        try {
            String[] pointid = null;
            pointid = point.split(",");
            for (int j = 0; j < pointid.length; j++) {
                lineIndex = Long.valueOf(pointid[j]);
                for (int i = 0; i < condition.length; i++) {
                    Long startT = (Long) json.getJSONObject(0).get("startTime");
                    Date date = new Date(startT);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    startTime = sdf.format(date);                      //获取时间段的开始时间
                    Long endT = (Long) json.getJSONObject(0).get("endTime");
                    Date date1 = new Date(endT);
                    endTime = sdf.format(date1);
                    eventDetails = eventDetailService.queryZj(startTime, endTime, start,
                            end, lineIndex);
                }
            }
        } catch (Exception e) {
            logger.error("获取暂降事件异常，异常是" + e.toString());
        }
        return eventDetails;
    }

    //谐波电流幅值
    @ResponseBody
    @RequestMapping(value = "getHarmI", method = RequestMethod.POST)
    public HttpResult getHarmI(HttpServletRequest request, @Param("lineId") long lineId,
                               @Param("startTime") String startTime, @Param("endTime") String endTime, String type) throws AccountException {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getHarmI");
        Condition tempCondition = new Condition();
        TransformTime TransformTime = new TransformTime(startTime, endTime);
        try {
            TransformTime.string2Date();
        } catch (Exception e2) {
            logger.error("转换时间发生异常，异常是" + e2.getMessage());
        }
        tempCondition.setStart(TransformTime.getStart());
        tempCondition.setEnd(TransformTime.getEnd());
        tempCondition.setPointIndex((int) lineId);
        int day = appConfig.getReportday();
        int days = (int) ((TransformTime.getEnd().getTime() - TransformTime.getStart().getTime()) / (1000 * 3600 * 24));
        Boolean b = (days > day) ? new Boolean(false) : new Boolean(true);
        tempCondition.setB(b);
        OverLimitInfo overLimitInfo = getOverLimitDataService.getOverLimitData(tempCondition);
        tempCondition.setCount(overLimitInfo.getCount());
        tempCondition.setPltCount(overLimitInfo.getPltCount());
        String userId = TokenManager.getUserId();
        String key = userId + "DeviceControllergetHarmI";
        saveConditionData(tempCondition, key);
        try {
            if (!datePojo.getValidity()) {
                result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
                return result;
            }
            List<List> harmonics;
            if (type.equals("0")) {
                harmonics = harmIService.getHarmI(lineId, datePojo.getStartTime(), datePojo.getEndTime());
            } else {
                harmonics = harmIService.getoffHarmI(getConditionData(key));
            }
            if (harmonics.isEmpty()) {
                result = PubUtils.assignmentResult(null, 500, "没有获取到历史谐波频谱数据");
                logger.error("获取历史谐波频谱数据失败");
                userLog.getLog("查询历史谐波频谱数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            } else {
                List<String> a = new ArrayList<>();
                String temp = "";
                for (int j = 0; j < 50; j++) {
                    if (j == 0) {
                        a.add("国标限值(A)");
                    } else if (j > 0 && j < 25) {
                        Example example = new Example(OverLimit.class);
                        example.createCriteria().andEqualTo("myIndex", lineId);
                        List<OverLimit> overLimit = overLimitMapper.selectByExample(example);
                        if (!overLimit.isEmpty()) {
                            for (OverLimit overLimit1 : overLimit) {
                                switch (j) {
                                    case 1:
                                        temp = overLimit1.getIharm_2() + "";
                                        break;
                                    case 2:
                                        temp = overLimit1.getIharm_3() + "";
                                        break;
                                    case 3:
                                        temp = overLimit1.getIharm_4() + "";
                                        break;
                                    case 4:
                                        temp = overLimit1.getIharm_5() + "";
                                        break;
                                    case 5:
                                        temp = overLimit1.getIharm_6() + "";
                                        break;
                                    case 6:
                                        temp = overLimit1.getIharm_7() + "";
                                        break;
                                    case 7:
                                        temp = overLimit1.getIharm_8() + "";
                                        break;
                                    case 8:
                                        temp = overLimit1.getIharm_9() + "";
                                        break;
                                    case 9:
                                        temp = overLimit1.getIharm_10() + "";
                                        break;
                                    case 10:
                                        temp = overLimit1.getIharm_11() + "";
                                        break;
                                    case 11:
                                        temp = overLimit1.getIharm_12() + "";
                                        break;
                                    case 12:
                                        temp = overLimit1.getIharm_13() + "";
                                        break;
                                    case 13:
                                        temp = overLimit1.getIharm_14() + "";
                                        break;
                                    case 14:
                                        temp = overLimit1.getIharm_15() + "";
                                        break;
                                    case 15:
                                        temp = overLimit1.getIharm_16() + "";
                                        break;
                                    case 16:
                                        temp = overLimit1.getIharm_17() + "";
                                        break;
                                    case 17:
                                        temp = overLimit1.getIharm_18() + "";
                                        break;
                                    case 18:
                                        temp = overLimit1.getIharm_19() + "";
                                        break;
                                    case 19:
                                        temp = overLimit1.getIharm_20() + "";
                                        break;
                                    case 20:
                                        temp = overLimit1.getIharm_21() + "";
                                        break;
                                    case 21:
                                        temp = overLimit1.getIharm_22() + "";
                                        break;
                                    case 22:
                                        temp = overLimit1.getIharm_23() + "";
                                        break;
                                    case 23:
                                        temp = overLimit1.getIharm_24() + "";
                                        break;
                                    case 24:
                                        temp = overLimit1.getIharm_25() + "";
                                        break;
                                }
                            }
                        } else {
                            temp = "/";
                        }
                        a.add(temp);
                    } else {
                        a.add("/");
                    }
                }
                harmonics.add(a);
                result = PubUtils.assignmentResult(harmonics, 200, "获取历史谐波频谱数据成功");
                logger.info("获取历史谐波频谱数据成功");
                userLog.getLog("查询历史谐波频谱数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            }
        } catch (Exception e) {
            logger.error("获取历史谐波频谱数据异常，异常是" + e.toString());
            userLog.getLog("查询历史谐波频谱数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            result = PubUtils.assignmentResult(null, 500, "获取历史谐波频谱数据失败");
        }
        return result;

    }

    //谐波含有率
    @RequestMapping(value = "getHarmonic", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getHarmonic(HttpServletRequest request, @Param("lineId") long lineId,
                                  @Param("startTime") String startTime, @Param("endTime") String endTime, String type) throws AccountException {
        HttpResult result;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getHarmonic");

        Condition tempCondition = new Condition();
        TransformTime TransformTime = new TransformTime(startTime, endTime);
        try {
            TransformTime.string2Date();
        } catch (Exception e2) {
            logger.error("");
        }
        tempCondition.setStart(TransformTime.getStart());
        tempCondition.setEnd(TransformTime.getEnd());
        tempCondition.setPointIndex((int) lineId);
        List<TransformTime> exc = new ArrayList<>();
        int day = appConfig.getReportday();
        int days = (int) ((TransformTime.getEnd().getTime() - TransformTime.getStart().getTime()) / (1000 * 3600 * 24));
        Boolean b = (days > day) ? new Boolean(false) : new Boolean(true);
        tempCondition.setB(b);
        OverLimitInfo overLimitInfo = getOverLimitDataService.getOverLimitData(tempCondition);
        tempCondition.setCount(overLimitInfo.getCount());
        tempCondition.setPltCount(overLimitInfo.getPltCount());
        String userId = TokenManager.getUserId();
        String key = userId + "DeviceControllergetHarmonic";
        saveConditionData(tempCondition, key);
        try {
            if (!datePojo.getValidity()) {
                result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
                return result;
            }
            List<List> harmonics;
            if (type.equals("0")) {
                harmonics = harmonicService.getHarmonic(lineId, datePojo.getStartTime(), datePojo.getEndTime());
            } else {
                harmonics = harmonicService.getoffHarmonic(getConditionData(key));
            }
            if (harmonics.isEmpty()) {
                result = PubUtils.assignmentResult(null, 500, "没有获取到历史谐波频谱数据");
                logger.error("获取用户信息失败");
                userLog.getLog("查询历史谐波频谱数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            } else {
                List<String> a = new ArrayList<>();
                String temp = "";
                for (int j = 0; j < 50; j++) {
                    if (j == 0) {
                        a.add("国标限值(%)");
                    } else if (j > 0 && j < 25) {
                        Example example = new Example(OverLimit.class);
                        example.createCriteria().andEqualTo("myIndex", lineId);
                        List<OverLimit> overLimit = overLimitMapper.selectByExample(example);
                        if (!overLimit.isEmpty()) {
                            for (OverLimit overLimit1 : overLimit) {
                                switch (j) {
                                    case 1:
                                        temp = overLimit1.getUharm_2() + "";
                                        break;
                                    case 2:
                                        temp = overLimit1.getUharm_3() + "";
                                        break;
                                    case 3:
                                        temp = overLimit1.getUharm_4() + "";
                                        break;
                                    case 4:
                                        temp = overLimit1.getUharm_5() + "";
                                        break;
                                    case 5:
                                        temp = overLimit1.getUharm_6() + "";
                                        break;
                                    case 6:
                                        temp = overLimit1.getUharm_7() + "";
                                        break;
                                    case 7:
                                        temp = overLimit1.getUharm_8() + "";
                                        break;
                                    case 8:
                                        temp = overLimit1.getUharm_9() + "";
                                        break;
                                    case 9:
                                        temp = overLimit1.getUharm_10() + "";
                                        break;
                                    case 10:
                                        temp = overLimit1.getUharm_11() + "";
                                        break;
                                    case 11:
                                        temp = overLimit1.getUharm_12() + "";
                                        break;
                                    case 12:
                                        temp = overLimit1.getUharm_13() + "";
                                        break;
                                    case 13:
                                        temp = overLimit1.getUharm_14() + "";
                                        break;
                                    case 14:
                                        temp = overLimit1.getUharm_15() + "";
                                        break;
                                    case 15:
                                        temp = overLimit1.getUharm_16() + "";
                                        break;
                                    case 16:
                                        temp = overLimit1.getUharm_17() + "";
                                        break;
                                    case 17:
                                        temp = overLimit1.getUharm_18() + "";
                                        break;
                                    case 18:
                                        temp = overLimit1.getUharm_19() + "";
                                        break;
                                    case 19:
                                        temp = overLimit1.getUharm_20() + "";
                                        break;
                                    case 20:
                                        temp = overLimit1.getUharm_21() + "";
                                        break;
                                    case 21:
                                        temp = overLimit1.getUharm_22() + "";
                                        break;
                                    case 22:
                                        temp = overLimit1.getUharm_23() + "";
                                        break;
                                    case 23:
                                        temp = overLimit1.getUharm_24() + "";
                                        break;
                                    case 24:
                                        temp = overLimit1.getUharm_25() + "";
                                        break;
                                }
                            }
                        } else {
                            temp = "/";
                        }
                        a.add(temp);
                    } else {
                        a.add("/");
                    }
                }
                harmonics.add(a);
                result = PubUtils.assignmentResult(harmonics, 200, "获取历史谐波频谱数据成功");
                logger.info("获取历史谐波频谱数据成功");
                userLog.getLog("查询历史谐波频谱数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            }
        } catch (Exception e) {
            logger.error("获取历史谐波频谱数据异常，异常是" + e.toString());
            userLog.getLog("查询历史谐波频谱数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            result = PubUtils.assignmentResult(null, 500, "获取历史谐波频谱数据失败");
        }
        return result;
    }

    /**
     * @autor denghuajun
     * @Date 2018/8/10 10:07
     * @annotation 查询所有供电公司和厂家
     */
    @RequestMapping(value = "getGdname", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getGdname(HttpSession session, String lineIndex)
            throws
            JsonProcessingException {
        HttpResult result = null;
        List<DeviceDetail> list = new ArrayList<DeviceDetail>();
        List<List> s = new ArrayList<List>();
        try {
            if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
                session.removeAttribute("line_index");
            }
            if (lineIndex == null || lineIndex.length() == 0) {
                list = deviceService.getGdname();
            } else {
                list = deviceService.queryDeviceDetailById(lineIndex);
            }
            result = PubUtils.assignmentResult(list, 200, "获取供电公司信息成功");
        } catch (Exception e) {
            logger.error("获取供电公司和厂家异常，异常是" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "获取供电公司信息失败");
        }
        return result;

    }

    @RequestMapping(value = "getManufacturers", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getManufacturers(HttpSession session, String lineIndex)
            throws
            JsonProcessingException {
        HttpResult result = null;
        List<DeviceDetail> list = new ArrayList<DeviceDetail>();
        List<List> s = new ArrayList<List>();
        try {
            if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
                session.removeAttribute("line_index");
            }
            if (lineIndex == null || lineIndex.length() == 0) {
                list = deviceService.getManufacturers();
            } else {
                list = deviceService.queryDeviceDetailById(lineIndex);
            }
            result = PubUtils.assignmentResult(list, 200, "获取厂家信息成功");
        } catch (Exception e) {
            logger.error("获取厂家信息异常，异常是" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "获取厂家信息失败");
        }
        return result;

    }


    /***
     * 终端管理详情
     * @return
     */
    @RequestMapping(value = "getDeviceDetail", method = RequestMethod.POST)
    @ResponseBody
    public String getDeviceDetail(HttpServletRequest request, HttpSession session, String status, String devflag, String gdName, String
            manufacturer, String lineIndex, String area,String type)
            throws
            JsonProcessingException, AccountException {
        if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
            session.removeAttribute("line_index");
        }
        List<DeviceDetail> result = new ArrayList<DeviceDetail>();
        List<List> s = new ArrayList<List>();

        try {

            if (status == null || status.isEmpty()) {
                status = "";
            }
            status = "%" + status + "%";
            if (devflag == null || devflag.isEmpty()) {
                devflag = "";
            }
            devflag = "%" + devflag + "%";
            if (gdName == null || gdName.isEmpty()) {
                gdName = "";
            }
            gdName = "%" + gdName + "%";
            if (manufacturer == null || manufacturer.isEmpty()) {
                manufacturer = "";
            }
            manufacturer = "%" + manufacturer + "%";
            if (lineIndex == null || lineIndex.length() == 0) {
                result = deviceService.getDeviceDetails(status, devflag, gdName, manufacturer, area,type);
            } else {
                result = deviceService.queryDeviceDetailById(lineIndex);
            }
            if (result == null) {
                return null;
            }
            int j = 0;
            for (int i = 0; i < result.size(); i++) {
                GDInformation gdInformation = new GDInformation();
                gdInformation.setGdIndex(result.get(i).getGdName());
                gdInformation = gdInforMapper.selectOne(gdInformation);

                List<String> a = new ArrayList<String>();
                j = j + 1;
                a.add(String.valueOf(j));
                a.add(String.valueOf(gdInformation.getName()));
                a.add(result.get(i).getSubName());
                a.add(result.get(i).getName());
                a.add(result.get(i).getTime());
                a.add(result.get(i).getManufacturer());
                a.add(String.valueOf(result.get(i).getDevType()));
                a.add(result.get(i).getIP());
                a.add(String.valueOf(result.get(i).getPortid()));
                a.add(result.get(i).getDevflag());
                a.add(result.get(i).getStatus());
                a.add(result.get(i).getUpdatetime());
                if (result.get(i).getEvaluate() == null) {
                    a.add("差");
                } else if (Double.parseDouble(result.get(i).getEvaluate()) >= 90) {
                    a.add("优");
                } else if (Double.parseDouble(result.get(i).getEvaluate()) < 90 && Double.parseDouble(result.get(i).getEvaluate()) >= 60) {
                    a.add("良");
                } else {
                    a.add("差");
                }
                a.add("<button type='button' class='btn  btn-primary glyphicon glyphicon-edit' style='margin-right:10px;' title='更改终端状态' href='javascript:void(0);' onclick='updateDevflag(\"" + result.get(i).getDevIndex() + "\")' ></button>");
                s.add(a);
            }
            userLog.getLog("查询终端管理详情", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            userLog.getLog("查询终端管理详情", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("终端管理详情获取异常，异常是" + e.toString());
        }
        return objectMapper.writeValueAsString(s);
    }

    //根据终端名查询该终端
    @ResponseBody
    @RequestMapping(value = "getDevflag", method = RequestMethod.POST)
    public Device getDevflag(String name) {
        Device device = new Device();
        try {
            device = deviceService.getDevflag(Long.valueOf(name));
        } catch (Exception e) {
            logger.error("查询终端异常，异常是" + e.toString());
        }
        return device;
    }

    //修改终端状态
    @ResponseBody
    @RequestMapping(value = "updateDevice", method = RequestMethod.POST)
    public int updateDevice(HttpServletRequest request, @Param("name") String name, @Param("devflag") Integer devflag,@Param("terminalDescribe")String terminalDescribe) throws AccountException {
        int flag = 0;
        try {
            String ip = PubUtils.getIpAddr(request);
            String username = TokenManager.getToken().getLoginName();

            byte[] value = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
            String key = SerializeUtil.deserialize(value, String.class);
            if (key.equals("success")) {
                flag = deviceService.updateDevice(Integer.valueOf(name), devflag,terminalDescribe);
                userLog.getLog("修改终端状态", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            } else {
                flag = 500;
            }

            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
        } catch (Exception e) {
            logger.error("修改终端状态异常，异常是" + e.toString());
            userLog.getLog("修改终端状态", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            flag = 0;
        }
        return flag;
    }


    /**
     * 通讯测试树
     */
    /**
     * 终端树
     *
     * @param
     * @param session
     * @return
     */
    @RequestMapping(value = "runtimetree", method = RequestMethod.POST)
    @ResponseBody
    public List<Tree> runtimetree(HttpSession session) {
        if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
            session.removeAttribute("line_index");
        }

        User user = TokenManager.getToken();
        List<Tree> result = null;
        try {
            result = getDeviceTree.getRunTimeTreedata(user.getLoginName());
        } catch (Exception e) {
            logger.error("获取终端树异常，异常是" + e.toString());
        }
        return result;
    }

    @RequestMapping(value = "getSelName", method = RequestMethod.POST)
    @ResponseBody
    public List<DeviceDetail> getSelName(@Param(value = "name") String name) {
        List<DeviceDetail> deviceDetails = new ArrayList<>();
        try {
            deviceDetails = deviceService.getSelName(name);
        } catch (Exception e) {
            logger.error("获取名称异常，异常是" + e.toString());
        }
        return deviceDetails;
    }


    @RequestMapping(value = "websocketon", method = RequestMethod.POST)
    @ResponseBody
    public String websocketon(HttpServletResponse response, HttpServletRequest request) {
        String result = "";
        try {
            result = appConfig.getWebsocket();
        } catch (Exception e) {
            logger.error("访问socket异常，异常是" + e.toString());
        }
        return result;
    }

    @RequestMapping(value = "socketon", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult socketon(HttpServletRequest request,Integer lineIndex) {
        String result = "";
        try {
            result = realTimeDataService.realTimeData(lineIndex);
            if("请求成功".equals(result)){
                userLog.getLog("查询实时数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
                return PubUtils.assignmentResult(null,200,result);
            }else {
                return PubUtils.assignmentResult(null,500,result);
            }
        } catch (Exception e) {
            userLog.getLog("查询实时数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("socket异常，异常是" + e.toString());
            return PubUtils.assignmentResult(null,500,"查询实时数据异常");
        }

    }

    /**
     * 实时数据心跳
     * @author cdf
     * @date 2021/8/9
     */
    @RequestMapping(value = "heartSocketon", method = RequestMethod.GET)
    @ResponseBody
    public HttpResult heartSocketon(Integer lineIndex) {
        String res= null;
        res=realTimeDataService.heartRealTimeData(lineIndex);
        if("实时数据心跳请求成功".equals(res)){
            return PubUtils.assignmentResult(null,200,res);
        }else{
            return PubUtils.assignmentResult(null,500,res);
        }
    }

    /**
     * 关闭实时数据心跳
     * @author cdf
     * @date 2021/8/9
     */
    @RequestMapping(value = "closeRealTimeData", method = RequestMethod.GET)
    @ResponseBody
    public HttpResult closeRealTimeData(Integer lineIndex) {
        System.out.println("用户关闭"+lineIndex);
        String res = realTimeDataService.closeRealTimeData(lineIndex);
        return PubUtils.assignmentResult(null,200,res);
    }

    //波形补招
    @RequestMapping(value = "socketonWave", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult socketonWave(HttpServletRequest request, String type, Long LineId, Long ComtradeName) {
        String result = "";
        try {
            result = versionService.sentLineWave(type, LineId, ComtradeName);
            if("波形补招命令接收成功".equals(result)){
                userLog.getLog("波形补招", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
                return PubUtils.assignmentResult(null,200,result);
            }else{
                return PubUtils.assignmentResult(null,500,result);
            }

        } catch (Exception e) {
            userLog.getLog("波形补招", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("socket异常，异常是" + e.getMessage());
            return PubUtils.assignmentResult(null,500,"波形补招异常");
        }
    }

    //修改终端状态
    @ResponseBody
    @RequestMapping(value = "getLineInfo", method = RequestMethod.POST)
    public Line getLineInfo(String lineIndex) {
        Line result = new Line();
        try {
            result = lineMapper.selectByPrimaryKey(Long.valueOf(lineIndex));
        } catch (Exception e) {
            logger.error("修改终端状态异常，异常是" + e.toString());
        }
        return result;
    }

    //获取离线监测点数据起始时间
    @ResponseBody
    @RequestMapping(value = "getSETime", method = RequestMethod.POST)
    public HttpResult getSETime(Long lineIndex) {
        HttpResult result;
        List<OfflLog> tmp = new ArrayList<>();
        try {
            tmp = offlLogMapper.getSETimeByIndex(lineIndex);
            if (tmp.size() == 0 || tmp.get(0).getStartTime().toString().isEmpty() || tmp.get(0).getEndTime().toString().isEmpty()) {
                result = PubUtils.assignmentResult(null, 500, "未找到数据!");
            } else {
                result = PubUtils.assignmentResult(tmp, 200, "获取时间成功!");
            }
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "获取时间失败!");
            logger.error("修改终端状态异常，异常是" + e.toString());
        }
        return result;
    }

    /**
     * 获取谐波责任划分设备树
     */
    @RequestMapping(value = "deviceTree", method = RequestMethod.POST)
    @ResponseBody
    public List<Tree> getDeviceTree() {
        List<Tree> result = deviceService.getOnlineDeviceTree();
        return result;
    }

    @ResponseBody
    @PostMapping("getMsgInfo")
    public HttpResult getMsgInfo(String start, String end, HttpServletRequest request) {
        HttpResult result = PubUtils.initResult(TokenManager.getToken().getLoginName(), request, LogTypeEnum.BUSSINESS.toString(), 0);
        DatePojo datePojo = PubUtils.validateDate(start, end, "getMsgInfo");

        if (!org.springframework.util.StringUtils.isEmpty(datePojo.getMsg())) {
            result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
            return result;
        }

        try {
            DeviceMapInfo deviceMapInfo = deviceService.getMsgInfo(datePojo.getStartTime(), datePojo.getEndTime());
            if (null == deviceMapInfo) {
                result = PubUtils.assignmentResultLog(null, 500, "获取终端在线率数据为空", "查询终端在线率", "成功", result);
            } else {
                result = PubUtils.assignmentResultLog(deviceMapInfo, 200, "获取终端在线率数据成功", "查询终端在线率", "成功", result);
            }
        } catch (Exception e) {
            logger.error("获取终端运行数据异常,异常为：" + e.toString());
            result = PubUtils.assignmentResultLog(null, 500, "获取终端在线率数据异常", "查询终端在线率", "失败", result);
        }

        return result;
    }

    @RequestMapping(value = "getselect", method = RequestMethod.POST)
    @ResponseBody
    public List<DicData> getselect(String dictypeName) {
        List<DicData> result = new ArrayList<>();
        try {
            result = deviceService.getdicdata(dictypeName);
        } catch (Exception e) {
            result = null;
        }

        return result;
    }

    @RequestMapping(value = "getUserAll", method = RequestMethod.POST)
    @ResponseBody
    public UserDetail getUserAll(String userIndex) {
        UserDetail result = new UserDetail();
        try {
            result = userMapper.getUserAll(userIndex);
        } catch (Exception e) {
            result = null;
        }

        return result;
    }

    /**
     * 9000在线监测点到处台账信息excel
     * @author cdf
     * @date 2021/3/5
     */
    @RequestMapping(value = "exportDev", method = RequestMethod.GET)
    @ResponseBody
    public HttpResult exportDev(HttpServletResponse response, HttpServletRequest request) {
        try {
             String wt = appConfig.getSysTypeWt();
             Integer res = excelReportService.getExportDev(response,request,wt);
             if(res!=1){
                return PubUtils.assignmentResult(null,500,"fail");
             }else {
                 return PubUtils.assignmentResult(null,200,"succeed");
             }
        } catch (Exception e) {
            return PubUtils.assignmentResult(null,500,"fail");
        }
    }


    /**
     * 9000在线监测点到处台账信息excel
     * @author cdf
     * @date 2021/3/5
     */
    @RequestMapping(value = "exportDevMain", method = RequestMethod.GET)
    public void exportDevMain(HttpServletResponse response, HttpServletRequest request) {
        try {
            excelReportService.getExportDevMain(response,request);
        } catch (Exception e) {
            logger.error("导出excle出错");
        }
    }

    /**
     * 保存condition数据
     *
     * @param condition 数据
     */
    private void saveConditionData(Condition condition, String key) {
        JSONObject conditionJson = JSONObject.fromObject(condition);
        jedisManager.saveValueByKey(RedisDB.LONG_TIME_QUERY, key, conditionJson.toString(), -1);
    }

    /**
     * 获取condition数据
     */
    private Condition getConditionData(String key) {
        String valueJson = jedisManager.getValueByKey(RedisDB.LONG_TIME_QUERY, key);
        JSONObject conditionJSONObject = JSONObject.fromObject(valueJson);
        return (Condition) JSONObject.toBean(conditionJSONObject, Condition.class);
    }

//    /***
//     * 终端状态更新列表
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "getLogsDetail")
//    public String getTerminalLogsDetail(HttpServletRequest request)
//            throws
//            JsonProcessingException, AccountException {
//        List<List> deviceLogDetail = new ArrayList<List>();
//        int systype = 0;//谐波系统
//        try {
//            deviceLogDetail = deviceService.getTerminalLogsDetail(systype);
//            if (deviceLogDetail == null) {
//                return null;
//            }
//
//            userLog.getLog("查询终端更改日志详情", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
//        } catch (Exception e) {
//            userLog.getLog("查询终端更改日志详情", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
//            logger.error("终端更改日志详情获取异常，异常是" + e.toString());
//        }
//        return objectMapper.writeValueAsString(deviceLogDetail);
//    }

    /**
     * 通过监测点id获取主接线图
     * @author cdf
     * @date 2023/5/30
     */
    @PostMapping(value = "queryWiringDiagram")
    @ResponseBody
    public HttpResult queryWiringDiagram(@RequestParam(value = "lineId") Integer lineId,HttpServletResponse response) {
        HttpResult httpResult;
        try {

            String result = lineService.queryWiringDiagram(lineId,response);
            if("查看主接线图失败".equals(result) || "暂无主接线图".equals(result)){
                httpResult = PubUtils.assignmentResult(null, 500, result);
            }else {
                httpResult = PubUtils.assignmentResult(result, 200, "查看主接线图成功");
            }
        } catch (Exception e) {
            logger.error("查看图片异常，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult(null, 500, "查看主接线图异常");
        }

        return httpResult;
    }
}
