package com.pqs9200.controller.business;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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 com.njcn.mapper.user.UserMapper;
import com.njcn.pojo.user.UserDetail;
import com.pqs9200.service.data.VersionService;
import org.apache.commons.lang3.StringUtils;
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.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.njcn.enums.LogTypeEnum;
import com.njcn.mapper.configuration.GDInforMapper;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.commons.WaveResponseBody;
import com.njcn.pojo.commons.area.Interval;
import com.njcn.pojo.commons.area.ReasonStatisc;
import com.njcn.pojo.commons.device.AnalyzeInfo;
import com.njcn.pojo.commons.device.Communication;
import com.njcn.pojo.commons.device.DeviceDetail;
import com.njcn.pojo.commons.device.DeviceMapInfo;
import com.njcn.pojo.commons.device.DeviceOnline;
import com.njcn.pojo.commons.device.EventCause;
import com.njcn.pojo.commons.device.EventChance;
import com.njcn.pojo.commons.device.EventDataList;
import com.njcn.pojo.commons.device.EventDensity;
import com.njcn.pojo.commons.device.EventTypeList;
import com.njcn.pojo.commons.device.LineInfo;
import com.njcn.pojo.commons.device.SbtjData;
import com.njcn.pojo.commons.device.Tree;
import com.njcn.pojo.configuration.Device;
import com.njcn.pojo.configuration.DicData;
import com.njcn.pojo.configuration.GDInformation;
import com.njcn.pojo.excel.CommonParamter;
import com.njcn.pojo.excel.SbycExcelBody;
import com.njcn.pojo.excel.ZjsjExcelBody;
import com.njcn.service.configuration.DeviceService;
import com.njcn.service.configuration.TreeService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.sso.pojo.user.User;
import com.njcn.utils.PubUtils;
import com.njcn.utils.SerializeUtil;
import com.njcn.utils.SocketClient;
import com.njcn.utils.redis.JedisManager;
import com.njcn.utils.redis.RedisCacheUtil;
import com.pqs9200.service.data.IEventPzService;

@Controller
@RequestMapping(value = "device")
public class DeviceController {
    ObjectMapper objectMapper = new ObjectMapper();
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(DeviceController.class);

    @Autowired
    GDInforMapper gdMapper;

    @Autowired
    private DeviceService deviceService;
    @Resource
    UserLogDetailService userLog;

    @Autowired
    private IEventPzService eventPz;

    @Resource
    private TreeService getDeviceTree;

    @Autowired
    GDInforMapper gdInforMapper;

    @Resource
    private DeviceService getDeviceInfo;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private SocketClient socketClient;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    JedisManager jedisManager;

    @Autowired
    private VersionService versionService;

    /**
     * 概览--》获取终端状态滚动事件
     */
    @ResponseBody
    @RequestMapping(value = "getTj", method = RequestMethod.POST)
    public List<DeviceDetail> getTj() {
        return deviceService.getTj();
    }

    /**
     * 运行管理==》终端运行状态
     */
    @RequestMapping(value = "getDeviceDataArea", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getDeviceDataArea(String area, String startTime, String endTime) {
        return null;
    }

    @RequestMapping(value = "getManufacturers", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getManufacturers(HttpSession session, String lineIndex) throws JsonProcessingException {
        HttpResult result;
        List<DeviceDetail> list;
        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;

    }

    /**
     * @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;

    }


    /***
     * 终端管理详情
     *
     * @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(result.get(i).getGdNa()));
                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);
    }

    /***
     * 终端统计
     *
     * @return
     */
    @RequestMapping(value = "getSbtj", method = RequestMethod.POST)
    @ResponseBody
    public SbtjData getSbtj(HttpServletRequest request) throws JsonProcessingException {
        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>();
        try {
            model = deviceService.getDevtype();
            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();
            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();
            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);
            }
        } catch (Exception e) {
            logger.error("终端统计异常，异常是" + e.toString());
        }
        result.setModel(mo);
        result.setArea(ar);
        result.setFactory(fa);

        return result;
    }

