package com.pqs9900.controller.business;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.njcn.enums.DicDataTypeEnum;
import com.njcn.enums.LogTypeEnum;
import com.njcn.enums.app.ReturnCode;
import com.njcn.enums.app.UserCodeEnum;
import com.njcn.mapper.configuration.*;
import com.njcn.mapper.user.DeptsMapper;
import com.njcn.pojo.commons.*;
import com.njcn.pojo.commons.device.*;
import com.njcn.pojo.configuration.*;
import com.njcn.pojo.data.OfflLog;
import com.njcn.pojo.jibei.Dnzljczz;
import com.njcn.pojo.jibei.Znycdz;
import com.njcn.pojo.user.Depts;
import com.njcn.service.configuration.DeviceService;
import com.njcn.service.configuration.LineService;
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.*;
import com.njcn.utils.SM.SM4Utils;
import com.pqs9900.pojo.DataInfo.TranslateState;
import com.pqs9900.pojo.terminal.FtpDTO;
import com.pqs9900.pojo.terminal.TerminalDirectory;
import com.pqs9900.service.configuration.ManaDeviceService;
import com.pqs9900.service.configuration.PushNodeService;
import com.pqs9900.service.terminal.TerminalDirectoryService;
import com.pqs9900.service.terminal.VersionService;
import com.pqs9900.util.DeleteThread;
import com.pqs9900.util.Homeostasis;
import com.pqs9900.util.Kafka.JavaKafkaConsumer;
import com.pqs9900.util.Kafka.JavaKafkaProducer;
import com.pqs9900.util.TerminalUtil;
import com.pqs9900.util.TranslateThread;
import net.sf.json.JSONArray;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.security.auth.login.AccountException;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

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

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

    @Resource
    private TerminalDirectoryService terminalDirectoryService;

    @Resource
    private DeviceService getDeviceInfo;

    @Resource
    private ManaDeviceService manaDevice;

    @Resource
    private PushNodeService pushNode;

    @Resource
    private TreeService getDeviceTree;

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private PushInfoMapper pushInfoMapper;

    @Autowired
    private DeptsMapper deptsMapper;

    @Resource
    private DicDataMapper dicDataMapper;

    @Resource
    private ExportDevMapper exportDevMapper;

    @Autowired
    private LineMapper lineMapper;

    @Resource
    private NodeInformationMapper nodeInformationMapper;

    @Autowired
    private SocketClient socketClient;

    @Autowired
    private VersionService versionService;

    @Autowired
    private ManaDeviceService manaDeviceService;

    @Autowired
    private Homeostasis homeostasis;

    @Resource
    private UserLogDetailService userLog;

    @Resource
    private LineService lineService;

    List<ExportDev> exportinfo;


    /**
     * 终端管理界面终端树
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "deviceTree", method = RequestMethod.POST)
    @ResponseBody
    public List<Tree> getdeviceTree(HttpServletRequest request, HttpSession session) {
        if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
            session.removeAttribute("line_index");
        }

        List<Tree> result = new ArrayList();
        try {
            result = getDeviceInfo.getDeviceTree();
        } catch (Exception e) {
            logger.error("获取终端树异常，异常是" + e.toString());
        }
        return result;
    }

    /**
     * 国网终端管理界面终端树
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "gwDeviceTree", method = RequestMethod.POST)
    @ResponseBody
    public List<Tree> gwDeviceTree(HttpServletRequest request, HttpSession session) {
        List<Tree> result = new ArrayList();
        try {
            result = getDeviceInfo.getGWDeviceTree();
        } catch (Exception e) {
            logger.error("获取终端树异常，异常是" + e.toString());
        }
        return result;
    }

    /**
     * 获取离线设备树
     */
    @RequestMapping(value = "offLineDeviceTree", method = RequestMethod.POST)
    @ResponseBody
    public List<Tree> getOffLineDeviceTree() {
        List<Tree> result = getDeviceInfo.getOfflineDeviceTree();
        return result;
    }

    @RequestMapping(value = "getSelName", method = RequestMethod.POST)
    @ResponseBody
    public List<DeviceDetail> getSelName(String deviceName) {
        return getDeviceInfo.getSelName(deviceName);
    }

    /**
     * 终端管理界面终端树
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "deviceMainTree", method = RequestMethod.POST)
    @ResponseBody
    public List<Tree> getdeviceMainTree(HttpServletRequest request, HttpSession session) {
        if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
            session.removeAttribute("line_index");
        }

        List<Tree> result = new ArrayList();
        try {
            result = getDeviceInfo.getDeviceMainTree();
        } catch (Exception e) {
            logger.error("获取终端树异常，异常是" + e.toString());
        }

        return result;
    }

    /**
     * 获取在线设备树（只保留项目以下节点）
     *
     * @author cdf
     * @date 2021/9/28
     */
    @RequestMapping(value = "getOnlineDeviceTree", method = RequestMethod.POST)
    @ResponseBody
    public List<Tree> getOnlineDeviceTree(HttpServletRequest request, HttpSession session) {
        List<Tree> result = new ArrayList();
        try {
            result = getDeviceInfo.getOnlineTreeAllSys();
        } catch (Exception e) {
            logger.error("获取终端树异常，异常是" + e.toString());
        }

        return result;
    }

    @RequestMapping(value = "addProj", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addProj(HttpServletRequest request, String projName) {
        HttpResult result = new HttpResult();
        AddResult temp;
        projName = XssFilterUtil.dealString(projName);
        if (!PubUtils.patternDevname(projName)) {
            result.setCode(501);
            result.setMessage("新增失败!名称违规");
            logger.error("新增项目失败!");
            userLog.getLog("新增项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                temp = manaDevice.saveProjectInfo(projName);
                if (temp.getMessage().equalsIgnoreCase("添加成功")) {
                    result.setCode(200);
                    result.setBody(temp.getIndex());
                    result.setMessage(temp.getMessage());
                    logger.info("新增项目成功!");
                    userLog.getLog("新增项目", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (temp.getMessage().equalsIgnoreCase("添加失败a")) {
                    result.setCode(400);
                    result.setMessage(temp.getMessage());
                    logger.error("新增项目失败!名称已存在");
                    userLog.getLog("新增项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(temp.getMessage());
                    logger.error("新增项目失败!");
                    userLog.getLog("新增项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }
            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("新增项目失败!");
                logger.error("新增项目失败!" + e.getMessage());
                userLog.getLog("新增项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "loadProj", method = RequestMethod.POST)
    @ResponseBody
    public Project loadProj(HttpServletRequest request, HttpSession session, Long projIndex) {
        session.removeAttribute("projIndex");
        Project result = new Project();
        try {
            result = manaDevice.loadProj(projIndex);
            userLog.getLog("查询项目", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            result = null;
            userLog.getLog("查询项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }

        return result;
    }

    @RequestMapping(value = "updateporj", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateporj(HttpServletRequest request, Long porjIndex, String name) {
        HttpResult result = new HttpResult();

        name = XssFilterUtil.dealString(name);
        if (!PubUtils.patternDevname(name)) {
            result.setCode(501);
            result.setMessage("更新失败!名称违规");
            logger.error("更新项目失败!");
            userLog.getLog("修改项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                String message = manaDevice.updateProj(porjIndex, name);
                if (message.equalsIgnoreCase("更新成功")) {
                    result.setCode(200);
                    result.setMessage(message);
                    logger.info("更新项目成功!");
                    userLog.getLog("修改项目", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("更新失败a")) {
                    result.setCode(400);
                    result.setMessage(message);
                    logger.error("更新项目失败!名称已存在");
                    userLog.getLog("修改项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("更新项目失败!");
                    userLog.getLog("修改项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }
            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("更新省份失败!");
                logger.error("更新省份失败!" + e.getMessage());
                userLog.getLog("修改省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "delporj", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult delporj(HttpServletRequest request, Long projIndex) {
        HttpResult result = new HttpResult();

        try {
            String message = manaDevice.delProj(projIndex);
            if (message.equalsIgnoreCase("删除成功")) {
                result.setCode(200);
                result.setMessage(message);
                logger.info("删除项目成功!");
                userLog.getLog("删除项目", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("删除失败a")) {
                result.setCode(400);
                result.setMessage(message);
                logger.error("删除项目失败!存在下级单位");
                userLog.getLog("删除项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                result.setCode(500);
                result.setMessage(message);
                logger.error("删除项目失败!");
                userLog.getLog("删除项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("删除项目失败!" + e.getMessage());
            logger.error("删除项目失败!");
            userLog.getLog("删除项目", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    @RequestMapping(value = "addPro", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addPro(HttpServletRequest request, Long projIndex, String proName) {
        HttpResult result = new HttpResult();
        AddResult temp;
        proName = XssFilterUtil.dealString(proName);
        if (!PubUtils.patternDevname(proName)) {
            result.setCode(501);
            result.setMessage("新增失败!名称违规");
            logger.error("新增省份失败!");
            userLog.getLog("新增省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                temp = manaDevice.saveProInfo(proName, projIndex);
                if (temp.getMessage().equalsIgnoreCase("添加成功")) {
                    result.setCode(200);
                    result.setBody(temp.getIndex());
                    result.setMessage(temp.getMessage());
                    logger.info("新增省份成功!");
                    userLog.getLog("新增省份", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (temp.getMessage().equalsIgnoreCase("添加失败a")) {
                    result.setCode(400);
                    result.setMessage(temp.getMessage());
                    logger.error("新增省份失败!名称已存在");
                    userLog.getLog("新增省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(temp.getMessage());
                    logger.error("新增省份失败!");
                    userLog.getLog("新增省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }
            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("新增省份失败!");
                logger.error("新增省份失败!" + e.getMessage());
                userLog.getLog("新增省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "loadPro", method = RequestMethod.POST)
    @ResponseBody
    public Province loadPro(HttpServletRequest request, HttpSession session, Long proIndex) {
        session.removeAttribute("proIndex");
        Province result;
        try {
            result = manaDevice.loadPro(proIndex);
            userLog.getLog("查询省份", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            result = null;
            userLog.getLog("查询省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }

        return result;
    }

    @RequestMapping(value = "updatePro", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updatePro(HttpServletRequest request, Long proIndex, String name) {
        HttpResult result = new HttpResult();

        name = XssFilterUtil.dealString(name);
        if (!PubUtils.patternDevname(name)) {
            result.setCode(501);
            result.setMessage("更新失败!名称违规");
            logger.error("更新省份失败!");
            userLog.getLog("修改省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                String message = manaDevice.updatePro(proIndex, name);
                if (message.equalsIgnoreCase("更新成功")) {
                    result.setCode(200);
                    result.setMessage(message);
                    logger.info("更新省份成功!");
                    userLog.getLog("修改省份", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("更新失败a")) {
                    result.setCode(400);
                    result.setMessage(message);
                    logger.error("更新省份失败!名称已存在");
                    userLog.getLog("修改省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("更新省份失败!");
                    userLog.getLog("修改省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }
            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("更新省份失败!");
                logger.error("更新省份失败!" + e.getMessage());
                userLog.getLog("修改省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "delPro", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult delPro(HttpServletRequest request, Long proIndex) {
        HttpResult result = new HttpResult();

        try {
            String message = manaDevice.delPro(proIndex);
            if (message.equalsIgnoreCase("删除成功")) {
                result.setCode(200);
                result.setMessage(message);
                logger.info("删除省份成功!");
                userLog.getLog("删除省份", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("删除失败a")) {
                result.setCode(400);
                result.setMessage(message);
                logger.error("删除省份失败!存在下级单位");
                userLog.getLog("删除省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                result.setCode(500);
                result.setMessage(message);
                logger.error("删除省份失败!");
                userLog.getLog("删除省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("删除省份失败!");
            logger.error("删除省份失败!" + e.getMessage());
            userLog.getLog("删除省份", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    @RequestMapping(value = "loadDepts", method = RequestMethod.POST)
    @ResponseBody
    public List<Depts> loadDept(HttpServletRequest request, Long proIndex) {
        List<Depts> result = manaDevice.loadDept(proIndex);

        return result;
    }

    @RequestMapping(value = "addGd", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addGd(HttpServletRequest request, HttpSession session, String gdName,
                            Long proIndex) {
        session.removeAttribute("proIndex");
        HttpResult result = new HttpResult();
        AddResult temp;

        gdName = XssFilterUtil.dealString(gdName);
        if (!PubUtils.patternDevname(gdName)) {
            result.setCode(501);
            result.setMessage("新增失败!名称违规");
            logger.error("新增供电公司失败!");
            userLog.getLog("新增供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                temp = manaDevice.saveGdInfo(gdName, proIndex);
                if (temp.getMessage().equalsIgnoreCase("添加成功")) {
                    result.setCode(200);
                    result.setBody(temp.getIndex());
                    result.setMessage(temp.getMessage());
                    logger.info("新增供电公司成功!");
                    userLog.getLog("新增供电公司", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (temp.getMessage().equalsIgnoreCase("添加失败a")) {
                    result.setCode(400);
                    result.setMessage(temp.getMessage());
                    logger.error("新增供电公司失败!名称已存在");
                    userLog.getLog("新增供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(temp.getMessage());
                    logger.error("新增供电公司失败!");
                    userLog.getLog("新增供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }
            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("新增供电公司失败!");
                logger.error("新增供电公司失败!" + e.getMessage());
                userLog.getLog("新增供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "updateGd", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateGd(HttpServletRequest request, Long proIndex, Long gdIndex, String name) {
        HttpResult result = new HttpResult();

        name = XssFilterUtil.dealString(name);
        if (!PubUtils.patternDevname(name)) {
            result.setCode(501);
            result.setMessage("更新失败!名称违规");
            logger.error("更新供电公司失败!");
            userLog.getLog("修改供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                String message = manaDevice.updateGd(proIndex, gdIndex, name);
                if (message.equalsIgnoreCase("更新成功")) {
                    result.setCode(200);
                    result.setMessage(message);
                    logger.info("更新供电公司成功!");
                    userLog.getLog("修改供电公司", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("更新失败a")) {
                    result.setCode(400);
                    result.setMessage(message);
                    logger.error("更新供电公司失败!名称已存在");
                    userLog.getLog("修改供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("更新供电公司失败!");
                    userLog.getLog("修改供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }
            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("更新供电公司失败!");
                logger.error("更新供电公司失败!" + e.getMessage());
                userLog.getLog("修改供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "delGd", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult delGd(HttpServletRequest request, Long gdIndex) {
        HttpResult result = new HttpResult();

        try {
            String message = manaDevice.delGd(gdIndex, PubUtils.getIpAddr(request));
            if (message.equalsIgnoreCase("删除成功")) {
                result.setCode(200);
                result.setMessage(message);
                logger.info("删除供电公司成功!");
                userLog.getLog("删除供电公司", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                result.setCode(500);
                result.setMessage(message);
                logger.error("删除供电公司失败!");
                userLog.getLog("删除供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("删除供电公司失败!");
            logger.error("删除供电公司失败!" + e.getMessage());
            userLog.getLog("删除供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    @RequestMapping(value = "loadGd", method = RequestMethod.POST)
    @ResponseBody
    public GDInformation loadGd(HttpServletRequest request, HttpSession session, Long gdIndex) {
        session.removeAttribute("proIndex");
        session.removeAttribute("gdIndex");
        GDInformation result = new GDInformation();
        try {
            result = manaDevice.loadGd(gdIndex);
            userLog.getLog("查询供电公司", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            result = null;
            userLog.getLog("查询供电公司", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }

        return result;
    }

    @RequestMapping(value = "addSub", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addSub(HttpServletRequest request, HttpSession session, String subName, String gdIndex, String scale,
                             String longitude, String latitude) {
        session.removeAttribute("proIndex");
        session.removeAttribute("gdIndex");
        HttpResult result = new HttpResult();
        AddResult temp;
        subName = XssFilterUtil.dealString(subName);

        if (!PubUtils.patternDevname(subName)) {
            result.setCode(501);
            result.setMessage("新增失败!名称违规");
            logger.error("新增变电站失败!");
            userLog.getLog("新增变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternFloat(longitude) || !PubUtils.patternFloat(latitude)) {
            result.setCode(501);
            result.setMessage("新增失败!经纬度违规");
            logger.error("新增变电站失败!");
            userLog.getLog("新增变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                temp = manaDevice.saveSubInfo(subName, gdIndex, Float.parseFloat(longitude),
                        Float.parseFloat(latitude), scale);
                if (temp.getMessage().equalsIgnoreCase("添加成功")) {
                    result.setCode(200);
                    result.setBody(temp.getIndex());
                    logger.info("新增变电站成功!");
                    userLog.getLog("新增变电站", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (temp.getMessage().equalsIgnoreCase("添加失败a")) {
                    result.setCode(400);
                    result.setMessage(temp.getMessage());
                    logger.error("新增变电站失败!名称已存在");
                    userLog.getLog("新增变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(temp.getMessage());
                    logger.error("新增变电站失败!");
                    userLog.getLog("新增变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }
            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("新增变电站失败!");
                logger.error("新增变电站失败!" + e.getMessage());
                userLog.getLog("新增变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "updateSub", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateSub(HttpServletRequest request, Long gdIndex, Long subIndex, String name, String longitude,
                                String latitude, String mapIndex, String scale) {
        HttpResult result = new HttpResult();

        name = XssFilterUtil.dealString(name);
        if (!PubUtils.patternDevname(name)) {
            result.setCode(501);
            result.setMessage("更新失败!名称违规");
            logger.error("更新变电站失败!");
            userLog.getLog("修改变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternFloat(longitude) || !PubUtils.patternFloat(latitude)) {
            result.setCode(501);
            result.setMessage("更新失败!经纬度违规");
            logger.error("更新变电站失败!");
            userLog.getLog("修改变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                Float longitudef = 0f;
                Float latitudef = 0f;
                if (StrUtil.isNotBlank(longitude)) {
                    longitudef = Float.parseFloat(longitude);
                }
                if (StrUtil.isNotBlank(latitude)) {
                    latitudef = Float.parseFloat(latitude);
                }

                String message = manaDevice.updateSub(gdIndex, subIndex, name, longitudef,
                        latitudef, mapIndex, scale);
                if (message.equalsIgnoreCase("更新成功")) {
                    result.setCode(200);
                    result.setMessage(message);
                    logger.info("更新变电站成功!");
                    userLog.getLog("修改变电站", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("更新失败a")) {
                    result.setCode(400);
                    result.setMessage(message);
                    logger.error("更新变电站失败!名称已存在");
                    userLog.getLog("修改变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("更新变电站失败!");
                    userLog.getLog("修改变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }

            } catch (Exception e) {
                e.printStackTrace();
                result.setCode(500);
                result.setMessage("更新变电站失败!");
                logger.error("更新变电站失败!" + e.getMessage());
                userLog.getLog("修改变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "delSub", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult delSub(HttpServletRequest request, Long subIndex) {
        HttpResult result = new HttpResult();

        try {
            String message = manaDevice.delSub(subIndex);
            if (message.equalsIgnoreCase("删除成功")) {
                result.setCode(200);
                result.setMessage(message);
                logger.info("删除变电站成功!");
                userLog.getLog("删除变电站", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("删除失败a")) {
                result.setCode(400);
                result.setMessage(message);
                logger.error("删除变电站失败!存在下级装置");
                userLog.getLog("删除变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("删除失败c")) {
                result.setCode(600);
                result.setMessage(message);
                logger.error("删除变电站失败!存在下级变压器");
                userLog.getLog("删除变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                result.setCode(500);
                result.setMessage(message);
                logger.error("删除变电站失败!");
                userLog.getLog("删除变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }

        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("删除变电站失败!");
            logger.error("删除变电站失败!" + e.getMessage());
            userLog.getLog("删除变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    @RequestMapping(value = "loadSub", method = RequestMethod.POST)
    @ResponseBody
    public SubInfo loadSub(HttpServletRequest request, Long subIndex) {
        SubInfo result = new SubInfo();
        try {
            result = manaDevice.loadSub(subIndex);
            userLog.getLog("查询变电站", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            result = null;
            userLog.getLog("查询变电站", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }

        return result;
    }

    @RequestMapping(value = "findMaxDeviceName", method = RequestMethod.POST)
    @ResponseBody
    public String findMaxDeviceName(HttpServletRequest request, Long gdIndex) {
        String result;
        try {
            result = manaDevice.findMaxDeviceName(gdIndex);
            userLog.getLog("查询当前供电公司下面最大的设备名称", "成功", result, LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            result = null;
            userLog.getLog("查询当前供电公司下面最大的设备名称", "失败", result, LogTypeEnum.SYSTEM.toString(), 0);
        }
        return result;
    }

    @RequestMapping(value = "addDevice", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addDevice(HttpServletRequest request, HttpSession session, String devName, Long gdIndex,
                                Long subIndex, String series, String key) {
        session.removeAttribute("proIndex");
        session.removeAttribute("gdIndex");
        session.removeAttribute("subIndex");
        HttpResult result = new HttpResult();
        AddResult temp;
        DeviceInfo dev = new DeviceInfo();

        devName = XssFilterUtil.dealString(devName);
        series = XssFilterUtil.dealString(series);
        key = XssFilterUtil.dealString(key);
        if (!PubUtils.patternDevname(devName)) {
            result.setCode(501);
            result.setMessage("新增失败!名称违规");
            logger.error("新增终端失败!");
            userLog.getLog("新增装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternSeries(series) || !PubUtils.patternSeries(key)) {
            result.setCode(501);
            result.setMessage("新增失败!识别码秘钥违规");
            logger.error("新增终端失败!");
            userLog.getLog("新增装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                if (devName != null || devName != "") {
                    dev.setName(devName);
                }
                if (gdIndex != null) {
                    dev.setGdIndex(gdIndex);
                }
                if (subIndex != null) {
                    dev.setSubIndex(subIndex);
                }
                if (series != null) {
                    dev.setSeries(series);
                }
                if (key != null) {
                    dev.setKey(key);
                }
                temp = manaDevice.saveDevInfo(dev);
                if (temp.getMessage().equalsIgnoreCase("添加成功")) {
                    result.setCode(200);
                    result.setBody(temp.getIndex());
                    logger.info("新增终端成功!");
                    userLog.getLog("新增装置", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (temp.getMessage().equalsIgnoreCase("添加失败a")) {
                    result.setCode(400);
                    result.setMessage(temp.getMessage());
                    logger.error("新增终端失败!名称已存在");
                    userLog.getLog("新增装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (temp.getMessage().equalsIgnoreCase("无服务器信息")) {
                    result.setCode(300);
                    result.setMessage(temp.getMessage());
                    logger.error("无前置机信息");
                    userLog.getLog("新增装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(temp.getMessage());
                    logger.error("新增终端失败!");
                    userLog.getLog("新增装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }

            } catch (Exception e) {
                e.printStackTrace();
                result.setCode(500);
                result.setMessage("新增终端失败!");
                logger.error("新增终端失败!" + e.getMessage());
                userLog.getLog("新增装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "updateDeviceInfo", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateDeviceInfo(HttpServletRequest request, HttpSession session, Long devIndex, String devtype, String typename,
                                       String LogonTime, Long nodeIndex, String name, Long devmodel, Long datatype, String manufacturer,
                                       String NextTimeCheck, String mac, String port, Integer callflag,
                                       String series, String key, String devfunc, Integer electroplate, Integer ontime, String contract, String devCatena, String sim,
                                       String devLocation, String devNo, Integer isAlarm
    ) {

        List<String> devfunction = new ArrayList<>();
        JSONArray jsonArray = JSONArray.fromObject(devfunc);
        for (int m = 0; m < jsonArray.size(); m++) {
            devfunction.add(jsonArray.getString(m));
        }
        HttpResult result = new HttpResult();
        DeviceInfo device = new DeviceInfo();
        name = XssFilterUtil.dealString(name);
        mac = XssFilterUtil.dealString(mac);
        port = XssFilterUtil.dealString(port);
        if (!name.equals("") && !PubUtils.patternDevname(name)) {
            result.setCode(501);
            result.setMessage("更新失败!名称违规");
            logger.error("更新终端失败!");
            userLog.getLog("修改装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (series != null && !PubUtils.patternSeries(series)) {
            result.setCode(501);
            result.setMessage("更新失败!识别码违规");
            logger.error("更新终端失败!");
            userLog.getLog("修改装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (key != null && !PubUtils.patternSeries(key)) {
            result.setCode(501);
            result.setMessage("更新失败!秘钥违规");
            logger.error("更新终端失败!");
            userLog.getLog("修改装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!mac.equals("") && !PubUtils.patternMac(mac) && !PubUtils.patternIp(mac)) {
            result.setCode(501);
            result.setMessage("更新失败!IP/MAC地址违规");
            logger.error("更新终端失败!");
            userLog.getLog("修改装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!port.equals("") && !PubUtils.patternPort(port)) {
            result.setCode(501);
            result.setMessage("更新失败!端口违规");
            logger.error("更新终端失败!");
            userLog.getLog("修改装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            if (devIndex != null) {
                device.setDevIndex(devIndex);
            }
            if (devtype != null) {
                device.setDevType(devtype);
            }
            if (name != null && !name.equals("")) {
                device.setName(name);
            }
            if (devmodel != null) {
                device.setDevmodel(devmodel);
            }
            if (manufacturer != null) {
                device.setManufacturer(manufacturer);
            }
            if (datatype != null) {
                device.setDatatype(datatype);
            }
            if (callflag != null) {
                device.setCallFlag(callflag);
            }
            if (series != null) {
                device.setSeries(series);
            }
            if (key != null) {
                device.setKey(key);
            }
            if (electroplate != null) {
                device.setElectroplate(electroplate);
            }
            if (ontime != null) {
                device.setOntime(ontime);
            }
            if (contract != null) {
                device.setContract(contract);
            }
            if (sim != null) {
                device.setSim(sim);
            }
            if (devCatena != null) {
                device.setDevCatena(devCatena);
            }

            if (StrUtil.isNotBlank(devLocation)) {
                device.setDevLocation(devLocation);
            }
            if (StrUtil.isNotBlank(devNo)) {
                device.setDevNo(devNo);
            }

            if (LogonTime != null && NextTimeCheck != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date logonTime;
                Date nextTimeCheck;
                try {
                    logonTime = sdf.parse(LogonTime);
                    nextTimeCheck = sdf.parse(NextTimeCheck);
                    device.setLogonTime(logonTime);
                    device.setNextTimeCheck(nextTimeCheck);
                } catch (ParseException e) {
                    logger.error("产生了异常，异常是" + e.getMessage());
                }
            }
            if (nodeIndex != null) {
                device.setNodeIndex(nodeIndex);
            }

            if (!mac.equals("")) {
                device.setMac(mac);
            }

            if (!port.equals("")) {
                device.setPortId(Long.valueOf(port));
            }

            device.setIsAlarm(isAlarm);

            try {
                String message = manaDevice.updateDeviceInfo(device, devfunction);
                if (message.equalsIgnoreCase("修改成功")) {
                    result.setCode(200);
                    result.setMessage(message);
                    logger.info("更新终端成功!");
                    userLog.getLog("修改装置", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("修改失败a")) {
                    result.setCode(400);
                    result.setMessage("更新终端失败!名称已存在");
                    logger.error("更新终端失败!名称已存在");
                    userLog.getLog("修改装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("修改失败b")) {
                    result.setCode(400);
                    result.setMessage("更新终端失败!IP(MAC)地址已占用");
                    logger.error("更新终端失败!IP(MAC)地址已占用");
                    userLog.getLog("修改装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("更新终端失败!");
                    userLog.getLog("修改装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }

            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("更新终端失败!");
                logger.error("更新终端失败!" + e.getMessage());
                userLog.getLog("修改装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

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

        List<Tree> result = new ArrayList();
        try {
            result = getDeviceTree.getTransTreedata();
            userLog.getLog("查询设备树", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            userLog.getLog("查询设备树", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("变压器树获取异常，异常是" + e.toString());
        }
        return result;
    }

    @RequestMapping(value = "delDeviceInfo", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult delDeviceInfo(HttpServletRequest request, Long devIndex) {
        HttpResult result = new HttpResult();

        try {
            String message = manaDevice.delDeviceInfo(devIndex);
            if (message.equalsIgnoreCase("删除成功")) {
                result.setCode(200);
                result.setMessage(message);
                logger.info("删除终端成功!");
                userLog.getLog("删除装置", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("删除失败a")) {
                result.setCode(400);
                result.setMessage(message);
                logger.error("删除终端失败!存在下级单位");
                userLog.getLog("删除装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                result.setCode(500);
                result.setMessage(message);
                logger.error("删除终端失败!");
                userLog.getLog("删除装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }

        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("删除终端失败!");
            logger.error("删除终端失败!" + e.getMessage());
            userLog.getLog("删除装置", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    // 查询终端类型
    @RequestMapping(value = "devNameType", method = RequestMethod.POST)
    @ResponseBody
    public Device devNameType(String devName, HttpServletRequest request) {
        // 后台Xss攻击处理、包括html/js/sql
        devName = XssFilterUtil.dealString(devName);
        Device quarryOutValue = new Device();
        try {
            quarryOutValue = getDeviceInfo.devNameType(devName);
            userLog.getLog("查询终端类型", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            userLog.getLog("查询终端类型", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("查找终端类型异常，异常是" + e.toString());
        }
        return quarryOutValue;
    }

    // 查询终端类型
    @RequestMapping(value = "devIndexType", method = RequestMethod.POST)
    @ResponseBody
    public Device devIndexType(String devName, HttpServletRequest request) {
        // 后台Xss攻击处理、包括html/js/sql
        devName = XssFilterUtil.dealString(devName);
        Device quarryOutValue = new Device();
        try {
            quarryOutValue = getDeviceInfo.devIndexType(devName);
            userLog.getLog("查询终端类型", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            userLog.getLog("查询终端类型", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("查找终端类型异常，异常是" + e.toString());
        }
        return quarryOutValue;
    }

    // 查询终端类型
    @RequestMapping(value = "devIndexsType", method = RequestMethod.POST)
    @ResponseBody
    public Device devIndexsType(String devName, HttpServletRequest request) {
        // 后台Xss攻击处理、包括html/js/sql
        devName = XssFilterUtil.dealString(devName);
        Device quarryOutValue = new Device();
        try {
            quarryOutValue = getDeviceInfo.devIndexsType(devName);
            userLog.getLog("查询终端类型", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            userLog.getLog("查询终端类型", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("查找终端类型异常，异常是" + e.toString());
        }
        return quarryOutValue;
    }

    @RequestMapping(value = "loadDevice", method = RequestMethod.POST)
    @ResponseBody
    public DeviceInfo loadDevice(HttpServletRequest request, Long devIndex) {
        DeviceInfo result;
        try {
            result = manaDevice.loadDevice(devIndex);
            userLog.getLog("查询终端", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            logger.error("获取终端详情失败，失败信息" + e);
            result = null;
            userLog.getLog("查询终端", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }

        return result;
    }

    @RequestMapping(value = "addSubv", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addSubv(HttpServletRequest request, HttpSession session, String subvName, String gdIndex,
                              String subIndex, String devIndex, int subvnum, String scale, Long subvModel) {
        session.removeAttribute("proIndex");
        session.removeAttribute("gdIndex");
        session.removeAttribute("subIndex");
        session.removeAttribute("devIndex");
        HttpResult result = new HttpResult();
        AddResult temp;

        subvName = XssFilterUtil.dealString(subvName);
        if (!PubUtils.patternDevname(subvName)) {
            result.setCode(501);
            result.setMessage("添加失败!名称违规");
            logger.error("新增母线失败!");
            userLog.getLog("新增母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                temp = manaDevice.saveSubvInfo(subvName, gdIndex, subIndex, devIndex, subvnum, scale, subvModel);
                if (temp.getMessage().equalsIgnoreCase("添加成功")) {
                    result.setCode(200);
                    result.setBody(temp.getIndex());
                    logger.info("新增母线成功!");
                    userLog.getLog("新增母线", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(temp.getMessage());
                    logger.error("新增母线失败!");
                    userLog.getLog("新增母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }

            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("新增母线失败!");
                logger.error("新增母线失败!" + e.getMessage());
                userLog.getLog("新增母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "updateSubv", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateSubv(HttpServletRequest request, String subvName, Long gdIndex, Long subIndex,
                                 Long devIndex, Long subvIndex, int subvnum, String scale, Long subvModel) {
        HttpResult result = new HttpResult();

        subvName = XssFilterUtil.dealString(subvName);
        if (!PubUtils.patternDevname(subvName)) {
            result.setCode(501);
            result.setMessage("更新失败!名称违规");
            logger.error("更新母线失败!");
            userLog.getLog("修改母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                String message = manaDevice.updateSubv(subvName, gdIndex, subIndex, devIndex, subvIndex, subvnum, scale,
                        subvModel);
                if (message.equalsIgnoreCase("更新成功")) {
                    result.setCode(200);
                    result.setMessage(message);
                    logger.info("更新母线成功!");
                    userLog.getLog("修改母线", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("更新失败a")) {
                    result.setCode(400);
                    result.setMessage("修改失败,名称已存在!");
                    logger.error("更新母线失败!");
                    userLog.getLog("修改母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("更新母线失败!");
                    userLog.getLog("修改母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }

            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("更新母线失败!");
                logger.error("更新母线失败!" + e.getMessage());
                userLog.getLog("修改母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "delSubv", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult delSubv(HttpServletRequest request, Long subvIndex) {
        HttpResult result = new HttpResult();

        try {
            String message = manaDevice.delSubv(subvIndex);
            if (message.equalsIgnoreCase("删除成功")) {
                result.setCode(200);
                result.setMessage(message);
                logger.info("删除母线成功!");
                userLog.getLog("删除母线", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else if (message.equalsIgnoreCase("删除失败a")) {
                result.setCode(400);
                result.setMessage(message);
                logger.error("删除母线失败!存在下级单位");
                userLog.getLog("删除母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                result.setCode(500);
                result.setMessage(message);
                logger.error("删除母线失败!");
                userLog.getLog("删除母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }

        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("删除母线失败!");
            logger.error("删除母线失败!" + e.getMessage());
            userLog.getLog("删除母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    @RequestMapping(value = "loadSubv", method = RequestMethod.POST)
    @ResponseBody
    public SubVoltage loadSubv(HttpServletRequest request, Long subvIndex) {
        SubVoltage result = new SubVoltage();
        try {
            result = manaDevice.loadSubv(subvIndex);
            userLog.getLog("查询母线", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            result = null;
            userLog.getLog("查询母线", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }

        return result;
    }

    @RequestMapping(value = "addLine", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addLine(HttpServletRequest request, HttpSession session, Long gdIndex, Long subIndex,
                              Long devIndex, Long subvIndex, String lineName, int lineNum, String dept) {
        session.removeAttribute("proIndex");
        session.removeAttribute("gdIndex");
        session.removeAttribute("subIndex");
        session.removeAttribute("devIndex");
        session.removeAttribute("subvIndex");
        HttpResult result = new HttpResult();
        AddResult temp = new AddResult();

        lineName = XssFilterUtil.dealString(lineName);
        if (!PubUtils.patternDevname(lineName)) {
            result.setCode(501);
            result.setMessage("添加失败!名称违规");
            logger.error("新增监测点失败!");
            userLog.getLog("新增监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                Line line = new Line();
                line.setGdIndex(gdIndex);
                line.setSubIndex(subIndex);
                line.setDevIndex(devIndex);
                line.setSubvIndex(subvIndex);
                line.setName(lineName);

                temp = manaDevice.saveLineInfo(line, dept, lineNum, null, null, null, 0, null, null, null, null, null, null);
                if (temp.getMessage().equalsIgnoreCase("添加成功")) {
                    result.setCode(200);
                    result.setBody(temp.getIndex());
                    logger.info("新增监测点成功!");
                    userLog.getLog("新增监测点", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (temp.getMessage().equalsIgnoreCase("添加失败a")) {
                    result.setCode(400);
                    result.setMessage(temp.getMessage());
                    logger.error("新增监测点失败!监测点号已使用");
                    userLog.getLog("新增监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(temp.getMessage());
                    logger.error("新增监测点失败!");
                    userLog.getLog("新增监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }

            } catch (Exception e) {
                e.printStackTrace();
                result.setCode(500);
                result.setMessage("新增监测点失败!" + e.getMessage());
                logger.error("新增监测点失败!" + e.getMessage());
                userLog.getLog("新增监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }


    @RequestMapping(value = "updateLineBase", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateLine(HttpServletRequest request, Integer lineId, String lineName) {
        HttpResult result = new HttpResult();

        if (!PubUtils.patternDevname(lineName)) {
            result.setCode(500);
            result.setMessage("更新失败!名称违规");
            logger.error("更新监测点名称失败!");
            userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }

        String res = manaDeviceService.updateLine(lineId, lineName);
        if ("更新监测点成功".equals(res)) {
            result.setCode(200);
        } else {
            result.setCode(500);
        }
        result.setMessage(res);
        return result;
    }

    //修改监测点详情
    @RequestMapping(value = "updateLine", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateLine(HttpServletRequest request, String name, Long lineIndex, String dlcMp, String xycMp,
                                 String devcMp, String ct1, String ct2, String pt1, String pt2, Integer ptType, Integer tInterval,
                                 String loadType, String businessType, Integer powerId, String remark, String monitorId, String voltage,
                                 String uvoltage, String objName, Integer statFlag, String powerSubName, String calssificationGrade, String superiorsSubstation,
                                 String hangLine, String owner, String ownerDuty, String ownerTel, Integer isGridPoint, Integer lineStatus
    ) {
        HttpResult result = new HttpResult();
        Line line = new Line();
        LineDetail detail = new LineDetail();

        name = XssFilterUtil.dealString(name);
        dlcMp = XssFilterUtil.dealString(dlcMp);
        xycMp = XssFilterUtil.dealString(xycMp);
        devcMp = XssFilterUtil.dealString(devcMp);
        ct1 = XssFilterUtil.dealString(ct1);
        ct2 = XssFilterUtil.dealString(ct2);
        pt1 = XssFilterUtil.dealString(pt1);
        pt2 = XssFilterUtil.dealString(pt2);
        remark = XssFilterUtil.dealString(remark);
        monitorId = XssFilterUtil.dealString(monitorId);
        voltage = XssFilterUtil.dealString(voltage);
        uvoltage = XssFilterUtil.dealString(uvoltage);
        objName = XssFilterUtil.dealString(objName);
        if (StrUtil.isNotBlank(powerSubName)) {
            powerSubName = XssFilterUtil.dealString(powerSubName);
            if (!PubUtils.patternDevname(powerSubName)) {
                result.setCode(501);
                result.setMessage("更新失败!电网侧变电站名称违规");
                logger.error("更新监测点失败!");
                userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        if (!PubUtils.patternDevname(name)) {
            result.setCode(501);
            result.setMessage("更新失败!名称违规");
            logger.error("更新监测点失败!");
            userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternFloat(dlcMp) || !PubUtils.patternFloat(xycMp) || !PubUtils.patternFloat(devcMp)) {
            result.setCode(501);
            result.setMessage("更新失败!容量违规");
            logger.error("更新监测点失败!");
            userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternFloat(ct1) || !PubUtils.patternFloat(ct2)) {
            result.setCode(501);
            result.setMessage("更新失败!CT违规");
            logger.error("更新监测点失败!");
            userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternFloat(pt1) || !PubUtils.patternFloat(pt2)) {
            result.setCode(501);
            result.setMessage("更新失败!PT违规");
            logger.error("更新监测点失败!");
            userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternRemark(remark)) {
            result.setCode(501);
            result.setMessage("更新失败!备注违规");
            logger.error("更新监测点失败!");
            userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternmonitorid(monitorId)) {
            result.setCode(501);
            result.setMessage("更新失败!国网平台监测点号违规");
            logger.error("更新监测点失败!");
            userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                line.setLineIndex(lineIndex);
                line.setStatus(lineStatus);
                if (name != null && !name.equals("")) {
                    line.setName(name);
                }
                if (dlcMp != null && !dlcMp.equals("")) {
                    line.setDlcMp(Float.parseFloat(dlcMp));
                }
                if (xycMp != null && !xycMp.equals("")) {
                    line.setXycMp(Float.parseFloat(xycMp));
                }
                if (devcMp != null && !devcMp.equals("")) {
                    line.setDevcMp(Float.parseFloat(devcMp));
                }
                if (ct1 != null && !ct1.equals("")) {
                    line.setCt1(Float.parseFloat(ct1));
                }
                if (ct2 != null && !ct2.equals("")) {
                    line.setCt2(Float.parseFloat(ct2));
                }
                if (pt1 != null && !pt1.equals("")) {
                    line.setPt1(Float.parseFloat(pt1));
                }
                if (pt2 != null && !pt2.equals("")) {
                    line.setPt2(Float.parseFloat(pt2));
                }

                detail.setLineIndex(lineIndex);
                if (name != null && !name.equals("")) {
                    detail.setLineName(name);
                }
                if (ptType != null && !ptType.equals("")) {
                    detail.setPtType(ptType);
                }
                if (tInterval != null && !tInterval.equals("")) {
                    detail.setTInterval(tInterval);
                }
                if (loadType != null && !loadType.equals("")) {
                    detail.setLoadType(loadType);
                }
                if (businessType != null && !businessType.equals("")) {
                    detail.setBusinessType(businessType);
                }
                if (powerId != null && !powerId.equals("")) {
                    detail.setPowerId(powerId);
                }

                detail.setRemark(remark);
                detail.setMonitorId(monitorId);
                detail.setObjName(objName);
                detail.setPowerSubstationName(powerSubName);
                detail.setStatFlag(statFlag);
                detail.setCalssificationGrade(calssificationGrade);
                detail.setSuperiorsSubstation(superiorsSubstation);
                detail.setHangLine(hangLine);
                detail.setOwner(owner);
                detail.setOwnerDuty(ownerDuty);
                detail.setOwnerTel(ownerTel);
                detail.setIsGridPoint(isGridPoint);


                String message = manaDevice.updateLine(line, detail, voltage, uvoltage, PubUtils.getIpAddr(request));
                if (message.equalsIgnoreCase("更新成功")) {
                    result.setCode(200);
                    result.setMessage(message);
                    logger.info("更新监测点成功!");
                    //   userLog.getLog("修改监测点", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("更新失败")) {
                    result.setCode(400);
                    result.setMessage("更新失败,监测点已存在!");
                    logger.error("更新监测点失败!");
                    userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("更新监测点失败!");
                    userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }

            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("更新监测点失败!");
                logger.error("更新监测点失败!" + e.getMessage());
                userLog.getLog("修改监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "delLine", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult delLine(HttpServletRequest request, Long lineIndex) {
        HttpResult result = new HttpResult();

        try {
            String message = manaDevice.delLine(lineIndex, PubUtils.getIpAddr(request));
            if (message.equalsIgnoreCase("删除成功")) {
                result.setCode(200);
                result.setMessage(message);
                logger.info("删除监测点成功!");
                //  userLog.getLog("删除监测点", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                result.setCode(500);
                result.setMessage(message);
                logger.error("删除监测点失败!");
                userLog.getLog("删除监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }

        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("删除监测点失败!");
            logger.error("删除监测点失败!" + e.getMessage());
            userLog.getLog("删除监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    @RequestMapping(value = "loadLineIndex", method = RequestMethod.POST)
    @ResponseBody
    public Long loadLineIndex(HttpServletRequest request, Long devIndex) {
        Long lineIndex = 0L;
        try {
            Example example = new Example(Line.class);
            example.createCriteria().andEqualTo("devIndex", devIndex);
            example.orderBy("lineIndex");
            List<Line> result = lineMapper.selectByExample(example);
            if (result.size() > 0) {
                lineIndex = result.get(0).getLineIndex();
            }
            userLog.getLog("查询监测点索引", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 1);
        } catch (Exception e) {
            userLog.getLog("查询监测点索引", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 1);
        }
        return lineIndex;
    }

    @RequestMapping(value = "loadLine", method = RequestMethod.POST)
    @ResponseBody
    public LineDetailInfo loadLine(HttpServletRequest request, Long lineIndex) {
        LineDetailInfo result;
        try {
            result = manaDevice.loadLine(lineIndex);
            userLog.getLog("查询监测点", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            result = null;
            userLog.getLog("查询监测点", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        }
        return result;
    }

    /**
     * 点击监测点的推送，将数据保存至PMS_MONITOR
     * @param request
     * @param monitorId
     * @return
     */
    @RequestMapping(value = "addMonitor", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addMonitor(HttpServletRequest request, String monitorId) {
        HttpResult result = new HttpResult();
        try {

            int count = manaDevice.addMonitor(monitorId);
            if (count == 1){
                result.setCode(200);
                userLog.getLog("PQS_MONITOR入库", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            } else {
                result.setCode(201);
                userLog.getLog("PQS_MONITOR入库(重复入库)", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMessage("PQS_MONITOR入库失败!" + e.getMessage());
            logger.error("PQS_MONITOR入库失败!" + e.getMessage());
            userLog.getLog("PQS_MONITOR入库", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }



    @RequestMapping(value = "updateAllLimit", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateAllLimit(HttpServletRequest request) {
        HttpResult result = new HttpResult();

        try {
            manaDevice.updateAllLimit();
            result.setCode(200);
            result.setMessage("批量更新限值成功");
            logger.info("批量更新限值成功!");
            userLog.getLog("批量更新限值", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("批量更新限值失败!");
            logger.error("批量更新限值失败:" + e.toString());
            userLog.getLog("批量更新限值", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    @RequestMapping(value = "loadSysType", method = RequestMethod.POST)
    @ResponseBody
    public String loadSysType(HttpServletRequest request) {
        String result;
        String sysType = TokenManager.getSysType();
        String systypezt = appConfig.getSysTypeZt();
        if (sysType.equals(systypezt)) {
            result = "0";
        } else {
            result = "1";
        }
        userLog.getLog("查询系统类型", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        return result;
    }

    @RequestMapping(value = "getselect", method = RequestMethod.POST)
    @ResponseBody
    public List<DicData> getselect(HttpServletRequest request, String dictypeName) {
        List<DicData> result;
        try {
            result = getDeviceInfo.getdicdata(dictypeName);
        } catch (Exception e) {
            result = null;
        }
        userLog.getLog("查询字典数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        return result;
    }

    @RequestMapping(value = "getDicPro", method = RequestMethod.POST)
    @ResponseBody
    public List<DicData> getDicPro(HttpServletRequest request) {
        List<DicData> result;
        try {
            result = getDeviceInfo.getDicPro();
        } catch (Exception e) {
            result = null;
        }
        userLog.getLog("查询字典数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        return result;
    }

    @RequestMapping(value = "getNodeInfo", method = RequestMethod.POST)
    @ResponseBody
    public List<NodeInformation> getNodeInfo(HttpServletRequest request) {
        List<NodeInformation> result = getDeviceInfo.getNodeInfo();
        userLog.getLog("查询节点信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        return result;
    }

    @RequestMapping(value = "loadNodeInfo", method = RequestMethod.POST)
    @ResponseBody
    public String loadNodeInfo(HttpServletRequest request) throws JsonProcessingException {
        List<NodeInformation> result;
        List<List> s = new ArrayList<>();
        result = getDeviceInfo.loadNodeInfo();
        for (int i = 0; i < result.size(); i++) {
            List<String> a = new ArrayList<>();
            a.add(String.valueOf(result.get(i).getNodeIndex()));
            a.add(result.get(i).getNodeName());
            a.add(result.get(i).getNodeDesc());
            a.add(result.get(i).getNodeIP());
            if (result.get(i).getNodeStatus() == 0) {
                a.add("删除");
            } else {
                a.add("正常");
            }
            if (result.get(i).getNodeGrade() == 0) {
                a.add("重要");
            } else if (result.get(i).getNodeGrade() == 1) {
                a.add("普通");
            } else {
                a.add("备用");
            }

            if (Objects.nonNull(result.get(i).getNodeDevNum())) {
                a.add(result.get(i).getNodeDevNum().toString());
            } else {
                a.add("/");
            }
            if (Objects.nonNull(result.get(i).getNodeOrder())) {
                a.add(result.get(i).getNodeOrder().toString());
            } else {
                a.add("/");
            }
            s.add(a);
        }
        userLog.getLog("查询节点信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        return objectMapper.writeValueAsString(s);
    }

    @RequestMapping(value = "delNodeInfo", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult delNodeInfo(HttpServletRequest request, Long nodeIndex) {
        HttpResult result = new HttpResult();

        try {
            String message = getDeviceInfo.delNode(nodeIndex);
            if (message.equalsIgnoreCase("删除成功")) {
                result.setCode(200);
                result.setMessage(message);
                logger.info("删除前置机成功!");
                userLog.getLog("删除前置机", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                result.setCode(500);
                result.setMessage(message);
                logger.error("删除前置机失败!");
                userLog.getLog("删除前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }

        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("删除前置机失败!");
            logger.error("删除前置机失败!");
            userLog.getLog("删除前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    @RequestMapping(value = "addNode", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addNode(HttpServletRequest request, HttpSession session, String nodeName, String nodeDesc,
                              String ip4, String ip3, String ip2, String ip1, Integer nodeGrade, Integer nodeDevNum) {
        HttpResult result = new HttpResult();

        nodeName = XssFilterUtil.dealString(nodeName);
        nodeDesc = XssFilterUtil.dealString(nodeDesc);
        ip4 = XssFilterUtil.dealString(ip4);
        ip3 = XssFilterUtil.dealString(ip3);
        ip2 = XssFilterUtil.dealString(ip2);
        ip1 = XssFilterUtil.dealString(ip1);
        if (Objects.isNull(nodeGrade)) {
            result.setCode(501);
            result.setMessage("新增失败!等级不可为空");
            logger.error("新增前置机失败!");
        }
        if (Objects.isNull(nodeDevNum)) {
            result.setCode(501);
            result.setMessage("新增失败!最大装置数不可为空");
            logger.error("新增前置机失败!");
        }

        if (!PubUtils.patternDevname(nodeName)) {
            result.setCode(501);
            result.setMessage("新增失败!名称违规");
            logger.error("新增前置机失败!");
            userLog.getLog("新增前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternDes64(nodeDesc)) {
            result.setCode(501);
            result.setMessage("新增前置机失败!描述违规");
            logger.error("新增前置机失败!");
            userLog.getLog("新增前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternSIp(ip4) || !PubUtils.patternSIp(ip3) || !PubUtils.patternSIp(ip2)
                || !PubUtils.patternSIp(ip1)) {
            result.setCode(501);
            result.setMessage("新增前置机失败!IP违规");
            logger.error("新增前置机失败!");
            userLog.getLog("新增前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                String message = getDeviceInfo.saveNode(nodeName, nodeDesc, ip4, ip3, ip2, ip1, nodeGrade, nodeDevNum);
                if (message.equalsIgnoreCase("添加成功")) {
                    result.setCode(200);
                    result.setMessage(message);
                    logger.info("新增前置机成功!");
                    userLog.getLog("新增前置机", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("添加失败a")) {
                    result.setCode(400);
                    result.setMessage(message);
                    logger.error("新增前置机失败!名称已存在");
                    userLog.getLog("新增前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("新增前置机失败!");
                    userLog.getLog("新增前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }

            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("新增前置机失败!");
                logger.error("新增前置机失败!");
                userLog.getLog("新增前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    @RequestMapping(value = "loadNode", method = RequestMethod.POST)
    @ResponseBody
    public List<String> loadNode(HttpServletRequest request, Long nodeIndex) {
        List<String> result = new ArrayList<>();
        try {
            result = getDeviceInfo.loadNode(nodeIndex);
            userLog.getLog("查询前置机", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            result = null;
            userLog.getLog("查询前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }

        return result;
    }

    @RequestMapping(value = "modNode", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult modNode(HttpServletRequest request, Long nodeIndex, String nodeName, String nodeDesc, String ip4,
                              String ip3, String ip2, String ip1, Integer nodeGrade, Integer nodeDevNum, Integer nodeOrder) {
        HttpResult result = new HttpResult();

        nodeName = XssFilterUtil.dealString(nodeName);
        nodeDesc = XssFilterUtil.dealString(nodeDesc);
        ip4 = XssFilterUtil.dealString(ip4);
        ip3 = XssFilterUtil.dealString(ip3);
        ip2 = XssFilterUtil.dealString(ip2);
        ip1 = XssFilterUtil.dealString(ip1);
        if (!PubUtils.patternDevname(nodeName)) {
            result.setCode(501);
            result.setMessage("更新失败!名称违规");
            logger.error("更新前置机失败!");
            userLog.getLog("修改前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternDes64(nodeDesc)) {
            result.setCode(501);
            result.setMessage("更新前置机失败!描述违规");
            logger.error("更新前置机失败!");
            userLog.getLog("修改前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else if (!PubUtils.patternSIp(ip4) || !PubUtils.patternSIp(ip3) || !PubUtils.patternSIp(ip2)
                || !PubUtils.patternSIp(ip1)) {
            result.setCode(501);
            result.setMessage("更新前置机失败!IP违规");
            logger.error("更新前置机失败!");
            userLog.getLog("修改前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            try {
                String message = getDeviceInfo.updateNode(nodeIndex, nodeName, nodeDesc, ip4, ip3, ip2, ip1, nodeGrade, nodeDevNum, nodeOrder);
                if (message.equalsIgnoreCase("更新成功")) {
                    result.setCode(200);
                    result.setMessage(message);
                    logger.info("更新前置机成功!");
                    userLog.getLog("修改前置机", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("更新失败a")) {
                    result.setCode(400);
                    result.setMessage(message);
                    logger.error("更新前置机失败!名称已存在");
                    userLog.getLog("修改前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("更新前置机失败!");
                    userLog.getLog("修改前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }

            } catch (Exception e) {
                result.setCode(500);
                result.setMessage("更新前置机失败!");
                logger.error("更新前置机失败!");
                userLog.getLog("修改前置机", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        }
        return result;
    }

    /**
     * 9900终端导入功能
     *
     * @date 2021/7/13
     */
    @RequestMapping(value = "importDev", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult importDev(@RequestParam(value = "file", required = false) MultipartFile file,
                                HttpServletRequest request, HttpServletResponse response) {
        HttpResult result;
        String errmess = "错误提示:";

        /**
         * ----------------------------------------------------------------------------------------------
         * xuyang 2020.08.25
         * 修改：对上传文件做判断
         * 1.文件类型 2.文件大小
         */
        //文件名
        String fileName = file.getOriginalFilename();
        //文件大小(此大小为kb)
        Long fileSize = file.getSize() / 1024;
        //获取文件后缀,判断上传文件格式
        String subffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        //判断文件大小
        if (fileSize > 3072) {
            result = PubUtils.assignmentResult(errmess, 500, "上传失败,上传文件超过3M，文件过大!");
            return result;
        }
        //判断文件类型
        if (!"xls".equals(subffix) && !"xlsx".equals(subffix)) {
            result = PubUtils.assignmentResult(errmess, 500, "文件类型错误，只能上传Excel文件！");
            return result;
        }
        /**
         * over
         * ----------------------------------------------------------------------------------------------
         */

        ImportExl exl = new ImportExl();
        List<DevList> devList = exl.getExcelInfo(file);

        try {
            for (int i = 0; i < devList.size(); i++) {
                DevList list = devList.get(i);
                if (list == null) {
                    break;
                }
                int linenum = i + 3;
                String projectName = XssFilterUtil.dealString(list.getProjectName());
                AddResult project = manaDevice.saveProjectInfo(projectName);
                Long projectIndex = project.getIndex();

                String proname = XssFilterUtil.dealString(list.getProName());
                AddResult pro = manaDevice.saveProInfo(proname, projectIndex);
                Long proIndex = pro.getIndex();

                String dept = list.getDept();
                Depts depts = new Depts();
                depts = deptsMapper.selByName(dept);
                if (depts == null) {
                    errmess += "第" + linenum + "行部门名称对应部门不存在!";
                    break;
                }
                AddResult gd = manaDevice.saveGdInfo(XssFilterUtil.dealString(list.getGdName()), proIndex);
                String gdIndex = String.valueOf(gd.getIndex());

                List<DicData> sca0 = dicDataMapper.selectdicName(XssFilterUtil.dealString(list.getSubScale()));
                if (CollectionUtil.isEmpty(sca0)) {
                    errmess += "第" + linenum + "行变电站电压等级有误!";
                    break;
                }
                AddResult sub = manaDevice.saveSubInfo(XssFilterUtil.dealString(list.getSubName()), gdIndex, list.getLongItude(),
                        list.getLatItude(), sca0.get(0).getDicIndex());
                String subIndex = String.valueOf(sub.getIndex());

                DeviceInfo dev = new DeviceInfo();
                List<DicData> manu = dicDataMapper.selectdicName(XssFilterUtil.dealString(list.getManufacturer()));
                dev.setGdIndex(gd.getIndex());
                dev.setSubIndex(sub.getIndex());
                dev.setName(XssFilterUtil.dealString(list.getDevName()));
                dev.setIp(XssFilterUtil.dealString(list.getIp()));
                dev.setManufacturer(manu.get(0).getDicIndex());
                String devmodel = XssFilterUtil.dealString(list.getDevmodel());
                switch (devmodel) {
                    case "虚拟终端":
                        dev.setDevmodel(Long.valueOf(0));
                        break;
                    case "实际终端":
                        dev.setDevmodel(Long.valueOf(1));
                        break;
                    default:
                        dev.setDevmodel(Long.valueOf(2));
                        break;
                }
                List<DicData> devtypes = dicDataMapper.selectdicName(XssFilterUtil.dealString(list.getDevtype()));
                if (CollectionUtil.isEmpty(devtypes)) {
                    errmess += "第" + linenum + "行装置类型有误!字典表中没有该设备型号";
                    break;
                }
                dev.setDevType(devtypes.get(0).getDicIndex());
                NodeInformation nodeTmp = nodeInformationMapper.selByName(XssFilterUtil.dealString(list.getNodename()));
                if (nodeTmp == null) {
                    errmess += "第" + linenum + "行前置机名称对应前置机不存在!";
                    break;
                }
                dev.setNodeIndex(nodeTmp.getNodeIndex());
                dev.setPortId(Long.valueOf(list.getPortid()));
                dev.setSeries(XssFilterUtil.dealString(list.getSeries()));
                dev.setKey(XssFilterUtil.dealString(list.getKey()));
                dev.setSim(list.getSim());
                dev.setDevLocation(list.getDevLocation());
                dev.setDevNo(list.getDevNo());
                AddResult device = manaDevice.saveDevInfo(dev);
                if (device.getMessage().equals("添加失败b")) {
                    errmess += "第" + linenum + "行终端网络端口已被使用!";
                    break;
                }
                String devIndex = String.valueOf(device.getIndex());

                List<DicData> sca = dicDataMapper.selectdicName(XssFilterUtil.dealString(list.getScale()));
                if (sca == null) {
                    errmess += "第" + linenum + "行电压等级有误!";
                    break;
                }
                Long subvModel = (long) 1;
                AddResult subv = manaDevice.saveSubvInfo(XssFilterUtil.dealString(list.getSubvName()), gdIndex, subIndex, devIndex,
                        list.getSubvnum(), sca.get(0).getDicIndex(), subvModel);

                Line line = new Line();
                line.setGdIndex(gd.getIndex());
                line.setSubIndex(sub.getIndex());
                line.setDevIndex(device.getIndex());
                line.setSubvIndex(subv.getIndex());
                line.setName(XssFilterUtil.dealString(list.getLineName()));
                String ct = XssFilterUtil.dealString(list.getCt());
                String[] ctstr = ct.split("/");
                line.setCt1(Float.parseFloat(ctstr[0]));
                line.setCt2(Float.parseFloat(ctstr[1]));
                String pt = XssFilterUtil.dealString(list.getPt());
                String[] ptstr = pt.split("/");
                line.setPt1(Float.parseFloat(ptstr[0]));
                line.setPt2(Float.parseFloat(ptstr[1]));
                line.setDlcMp(list.getDlrl());
                line.setDevcMp(list.getSbrl());
                line.setXycMp(list.getXyrl());
                int lineNum = list.getLineNum();
                int statFlag = 1;
                //监测点运行状态
                String status = XssFilterUtil.dealString(list.getStatus());
                switch (status) {
                    case "投运":
                        line.setStatus(0);
                        break;
                    case "检修":
                        line.setStatus(1);
                        break;
                    default:
                        line.setStatus(2);
                        break;
                }
                //行业类型
                List<DicData> hy = dicDataMapper.selectdicName(XssFilterUtil.dealString(list.getBusinessType()));
                if (sca == null) {
                    errmess += "第" + linenum + "行行业有误!";
                    break;
                }
                //监测点性质
                String powerName = XssFilterUtil.dealString(list.getPowerId());
                Integer powerId;
                switch (powerName) {
                    case "电网侧":
                        powerId = 0;
                        break;
                    case "非电网侧":
                        powerId = 1;
                        break;
                    case "电网侧(新能源)":
                        powerId = 2;
                        break;
                    case "非电网侧(新能源)":
                        powerId = 3;
                        break;
                    case "上送国网":
                        powerId = 4;
                        break;
                    default://PCC
                        powerId = 5;
                        break;
                }
                if (StrUtil.isNotBlank(list.getStatFlag())) {
                    if (list.getStatFlag().equals("不参与统计")) {
                        statFlag = 0;
                    } else {
                        statFlag = 1;
                    }
                }
                Integer isGridPoint = null;
                if (StrUtil.isNotBlank(list.getIsGridPoint())) {
                    if (list.getStatFlag().equals("否")) {
                        isGridPoint = 0;
                    } else {
                        isGridPoint = 1;
                    }
                }
                List<DicData> loadt = dicDataMapper.selectdicName(XssFilterUtil.dealString(list.getLoadType()));
                AddResult lin = manaDevice.saveLineInfo(line, depts.getDeptsIndex(),
                        lineNum, XssFilterUtil.dealString(list.getMonitorid()), XssFilterUtil.dealString(list.getPttype()), loadt.get(0).getDicIndex(), list.getInterval(), list.getObjName(), statFlag,
                        hy.get(0).getDicIndex(),powerId,list.getPowerSubstationName(), isGridPoint
                );

                // 根据文件名和监测点id查询offl_log是否已有数据存在
                int count;

                try {
                    count = manaDeviceService.getCount((int) (line.getDevIndex() * 10 + lineNum), XssFilterUtil.dealString(list.getFileName()),
                            null);
                } catch (Exception e) {
                    count = 0;
                }

                if (!StringUtils.isEmpty(XssFilterUtil.dealString(list.getFileName()))) {
                    if (count == 0 && list.getFileName().indexOf(".bin") > -1) { // 如果传入的模板有文件名则记录信息到offl_log表
                        OfflLog offlLog = new OfflLog();
                        String filePath = appConfig.getTmppath() + "files" + File.separator + XssFilterUtil.dealString(list.getFileName());
                        offlLog.setDataPath(filePath); // 监测点数据文件
                        offlLog.setLineIndex(line.getDevIndex() * 10 + lineNum); // 监测点号
                        offlLog.setLogsIndex(UUID.randomUUID().toString()); // guid
                        offlLog.setName(XssFilterUtil.dealString(list.getFileName())); // 文件名根据数据文件生成
                        offlLog.setUserIndex(TokenManager.getToken().getUserIndex()); // 执行导入操作的用户id
                        offlLog.setImporttime(new Date()); // 执行导入的时间
                        offlLog.setState(0); // 数据文件的解析状态
                        // 执行入库操作
                        manaDeviceService.insertOFFlog(offlLog);
                    }
                }

                if (gd.getMessage().lastIndexOf("添加失败") > 0 || sub.getMessage().lastIndexOf("添加失败") > 0
                        || device.getMessage().lastIndexOf("添加失败") > 0 || subv.getMessage().lastIndexOf("添加失败") > 0
                        || lin.getMessage().lastIndexOf("添加失败") > 0) {
                    errmess += "第" + linenum + "行";
                    if (gd.getMessage().equals("添加失败")) {
                        errmess += "供电公司或部门,";
                    }
                    if (sub.getMessage().equals("添加失败")) {
                        errmess += "变电站或经纬度,";
                    }
                    if (device.getMessage().equals("添加失败")) {
                        errmess += "装置相关信息,";
                    }
                    if (subv.getMessage().equals("添加失败")) {
                        errmess += "母线相关信息,";
                    }
                    if (lin.getMessage().equals("添加失败")) {
                        errmess += "监测点相关信息<br />";
                    }
                }
            }

            if (errmess.equals("错误提示:")) {
                errmess += "无";
            } else {

            }
            result = PubUtils.assignmentResult(errmess, 200, "上传成功");
            userLog.getLog("上传终端信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导入终端失败,方法名：importdev");
            userLog.getLog("上传终端信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            result = PubUtils.assignmentResult(null, 500, "上传失败");
        }

        return result;
    }

    @PostMapping(value = "/exportDev")
    @ResponseBody
    public String exportDev(HttpServletRequest request) throws Exception {
        String systype = TokenManager.getSysType();
        String wt = appConfig.getSysTypeWt();
        String zt = appConfig.getSysTypeZt();
        List<Integer> type = new ArrayList<>();
        String sysType;
        if (systype.equals(wt)) {
            type.add(1);
            type.add(2);
            sysType = wt;
        } else {
            type.add(0);
            type.add(2);
            sysType = zt;
        }
        try {
            this.exportinfo = exportDevMapper.getExportDev(sysType, type);
            userLog.getLog("导出终端信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            return "success";
        } catch (Exception e) {
            userLog.getLog("导出终端信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            return "fail";
        }

    }

    @GetMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response, HttpServletRequest request) {
        // 第一步，创建一个webbook，对应一个Excel文件
        XSSFWorkbook wb = new XSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        XSSFSheet sheet = wb.createSheet("sheet1");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        XSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        XSSFCellStyle style = wb.createCellStyle();

        XSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("批量导入模板（请严格按照模板标准填入数据）");
        cell.setCellStyle(style);

        row = sheet.createRow((int) 1);
        cell = row.createCell((short) 0);
        cell.setCellValue("项目名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("省份");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("所属公司");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("所属部门");
        cell.setCellStyle(style);
        cell = row.createCell((short) 4);
        cell.setCellValue("变电站（场站）名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 5);
        cell.setCellValue("变电站电压等级");
        cell.setCellStyle(style);
        cell = row.createCell((short) 6);
        cell.setCellValue("经度");
        cell.setCellStyle(style);
        cell = row.createCell((short) 7);
        cell.setCellValue("纬度");
        cell.setCellStyle(style);
        cell = row.createCell((short) 8);
        cell.setCellValue("装置编号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 9);
        cell.setCellValue("IP地址");
        cell.setCellStyle(style);
        cell = row.createCell((short) 10);
        cell.setCellValue("终端厂家");
        cell.setCellStyle(style);
        cell = row.createCell((short) 11);
        cell.setCellValue("终端模型");
        cell.setCellStyle(style);
        cell = row.createCell((short) 12);
        cell.setCellValue("终端型号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 13);
        cell.setCellValue("所属前置机名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 14);
        cell.setCellValue("端口号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 15);
        cell.setCellValue("识别码");
        cell.setCellStyle(style);
        cell = row.createCell((short) 16);
        cell.setCellValue("秘钥");
        cell.setCellStyle(style);
        cell = row.createCell((short) 17);
        cell.setCellValue("母线名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 18);
        cell.setCellValue("母线号(1-6)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 19);
        cell.setCellValue("电压等级");
        cell.setCellStyle(style);
        cell = row.createCell((short) 20);
        cell.setCellValue("接入电网侧变电站名");
        cell.setCellStyle(style);
        cell = row.createCell((short) 21);
        cell.setCellValue("监测点名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 22);
        cell.setCellValue("监测点号(1-6)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 23);
        cell.setCellValue("PT变比");
        cell.setCellStyle(style);
        cell = row.createCell((short) 24);
        cell.setCellValue("CT变比");
        cell.setCellStyle(style);
        cell = row.createCell((short) 25);
        cell.setCellValue("短路容量(默认值10)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 26);
        cell.setCellValue("设备容量(默认值10)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 27);
        cell.setCellValue("协议容量(默认值10)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 28);
        cell.setCellValue("接线类型");
        cell.setCellStyle(style);
        cell = row.createCell((short) 29);
        cell.setCellValue("*测量间隔(分钟)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 30);
        cell.setCellValue("干扰源类型");
        cell.setCellStyle(style);
        cell = row.createCell((short) 31);
        cell.setCellValue("国网ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 32);
        cell.setCellValue("监测点对象名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 33);
        cell.setCellValue("统计类型");
        cell.setCellStyle(style);
        cell = row.createCell((short) 34);
        cell.setCellValue("设备状态");
        cell.setCellStyle(style);
        cell = row.createCell((short) 35);
        cell.setCellValue("监测点性质");
        cell.setCellStyle(style);
        cell = row.createCell((short) 36);
        cell.setCellValue("是否并网点");
        cell.setCellStyle(style);

        int rowid = 2;
        List<ExportDev> list = this.exportinfo;
        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                ExportDev rowinfo = list.get(i);
                row = sheet.createRow(rowid);
                cell = row.createCell((short) 0);
                cell.setCellValue(rowinfo.getProjname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 1);
                cell.setCellValue(rowinfo.getProname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 2);
                cell.setCellValue(rowinfo.getGdname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 3);
                cell.setCellValue(rowinfo.getDeptsname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 4);
                cell.setCellValue(rowinfo.getSubname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 5);
                cell.setCellValue(rowinfo.getSubScale());
                cell.setCellStyle(style);
                cell = row.createCell((short) 6);
                cell.setCellValue(rowinfo.getLongitude());
                cell.setCellStyle(style);
                cell = row.createCell((short) 7);
                cell.setCellValue(rowinfo.getLatitude());
                cell.setCellStyle(style);
                cell = row.createCell((short) 8);
                cell.setCellValue(rowinfo.getDevname());
                cell.setCellStyle(style);
                cell = row.createCell((short) 9);
                cell.setCellValue(rowinfo.getIp());
                cell.setCellStyle(style);
                cell = row.createCell((short) 10);
                cell.setCellValue(rowinfo.getManufacturer());
                cell.setCellStyle(style);
                cell = row.createCell((short) 11);
                cell.setCellValue(rowinfo.getDevmodel());
                cell.setCellStyle(style);
                cell = row.createCell((short) 12);
                cell.setCellValue(rowinfo.getDevtype());
                cell.setCellStyle(style);
                cell = row.createCell((short) 13);
                cell.setCellValue(rowinfo.getNodename());
                cell.setCellStyle(style);
                cell = row.createCell((short) 14);
                cell.setCellValue(rowinfo.getPortid());
                cell.setCellStyle(style);
                cell = row.createCell((short) 15);
                try {
                    if (rowinfo.getSeries() == null || rowinfo.getSeries() == "") {
                        cell.setCellValue("");
                    } else {
                        String seriesTmp = TerminalUtil.decoderString(appConfig.getCdkeyEncy(), rowinfo.getSeries());
                        Boolean strResult = seriesTmp.matches("-?[0-9]+.？[0-9]*");
                        if (strResult == true) {
                            seriesTmp = new BigDecimal(seriesTmp).toString();
                        }

                        cell.setCellValue(seriesTmp);
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 16);
                    if (rowinfo.getKeym() == null || rowinfo.getKeym() == "") {
                        cell.setCellValue("");
                    } else {
                        String keyTmp = ThreeDes.decryptThreeDes(rowinfo.getKeym());
                        cell.setCellValue(keyTmp);
                    }
                    cell.setCellStyle(style);


                } catch (Exception e) {
                    logger.error(e.getMessage());
                    // TODO: handle exception
                } finally {
                    // TODO: handle finally clause
                    cell = row.createCell((short) 17);
                    cell.setCellValue(rowinfo.getSubvname());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 18);
                    cell.setCellValue(rowinfo.getSubvnum());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 19);
                    cell.setCellValue(rowinfo.getScale());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 20);
                    if (StringUtils.isEmpty(rowinfo.getPowerSubstationName())) {
                        cell.setCellValue(rowinfo.getSubname());
                    } else {
                        cell.setCellValue(rowinfo.getPowerSubstationName());
                    }
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 21);
                    cell.setCellValue(rowinfo.getLinename());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 22);
                    cell.setCellValue(rowinfo.getLinenum());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 23);
                    cell.setCellValue(rowinfo.getPt());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 24);
                    cell.setCellValue(rowinfo.getCt());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 25);
                    cell.setCellValue(rowinfo.getDlrl());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 26);
                    cell.setCellValue(rowinfo.getSbrl());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 27);
                    cell.setCellValue(rowinfo.getXyrl());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 28);
                    cell.setCellValue(rowinfo.getPtType());
                    cell.setCellStyle(style);

                    cell = row.createCell((short) 29);
                    cell.setCellValue(rowinfo.getInterval());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 30);
                    cell.setCellValue(rowinfo.getLoadtype());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 31);
                    cell.setCellValue(rowinfo.getMonitorid());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 32);
                    cell.setCellValue(rowinfo.getObjName());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 33);
                    cell.setCellValue(rowinfo.getStatFlag());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 34);
                    cell.setCellValue(rowinfo.getDevFlag());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 35);
                    cell.setCellValue(rowinfo.getPowerid());
                    cell.setCellStyle(style);
                    cell = row.createCell((short) 36);
                    cell.setCellValue(rowinfo.getIsGridPoint());
                    cell.setCellStyle(style);
                    rowid++;
                }
            }
        }

        try {
            response.setContentType("application/force-download");
            String str = "台账导出";
            response.addHeader("Content-Disposition",
                    "attachment;fileName=" + new String(str.getBytes("GB2312"), "iso8859-1") + ".xlsx");// 设置文件名
            OutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            wb.close();
            outputStream.close();
            userLog.getLog("导出台账信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (IOException e) {
            userLog.getLog("导出台账信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            logger.error("台账导出发生了异常，异常是" + e.getMessage());
        }
    }

    @RequestMapping(value = "setIp", method = RequestMethod.POST)
    @ResponseBody
    public NodeInformation setIp(int nodeIndex, HttpServletRequest request) {
        NodeInformation nodeInformation = new NodeInformation();
        try {
            nodeInformation = getDeviceInfo.setIp(nodeIndex);
        } catch (Exception e) {
            // TODO: handle exception
        }
        userLog.getLog("设置IP", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        return nodeInformation;
    }

    @RequestMapping(value = "websocketon", method = RequestMethod.POST)
    @ResponseBody
    public String websocketon(HttpServletResponse response, HttpServletRequest request) {
        String result = "";
        try {
            result = appConfig.getWebsocket();
        } catch (Exception e) {
            result = "socket连接失败";
        }
        return result;
    }

    @RequestMapping(value = "socketoReset", method = RequestMethod.POST)
    @ResponseBody
    public String socketoReset(HttpServletRequest request, String typeid, String lineIndex) {
        String result = "";
        String ip = PubUtils.getIpAddr(request);
        try {
            result = versionService.socketoReset(ip, typeid, lineIndex);
        } catch (Exception e) {
            result = "socket连接失败";
        }
        return result;
    }

    @RequestMapping(value = "socketon", method = RequestMethod.POST)
    @ResponseBody
    public String socketon(HttpServletRequest request, String typeid, String lineIndex, Long hander) {
        String result = "";
        String ip = PubUtils.getIpAddr(request);
        try {
            result = versionService.sentLine(ip, typeid, lineIndex, hander);
        } catch (Exception e) {
            result = "socket连接失败";
        }
        return result;
    }

    @RequestMapping(value = "updatesocketonDev", method = RequestMethod.POST)
    @ResponseBody
    public String updatesocketonDev(HttpServletRequest request, String typeid, String lineIndex, Long hander, String interValue) {
        String result = "";
        String ip = PubUtils.getIpAddr(request);
        result = versionService.sentUpdateDev(ip, typeid, lineIndex, hander, interValue);
        return result;
    }

    @RequestMapping(value = "updatesocketon", method = RequestMethod.POST)
    @ResponseBody
    public String updatesocketon(HttpServletRequest request, String typeid, String lineIndex, Long hander, String value) {
        String result = "";
        String ip = PubUtils.getIpAddr(request);
        result = versionService.sentUpdateLine(ip, typeid, lineIndex, hander, value);
        return result;
    }

    @RequestMapping(value = "socketonDev", method = RequestMethod.POST)
    @ResponseBody
    public String socketonDev(HttpServletRequest request, String typeid, String lineIndex, Long hander) {
        String result = "";
        String ip = PubUtils.getIpAddr(request);
        try {
            result = versionService.sentDev(ip, typeid, lineIndex, hander);
        } catch (Exception e) {
            result = "socket连接失败";
        }
        return result;
    }

    @RequestMapping(value = "loadpushInfo", method = RequestMethod.POST)
    @ResponseBody
    public String getpushInfo(HttpServletRequest request) throws JsonProcessingException {
        List<PushInfo> result;
        List<List> s = new ArrayList<>();

        int j = 0;

        result = pushInfoMapper.selAll();

        for (int i = 0; i < result.size(); i++) {
            List<String> a = new ArrayList<>();
            a.add(result.get(i).getNodeName());
            a.add(result.get(i).getNodeIP());
            if (result.get(i).getPushType() == 0) {
                a.add("终端");
            } else {
                a.add("监测点");
            }
            a.add(result.get(i).getMyName());
            if (result.get(i).getActType() == 0) {
                a.add("新增");
            } else if (result.get(i).getActType() == 1) {
                a.add("修改");
            } else {
                a.add("删除");
            }
            if (result.get(i).getState() == 0) {
                a.add("已删除");
            } else if (result.get(i).getState() == 1) {
                a.add("未推送");
            } else {
                a.add("已推送");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            a.add(sdf.format(result.get(i).getUpdateTime()));
            s.add(a);
        }
        userLog.getLog("查询推送消息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        return objectMapper.writeValueAsString(s);
    }

    @PostMapping("/uploader")
    @ResponseBody
    public HttpResult upload(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = Murequest.getFileMap();// 得到文件map对象
        String id = Murequest.getParameter("id");
        String upaloadUrl = appConfig.getTmppath() + "files" + File.separator;
        File dir = new File(upaloadUrl);
        HttpResult httpResult = new HttpResult();
        httpResult.setCode(200);
        if (!dir.exists())// 目录不存在则创建
        {
            dir.mkdirs();
        }
        for (MultipartFile file : files.values()) {
            String fileName = file.getOriginalFilename();
            //判断上传名称是xlsx和bin后缀
            if (!JudgeFileType.judgeExcel(fileName) && !JudgeFileType.judgeBin(fileName)) {
                httpResult = PubUtils.assignmentResult(null, 500, "上传文件非法");
            }
            if (fileName.contains(".xlsx")) { // 防止单点传入了excel文件
                if (Integer.parseInt(id) != -1) {
                    continue;
                }
                httpResult = importDev(file, request, response);
                if (!httpResult.getBody().equals("错误提示:无")) {
                    httpResult.setCode(2019);
                    return httpResult;
                }
                httpResult.setCode(2020);
                Date date = new Date();
                DateFormat bf = new SimpleDateFormat("yyyyMMddHHmmss");
                String name = fileName.substring(0, fileName.indexOf(".xlsx"));
                fileName = name + "_" + bf.format(date) + ".xlsx"; // 改变excel文件名保存在这里
            }

            File tagetFile = new File(upaloadUrl + fileName);

            // 如果是单点上传
            if (Integer.parseInt(id) != -1) {
                // 根据文件名和监测点id查询offl_log是否已有数据存在
                int count;

                try {
                    count = manaDeviceService.getCount(Integer.parseInt(id), fileName, null);
                } catch (Exception e) {
                    count = 0;
                }

                if (count == 0 && fileName.indexOf(".bin") > -1) { // 如果传入的模板有文件名则记录信息到offl_log表
                    OfflLog offlLog = new OfflLog();
                    offlLog.setLineIndex((long) Integer.parseInt(id)); // 监测点号
                    offlLog.setLogsIndex(UUID.randomUUID().toString()); // guid
                    offlLog.setDataPath(upaloadUrl + fileName); // 监测点数据文件
                    offlLog.setName(fileName);
                    // 文件名根据数据文件生成
                    offlLog.setUserIndex(TokenManager.getToken().getUserIndex()); // 执行导入操作的用户id
                    offlLog.setState(0); // 数据文件的解析状态
                    offlLog.setImporttime(new Date());// 执行导入的时间
                    // 执行入库操作
                    manaDeviceService.insertOFFlog(offlLog);
                }
            }

            if (!tagetFile.exists()) {
                try {
                    tagetFile.createNewFile();
                } catch (IOException e) {
                    logger.error("产生了异常，异常是" + e.getMessage());
                }

                try {
                    file.transferTo(tagetFile);
                } catch (IllegalStateException | IOException e) {
                    logger.error("产生了异常，异常是" + e.getMessage());
                }
            }
        }

        if (httpResult.getCode() == 500) {
            userLog.getLog("上传离线数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } else {
            userLog.getLog("上传离线数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }

        return httpResult;
    }

    @PostMapping("/existfile")
    @ResponseBody
    public List<String> fileExist(String filename, int lineid) { //判断服务器文件是否存在,不存在返回到前台上传文件
        List<String> file = new ArrayList<>();
        String path = appConfig.getTmppath() + "files" + File.separator;
        String[] files = filename.split(",");

        for (String name : files) {
            File f = new File(path + name);

            if (!f.exists() || lineid != 0 && manaDevice.getCount(lineid, name, 1) == 0) {

                if (manaDevice.getCount(lineid, name, 1) == 1) {
                    String filePath = path + name;
                    manaDevice.updateOFFlog(null, null, null, 0, name, lineid, new Date(), 0, 0, null);
                }

                file.add(name);
            }
        }

        return file;
    }

    @PostMapping("/translate")
    @ResponseBody
    public HttpResult translate() {
        TranslateThread translateThread = new TranslateThread(homeostasis, manaDeviceService);
        translateThread.setName("translate");
        translateThread.start();// 开启解析线程
        return new HttpResult();
    }

    @PostMapping("/getTranslateState")
    @ResponseBody
    public HttpResult getTranslateState() {
        HttpResult httpResult = new HttpResult();
        httpResult.setCode(0);

        if (threadAlive("translate") == 1) { //线程已开启，前台提示等待
            return httpResult;
        }

        httpResult.setCode(1);
        return httpResult;
    }

    private int threadAlive(String name) {//判断线程是否还在运行
        ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
        int index = threadGroup.activeCount();
        Thread[] threads = new Thread[index];
        threadGroup.enumerate(threads);

        for (int i = 0; i < index; i++) {
            if (threads[i].getName().equals(name)) {
                return 1;
            }
        }

        return 0;
    }

    /**
     * 离线终端树
     */
    @RequestMapping(value = "offLinetree", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getOffLineTree(HttpServletRequest request) {
        HttpResult result;
        User user = TokenManager.getToken();

        try {
            List<Tree> data = getDeviceTree.getOffLineTree(user.getLoginName(), 0);
            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("queryTranslateState")
    @ResponseBody
    public HttpResult queryTranslateState(String start, String end) {
        HttpResult result;
        DatePojo datePojo = PubUtils.validateDate(start, end, "queryTranslateState");

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

        try {
            List<TranslateState> list = manaDeviceService.getTranslateState(datePojo.getStartTime(),
                    datePojo.getEndTime());
            result = PubUtils.assignmentResult(list, 200, "success");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "后台获取数据失败");
        }

        return result;
    }

    @PostMapping("queryimportLoading")
    @ResponseBody
    public HttpResult queryimportLoading() {
        HttpResult httpResult = new HttpResult();
        httpResult.setCode(0);

        if (threadAlive("translate") == 1) { //如果解析线程开启，则获取当前解析文件的数据情况
            TranslateState translateState = manaDeviceService.queryimportLoading();

            if (translateState != null) {
                httpResult.setBody(translateState);
                return httpResult;
            }
        }

        httpResult.setCode(1);
        return httpResult;
    }

    @PostMapping("deleteLoading")
    @ResponseBody
    public HttpResult deleteLoading() {
        HttpResult httpResult = new HttpResult();
        httpResult.setCode(0);

        if (threadAlive("deleteing") == 1) {
            return httpResult;
        }

        httpResult.setCode(1);
        return httpResult;
    }

    @GetMapping(value = "/export")
    public void export(HttpServletResponse response, HttpServletRequest request) {
        try {
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName="
                    + new String("模板".getBytes("GB2312"), "iso8859-1") + ".xlsx");// 设置文件名
            OutputStream outputStream = response.getOutputStream();
            manaDeviceService.export(outputStream);
            outputStream.close();
            userLog.getLog("导出模板数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (IOException e) {
            logger.error("产生了异常，异常是" + e.getMessage());
            userLog.getLog("导出模板数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        }
    }

    @GetMapping(value = "/downDevPloy")
    public void downDevPloy(HttpServletResponse response, HttpServletRequest request) {
        try {
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName="
                    + new String("台账模板".getBytes("GB2312"), "iso8859-1") + "_" + PubUtils.getNow() + ".xlsx");// 设置文件名
            OutputStream outputStream = response.getOutputStream();
            manaDeviceService.downDevPloy(outputStream);
            outputStream.close();
            userLog.getLog("导出台账模板数据", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (IOException e) {
            logger.error("产生了异常，异常是" + e.getMessage());
            userLog.getLog("导出台账模板数据", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        }
    }

    @PostMapping(value = "deleteTranslate")
    @ResponseBody
    public HttpResult deleteTranslate(String guid) { //开启线程删除操作
        HttpResult httpResult = new HttpResult();
        httpResult.setCode(0);

        if (threadAlive("deleteing") == 1) {
            return httpResult;
        }

        DeleteThread deleteThread = new DeleteThread(guid, manaDevice);
        deleteThread.setName("deleteing");
        deleteThread.start();
        httpResult.setCode(1);
        return httpResult;
    }

    @PostMapping("pushNode")
    @ResponseBody
    public HttpResult pushNode(String message, HttpServletRequest request) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        HttpResult result;
        List<String> nodeindexs;
        nodeindexs = pushNode.getNodes();
        int m = 0, n = 0;
        if (nodeindexs.size() == 0) {
            result = PubUtils.assignmentResult(null, 500, "暂无推送消息");

        } else {
            for (int i = 0; i < nodeindexs.size(); i++) {
                String receive = null;
                String port = nodeindexs.get(i);
                Callable<String> call = new Callable<String>() {
                    public String call() throws Exception {
                        // 开始执行耗时操作
                        // Thread.sleep(1000 * 5);
                        // return "线程执行完成.";
                        // 响应时间较长的方法或接口调用，返回String类型
                        return pushNode.sentSocket(message, port);
                    }
                };
                Future<String> future = executorService.submit(call);
                try {
                    receive = future.get(5, TimeUnit.SECONDS);
                } catch (InterruptedException | ExecutionException | TimeoutException e) {
                    future.cancel(true);
                } finally {
                    if (receive != null) {
                        if (receive.substring(27, 32).equals("10000")) {
                            m++;
                            pushNode.delByNodeIP(nodeindexs.get(i));
                        } else {
                            n++;
                        }
                    } else {
                        n++;
                    }
                }
            }
            String tips = "共推送" + nodeindexs.size() + "条信息,成功" + m + "条,失败" + n + "条";
            result = PubUtils.assignmentResult(null, 200, tips);
            userLog.getLog("推送消息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        }

        return result;
    }


    /**
     * 国网台账获取监测点的数据信息
     *
     * @param lineIndex 监测点索引
     */
    @PostMapping(value = "loadgwLine")
    @ResponseBody
    public HttpResult loadgwLine(String lineIndex, String monitorID, HttpServletRequest request) {
        HttpResult httpResult;
        Monitor monitor;
        try {
            monitor = lineService.loadgwLine(lineIndex, monitorID);
            if (null == monitor) {
                httpResult = PubUtils.assignmentResult(null, 500, "缺失国网监测点信息");
            } else {
                httpResult = PubUtils.assignmentResult(monitor, 200, "获取国网台账监测点信息成功");
            }
            userLog.getLog("查询国网监测点信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            logger.error("获取国网台账监测点信息异常，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult(null, 500, "获取国网台账监测点信息异常");
            userLog.getLog("查询国网监测点信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return httpResult;
    }

    /**
     * 国网台账获取变电站的数据信息
     *
     * @param subIndex 变电站索引
     */
    @PostMapping(value = "loadgwSubstation")
    @ResponseBody
    public HttpResult loadgwSubstation(String subIndex, HttpServletRequest request) {
        HttpResult httpResult;
        Znycdz znycdz;
        try {
            znycdz = lineService.loadgwSubstation(subIndex);
            if (null == znycdz) {
                httpResult = PubUtils.assignmentResult(null, 500, "缺失国网变电站信息");
            } else {
                httpResult = PubUtils.assignmentResult(znycdz, 200, "获取国网台账变电站信息成功");
            }
            userLog.getLog("查询国网变电站信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            logger.error("获取国网台账变电站信息异常，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult(null, 500, "获取国网台账变电站信息异常");
            userLog.getLog("查询国网变电站信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return httpResult;
    }

    /**
     * 国网台账获取终端的数据信息
     *
     * @param devIndex 终端索引
     */
    @PostMapping(value = "loadgwDevice")
    @ResponseBody
    public HttpResult loadgwDevice(String devIndex, HttpServletRequest request) {
        HttpResult httpResult;
        Dnzljczz dnzljczz;
        try {
            dnzljczz = lineService.loadgwDevice(devIndex);
            if (null == dnzljczz) {
                httpResult = PubUtils.assignmentResult(null, 500, "缺失国网终端信息");
            } else {
                httpResult = PubUtils.assignmentResult(dnzljczz, 200, "获取国网台账终端信息成功");
            }
            userLog.getLog("查询国网终端信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            logger.error("获取国网台账终端信息异常，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult(null, 500, "获取国网台账终端信息异常");
            userLog.getLog("查询国网终端信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return httpResult;
    }

    /**
     * @Author chendaofei
     * @Description 仅仅获取终端设备（供电公司+变电+设备）
     * @Date 14:07 2020/7/24
     **/
    @RequestMapping(value = "terminalDeviceTree", method = RequestMethod.POST)
    @ResponseBody
    public List<Tree> getTerminalDeviceTree(HttpServletRequest request, HttpSession session) {
        if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
            session.removeAttribute("line_index");
        }

        List<Tree> result = new ArrayList();
        try {
            result = getDeviceInfo.getTerminalDeviceTree();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取终端树异常，异常是" + e.toString());
        }
        return result;
    }

    /***
     * 终端状态更新列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getLogsDetail")
    public String getTerminalLogsDetail(HttpServletRequest request, String terminalType, String startTime, String endTime)
            throws
            JsonProcessingException, AccountException {
        List<List> deviceLogDetail = new ArrayList<List>();
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getTerminalLogsDetail");
        //获取当前系统
        try {
            deviceLogDetail = getDeviceInfo.getTerminalLogsDetail(terminalType, datePojo.getStartTime(), datePojo.getEndTime());
            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 2022/6/17
     */
    @RequestMapping(value = "getDevRunFlagLogs", method = RequestMethod.GET)
    @ResponseBody
    public HttpResult getDevRunFlagLogs(@RequestParam("devId") String devId, @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) {
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getDevRunFlagLogs");
        if (!datePojo.getValidity()) {
            return PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
        }
        List<TerminalLogs> logsList = getDeviceInfo.getLogByDevId(devId, datePojo.getStartTime(), datePojo.getEndTime());
        return PubUtils.assignmentResult(logsList, 200, "获取终端运行日志成功");
    }

    /**
     * 暂降事件推送日志
     */
    @RequestMapping(value = "getEventPushLogsDetail", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getEventPushLogsDetail(HttpServletRequest request, int resultStatus, String startTime, String endTime) throws JsonProcessingException {
        HttpResult result = new HttpResult();
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getUserLogId");
        try {
            if (!datePojo.getValidity()) {
                result = PubUtils.assignmentResult(null, 500, "校验前台传递时间参数报错");
                return result;
            }
            List<EventPushLogsDetail> eventPushLogsDetails = getDeviceInfo.getEventPushDetail(datePojo.getStartTime(), datePojo.getEndTime(), resultStatus);
            if (eventPushLogsDetails.isEmpty()) {
                result.setCode(500);
                result.setMessage("没有获取到暂降消息推送信息列表");
            } else {
                result.setCode(200);
                result.setBody(eventPushLogsDetails);
                result.setMessage("获取暂降消息推送信息列表成功");
            }
        } catch (Exception e) {
            logger.error("查询暂降消息推送信息列表异常，异常是" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "查询暂降消息推送信息列表失败");
        }
        return result;
    }

    /**
     * 暂降事件人工推送
     */
    @RequestMapping(value = "sendUserEventMsg", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData sendUserEventMsg(HttpServletRequest request, Integer lineId, String eventDetailIndex) throws JsonProcessingException {
        ResponseData result = new ResponseData();
        try {
            String urls = request.getRequestURL().toString();
            String localAddr = request.getLocalAddr();
            int serverPort = request.getServerPort();
            URL url = new URL(urls);
            URI uri = url.toURI();
            RestTemplate template = new RestTemplate();
            String url1 = StrUtil.format("{}://{}:{}/shiningCloud/msg/sendEventMsg?eventDetailIndex={}&lineId={}", uri.getScheme(), localAddr, serverPort, eventDetailIndex, lineId);

            ResponseData responseEntity = template.postForObject(url1, null, ResponseData.class);
            if (responseEntity.getResultCode() == 10000) {
                getDeviceInfo.updatEventPushLog(eventDetailIndex, lineId);
                result = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.EVENT_MSG_SUCCESS.getCode(), UserCodeEnum.EVENT_MSG_SUCCESS.getMsg(), null);
            } else {
                result = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(responseEntity.getMsg()), responseEntity.getMsg(), null);
            }

        } catch (Exception e) {
            logger.error("暂降消息推送异常，异常是" + e.toString());
            result = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * create by: xu yang
     * description: 获取装置的文件目录
     * create time: 2021/8/16 13:08
     */
    @PostMapping(value = "getFileContent")
    @ResponseBody
    public HttpResult getFileContent(Integer lineIndex, String path, HttpServletRequest request) {
        HttpResult httpResult;
        FtpDTO pojo;
        try {
            pojo = terminalDirectoryService.getFileDirectory(lineIndex, path);
            if (CollectionUtil.isEmpty(pojo.getList())) {
                httpResult = PubUtils.assignmentResult(null, 404, "缺失装置目录信息");
            } else {
                httpResult = PubUtils.assignmentResult(pojo, 200, "获取装置目录信息，成功");
            }
            userLog.getLog("获取装置目录信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            logger.error("获取装置目录信息异常，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult(null, 500, "获取装置目录信息异常");
            userLog.getLog("获取装置目录信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return httpResult;
    }


    /**
     * create by: xu yang
     * description: 装置文件下载
     * create time: 2021/8/19 11:41
     */
    @PostMapping(value = "downloadFile")
    @ResponseBody
    public HttpResult downloadFile(Integer lineIndex, String path, HttpServletRequest request, HttpServletResponse response) {
        HttpResult httpResult;
        try {
            terminalDirectoryService.getFile(lineIndex, path, response, request);
            httpResult = PubUtils.assignmentResult("success", 200, "下载装置文件，成功");
            userLog.getLog("下载装置文件", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            logger.error("下载装置文件异常，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult("error", 500, "下载装置文件异常");
            userLog.getLog("下载装置文件", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return httpResult;
    }

    /**
     * create by: xu yang
     * description: 获取session
     * create time: 2021/11/23 20:03
     */
    @PostMapping(value = "getSession")
    @ResponseBody
    public HttpResult getSession(HttpServletRequest request, HttpServletResponse response) {
        HttpResult httpResult;
        String result = (String) request.getSession().getAttribute("path");
        httpResult = PubUtils.assignmentResult(result, 200, "获取session，成功");
        return httpResult;
    }


    /**
     * create by: xu yang
     * description: 清除Session
     * create time: 2021/11/23 20:59
     */
    @PostMapping(value = "deleteSession")
    @ResponseBody
    public HttpResult deleteSession(HttpServletRequest request, HttpServletResponse response) {
        HttpResult httpResult;
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("path", null);
        httpResult = PubUtils.assignmentResult("success", 200, "清空session，成功");
        return httpResult;
    }


    /**
     * create by: xu yang
     * description: 获取指定服务器的文件目录
     * create time: 2021/8/24 11:01
     */
    @PostMapping(value = "serverContent")
    @ResponseBody
    public HttpResult serverContent(HttpServletRequest request) {
        HttpResult httpResult;
        List<TerminalDirectory> list;
        try {
            list = terminalDirectoryService.getServerContent();
            if (CollectionUtil.isEmpty(list)) {
                httpResult = PubUtils.assignmentResult(null, 404, "缺失服务器目录");
            } else {
                httpResult = PubUtils.assignmentResult(list, 200, "获取服务器目录，成功");
            }
            userLog.getLog("获取服务器目录", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            logger.error("获取服务器目录异常，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult(null, 500, "获取服务器目录异常");
            userLog.getLog("获取服务器目录", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return httpResult;
    }


    /**
     * create by: xu yang
     * description: 上传文件到服务器
     * create time: 2021/8/24 15:24
     */
    @PostMapping(value = "uploadFileToServer")
    @ResponseBody
    public HttpResult uploadFileToServer(@RequestParam("excelFile") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        HttpResult httpResult;
        try {
            //文件大小(此大小为kb)
            Long fileSize = file.getSize() / 1024;
            //判断文件大小
            if (fileSize > 3072) {
                httpResult = PubUtils.assignmentResult(null, 400, "文件过大");
                return httpResult;
            }
            boolean result = terminalDirectoryService.uploadFileToServer(file, request, response);
            if (result) {
                httpResult = PubUtils.assignmentResult("success", 200, "上传文件成功");
            } else {
                httpResult = PubUtils.assignmentResult("fail", 500, "上传文件失败");
            }
            userLog.getLog("上传文件", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            logger.error("上传文件异常，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult(null, 500, "上传文件异常");
            userLog.getLog("上传文件", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return httpResult;
    }

    @RequestMapping(value = "getStatus", method = RequestMethod.POST)
    @ResponseBody
    public List<DicData> getStatus() {
        List<DicData> dicData = new ArrayList<>();
        try {
            dicData = dicDataMapper.selectWring(DicDataTypeEnum.terminalEnum.getName());
        } catch (Exception e) {
            dicData = null;
            logger.error("查询运维状态日志异常，异常为" + e.toString());
        }
        return dicData;
    }


    /**
     * 台账监测点新增一次接线图
     *
     * @author cdf
     * @date 2023/5/30
     */

    @PostMapping(value = "uploadWiringDiagram")
    @ResponseBody
    public HttpResult uploadWiringDiagram(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "lineId") Integer lineId) {
        HttpResult httpResult;
        try {
            //文件大小(此大小为kb)
            Long fileSize = file.getSize() / 1024;
            //判断文件大小
            if (fileSize > 30072) {
                httpResult = PubUtils.assignmentResult(null, 500, "文件过大");
                return httpResult;
            }
            boolean result = terminalDirectoryService.uploadWiringDiagram(file, request, response, lineId);
            if (result) {
                httpResult = PubUtils.assignmentResult("success", 200, "上传文件成功");
            } else {
                httpResult = PubUtils.assignmentResult("fail", 500, "上传文件失败");
            }
            userLog.getLog("上传文件", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        } catch (Exception e) {
            logger.error("上传文件异常，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult(null, 500, "上传文件异常");
            userLog.getLog("上传文件", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return httpResult;
    }


    /**
     * 通过监测点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;
    }


    /**
     * 通过监测点id获取主接线图
     *
     * @author cdf
     * @date 2023/5/30
     */
    @GetMapping(value = "reCalOverLimit")
    @ResponseBody
    public HttpResult reCalOverLimit() {
        HttpResult httpResult;
        try {
            Integer result = manaDeviceService.reCalOverLimit();
            httpResult = PubUtils.assignmentResult(result, 200, "重新计算限值成功");
        } catch (Exception e) {
            logger.error("重新计算限值出错，异常为" + e.toString());
            httpResult = PubUtils.assignmentResult(null, 500, "重新计算限值出错");
        }
        return httpResult;
    }
}