    // 根据终端名查询该终端
    @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(), 1);
            } else {
                flag = 500;
            }

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

    @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;
    }

    @ResponseBody
    @RequestMapping(value = "getSbyc", method = RequestMethod.POST)
    public HttpResult getSbyc(HttpServletRequest request) {
        HttpResult result = new HttpResult();
        try {
            List<List> deviceList = deviceService.getSbyc();
            if (deviceList.isEmpty()) {
                result.setCode(500);
                userLog.getLog("查询终端异常事件", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
                result.setMessage("没有配置信息");
            } else {
                result.setCode(200);
                userLog.getLog("查询终端异常事件", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
                result.setMessage("获取配置信息成功");
                result.setBody(deviceList);
            }
        } catch (Exception e) {
            logger.error("获取设备异常信息异常，异常是" + e.toString());
        }
        return result;
    }

    @RequestMapping(value = "downloadExcel", method = RequestMethod.POST)
    public void downloadExcel(@RequestBody CommonParamter commonParamter, HttpServletResponse response) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(response.getOutputStream());
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
            Sheet sheet1 = new Sheet(1, 0, SbycExcelBody.class);
            sheet1.setSheetName("设备异常");
            writer.write(getSbycData(), sheet1);
            Sheet sheet2 = new Sheet(2, 0, ZjsjExcelBody.class);
            sheet2.setSheetName("暂降事件");
            writer.write(getZjsjData(), sheet2);
            writer.finish();
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

    private List<SbycExcelBody> getSbycData() {
        List<SbycExcelBody> list = new ArrayList<>();
        List<List> deviceList = deviceService.getSbyc();

        if (!deviceList.isEmpty()) {
            for (int i = 0; i < deviceList.size(); i++) {
                SbycExcelBody sbycExcelBody = new SbycExcelBody();
                sbycExcelBody.setTime(deviceList.get(i).get(9).toString());
                sbycExcelBody.setGdName(deviceList.get(i).get(0).toString());
                sbycExcelBody.setBdName(deviceList.get(i).get(3).toString());
                sbycExcelBody.setIp(deviceList.get(i).get(6).toString());
                list.add(sbycExcelBody);
            }
        }

        return list;
    }

    private List<ZjsjExcelBody> getZjsjData() {
        List<ZjsjExcelBody> list = new ArrayList<>();
        List<List> deviceList = eventPz.getZjsj();

        if (!deviceList.isEmpty()) {
            for (int i = 0; i < deviceList.size(); i++) {
                ZjsjExcelBody zjsjExcelBody = new ZjsjExcelBody();
                zjsjExcelBody.setTime(deviceList.get(i).get(1).toString());
                zjsjExcelBody.setPoingName(deviceList.get(i).get(0).toString());
                zjsjExcelBody.setAmplitude(deviceList.get(i).get(3).toString());
                zjsjExcelBody.setDuration(deviceList.get(i).get(2).toString());
                list.add(zjsjExcelBody);
            }
        }

        return list;
    }

    @RequestMapping(value = "eventdatalist", method = RequestMethod.POST)
    @ResponseBody
    public List<EventDataList> getEventDataList(HttpServletRequest request, HttpSession session, String lineIndex,
                                                String startTime, String endTime) {
        session.removeAttribute("lineIndex");
        List<EventDataList> result = new ArrayList();

        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "eventdatalist");
        try {
            result = getDeviceInfo.getEventDataList(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            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;
    }

    @RequestMapping(value = "eventTime", method = RequestMethod.POST)
    @ResponseBody
    public List<Interval> getEventTime(HttpServletRequest request, HttpSession session, String lineIndex,
                                       String startTime, String endTime) {
        session.removeAttribute("lineIndex");
        List<Interval> result = new ArrayList();

        Date sTime = new Date();
        Date eTime = new Date();
        /**
         * 校验参数的有效性
         */
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            sTime = sdf.parse(startTime);
            endTime = endTime + " 23:59:59";
            eTime = sdfs.parse(endTime);

            result = getDeviceInfo.getEventTime(sTime, eTime, lineIndex);
            userLog.getLog("查询暂降月份统计", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (ParseException e) {
            userLog.getLog("查询暂降月份统计", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            logger.error("解析前台传递的时间有误，方法名为：eventTime，时间为startTime=" + startTime + ",endTime=" + endTime);
        }

        return result;
    }

    @RequestMapping(value = "eventType", method = RequestMethod.POST)
    @ResponseBody
    public List<EventTypeList> getEventType(HttpServletRequest request, HttpSession session, String lineIndex,
                                            String startTime, String endTime) {
        session.removeAttribute("lineIndex");
        List<EventTypeList> result = new ArrayList();

        DatePojo datePojo;
        try {
            datePojo = PubUtils.validateDate(startTime, endTime, "eventType");

            result = getDeviceInfo.getEventType(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            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());
            result = null;
        }
        return result;
    }

    @RequestMapping(value = "eventCause", method = RequestMethod.POST)
    @ResponseBody
    public List<EventCause> getEventCause(HttpServletRequest request, HttpSession session, String lineIndex,
                                          String startTime, String endTime) {
        session.removeAttribute("lineIndex");
        List<EventCause> result = new ArrayList();

        DatePojo datePojo;
        try {
            datePojo = PubUtils.validateDate(startTime, endTime, "eventCause");

            result = getDeviceInfo.getEventCause(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            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());
            result = null;
        }
        return result;
    }

    @RequestMapping(value = "eventStatistic", method = RequestMethod.POST)
    @ResponseBody
    public ReasonStatisc eventStatistic(HttpServletRequest request, HttpSession session, String lineIndex,
                                        String startTime, String endTime) {
        session.removeAttribute("lineIndex");
        ReasonStatisc result = new ReasonStatisc();

        DatePojo datePojo;
        try {
            datePojo = PubUtils.validateDate(startTime, endTime, "eventStatistic");

            result = getDeviceInfo.eventStatistic(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            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());
            result = null;
        }
        return result;
    }

    @RequestMapping(value = "eventDensity", method = RequestMethod.POST)
    @ResponseBody
    public List<EventDensity> getEventDensity(HttpServletRequest request, HttpSession session, String lineIndex,
                                              String startTime, String endTime) {
        session.removeAttribute("lineIndex");
        List<EventDensity> result = new ArrayList();

        DatePojo datePojo;
        try {
            datePojo = PubUtils.validateDate(startTime, endTime, "eventDensity");

            result = getDeviceInfo.getEventDensity(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            userLog.getLog("查询暂降密度图", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            logger.error("获取信息异常，异常是" + e.toString());
            result = null;
            userLog.getLog("查询暂降密度图", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        }
        return result;
    }

    @RequestMapping(value = "eventDisdip", method = RequestMethod.POST)
    @ResponseBody
    public List<List> getEventDisdip(HttpServletRequest request, HttpSession session, String lineIndex,
                                     String startTime, String endTime) {
        session.removeAttribute("lineIndex");
        List<List> result = new ArrayList();

        DatePojo datePojo;
        try {
            datePojo = PubUtils.validateDate(startTime, endTime, "eventDisdip");

            result = getDeviceInfo.getEventDisdip(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
        } catch (Exception e) {
            logger.error("获取信息异常，异常是" + e.toString());
            result = null;
        }
        return result;
    }

    @RequestMapping(value = "IEC411", method = RequestMethod.POST)
    @ResponseBody
    public List<List> getIEC411(HttpServletRequest request, HttpSession session, String lineIndex, String startTime,
                                String endTime) {
        session.removeAttribute("lineIndex");
        List<List> result = new ArrayList();

        DatePojo datePojo;
        try {
            datePojo = PubUtils.validateDate(startTime, endTime, "IEC411");

            result = getDeviceInfo.getIEC411(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
        } catch (Exception e) {
            logger.error("获取信息异常，异常是" + e.toString());
            result = null;
        }
        return result;
    }

    @RequestMapping(value = "IEC28", method = RequestMethod.POST)
    @ResponseBody
    public List<List> getIEC28(HttpServletRequest request, HttpSession session, String lineIndex, String startTime,
                               String endTime) {
        session.removeAttribute("lineIndex");
        List<List> result = new ArrayList();

        DatePojo datePojo;
        try {
            datePojo = PubUtils.validateDate(startTime, endTime, "IEC28");

            result = getDeviceInfo.getIEC28(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
        } catch (Exception e) {
            logger.error("获取信息异常，异常是" + e.toString());
            result = null;
        }
        return result;
    }

    @RequestMapping(value = "eventChance", method = RequestMethod.POST)
    @ResponseBody
    public EventChance getEventChance(HttpServletRequest request, HttpSession session, String lineIndex,
                                      String startTime, String endTime) {
        session.removeAttribute("lineIndex");
        EventChance result = new EventChance();

        DatePojo datePojo;
        try {
            datePojo = PubUtils.validateDate(startTime, endTime, "eventChance");

            result = getDeviceInfo.getEventChance(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            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());
            result = null;
        }
        return result;
    }

    @RequestMapping(value = "analyze", method = RequestMethod.POST)
    @ResponseBody
    public String queryanalyzeinfo(HttpServletRequest request, String lineIndex, String startTime, String endTime)
            throws JsonProcessingException {
        List<AnalyzeInfo> result = new ArrayList<AnalyzeInfo>();
        List<List> s = new ArrayList<List>();

        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "analyze");
        if (!StringUtils.isEmpty(datePojo.getMsg())) {
            return null;
        }

        try {
            result = getDeviceInfo.queryanalyzeinfo(datePojo.getStartTime(), datePojo.getEndTime(), lineIndex);
            int j = 0;
            for (int i = 0; i < result.size(); i++) {
                List<String> a = new ArrayList<String>();
                j = j + 1;
                a.add(String.valueOf(j));
                a.add(result.get(i).getEventDetailIndex());
                a.add(result.get(i).getTime());
                a.add(result.get(i).getEventvaule());
                a.add(result.get(i).getPersisttime());
                if (Float.parseFloat(result.get(i).getEventvaule()) > 100) {
                    a.add("/");
                    a.add("/");
                    a.add("/");
                    a.add("/");
                } else {
                    a.add(result.get(i).getType());
                    a.add(result.get(i).getReason());
                    a.add(result.get(i).getWavetype());
                    a.add(String.valueOf(result.get(i).getYzd()));
                }
                a.add(result.get(i).getFileFlag());
                s.add(a);
            }

            return objectMapper.writeValueAsString(s);

        } catch (Exception e) {
            return null;
        }
    }


    @RequestMapping(value = "deviceOnline", method = RequestMethod.POST)
    @ResponseBody
    public List<DeviceOnline> getDeviceOnline(HttpServletRequest request, String lineIndex, String startTime, String endTime) {
        Date sTime = new Date();
        Date eTime = new Date();
        /**
         * 校验参数的有效性
         */
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            sTime = sdf.parse(startTime);
            eTime = sdf.parse(endTime);

        } catch (ParseException e) {
            logger.error("解析前台传递的时间有误");
        }

        List<DeviceOnline> result = getDeviceInfo.getDeviceOnlineRate(sTime, eTime, Long.valueOf(lineIndex));
        return result;
    }

    @RequestMapping(value = "run", 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 = getDeviceInfo.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;
    }

    /**
     * 终端树
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "tree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getTree(HttpServletRequest request, HttpSession session, String startTime, String endTime) {
        if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
            session.removeAttribute("line_index");
        }
        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, "获取设备树信息成功");
            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;
    }

    /**
     * 电压等级终端树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "scaleTree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult devTypeTree(HttpServletRequest request, 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) {
            logger.error("获取设备树信息失败,方法名：scaleTree失败信息"+e.getMessage());
            result = PubUtils.assignmentResult(null, 200, "获取设备树信息失败");
        }
        return result;
    }

    /**
     * 厂家终端树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "mancTree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult mancTree(HttpServletRequest request, 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;
    }

    /**
     * 干扰源类型终端树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "loadTypeTree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult loadTypeTree(HttpServletRequest request, 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;
    }

    /**
     * 国网上报终端树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "monitorTree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult monitorTree(HttpServletRequest request, 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;
    }

    @ResponseBody
    @RequestMapping(value = "selState", method = RequestMethod.POST)
    public List<DeviceDetail> selState(@Param("devIndex") Integer devIndex) {
        List<DeviceDetail> list = getDeviceInfo.selState(devIndex);
        return list;
    }

    /**
     * 监测点模块
     */
    @RequestMapping(value = "deviceInfo", method = RequestMethod.POST)
    @ResponseBody
    public LineInfo getDeviceInfo(HttpServletRequest request, HttpSession session, String lineIndex) {
        session.removeAttribute("lineIndex");
        session.removeAttribute("longitude");
        session.removeAttribute("latitude");

        LineInfo result = new LineInfo();

        try {
            result = getDeviceInfo.getDeviceInfo(Long.valueOf(lineIndex));
        } catch (Exception e) {
            result = null;
        }

        return result;
    }

    /**
     * 获取字典表的电压等级数据
     */
    @PostMapping("voltage")
    @ResponseBody
    public HttpResult getVoltages() {
        HttpResult result;
        List<DicData> voltages;
        try {
            voltages = redisCacheUtil.getVoltageData();
            if (CollectionUtils.isEmpty(voltages)) {
                result = PubUtils.assignmentResult(null, 500, "字典表没有电压等级数据");
            } else {
                result = PubUtils.assignmentResult(voltages, 200, "获取字典表电压等级成功");
            }
        } catch (Exception e) {
            logger.error("获取字典表电压等级失败，失败原因：" + e.getMessage());
            result = PubUtils.assignmentResult(null, 500, "获取字典表电压等级失败");
        }
        return result;
    }

    /**
     * 获取字典表的干扰源类型数据
     */
    @PostMapping("loadType")
    @ResponseBody
    public HttpResult getLoadType() {
        HttpResult result;
        List<DicData> loadTypes;
        try {
            loadTypes = redisCacheUtil.getLoadType();
            if (CollectionUtils.isEmpty(loadTypes)) {
                result = PubUtils.assignmentResult(null, 500, "字典表没有干扰源类型数据");
            } else {
                result = PubUtils.assignmentResult(loadTypes, 200, "获取字典表干扰源类型成功");
            }
        } catch (Exception e) {
            logger.error("获取字典表符合类型失败，失败原因：" + e.getMessage());
            result = PubUtils.assignmentResult(null, 500, "获取字典表符合类型失败");
        }
        return result;
    }

    @RequestMapping(value = "socketon", method = RequestMethod.POST)
    @ResponseBody
    public String socketon(String message, Long lineIndex) {
        String result = "";
        result = socketClient.sent(message, lineIndex);
        return result;
    }


    //波形补招
    @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,"波形补招异常");
        }
    }

    @RequestMapping(value = "downZIPFile")
    @ResponseBody
    public void downZIPFile(HttpServletRequest request, HttpServletResponse response, String eventIndex) {
        getDeviceInfo.downZIPFileInfo(response, eventIndex);
    }

    @RequestMapping(value = "getZIPFile", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getZIPFile(HttpServletRequest request, HttpServletResponse response, String eventIndex) {
        HttpResult result = new HttpResult();
        String message = getDeviceInfo.getZIPFileInfo(response, eventIndex);

        if (message.equalsIgnoreCase("成功")) {
            result.setCode(200);
            result.setMessage(message);
        } else {
            result.setCode(500);
            result.setMessage(message);
        }
        return result;
    }

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

        return result;
    }

    /**
     * 根据字典表类型获取字典数据
     *
     * @author cdf
     * @date 2021/2/5
     */
    @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;
    }

//    /***
//     * 终端状态更新列表
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "getLogsDetail")
//    public String getTerminalLogsDetail(HttpServletRequest request, HttpSession session)
//            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);
//    }
}
