/**
 * <p>Copyright:Copyright(c) 2016</p>
 * <p>Company:上海中信信息发展股份有限公司</p>
 * <p>类更新历史信息</p>
 * @author 张二伟
 * @date 2017-03-19 14:58
 * @todo
 */

package com.cesgroup.cesmonitor.service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cesgroup.cesmonitor.bean.Alert;
import com.cesgroup.cesmonitor.bean.DiskUsageInfo;
import com.cesgroup.cesmonitor.bean.EventInfo;
import com.cesgroup.cesmonitor.bean.FaultWarningDto;
import com.cesgroup.cesmonitor.bean.InterfaceInfo;
import com.cesgroup.cesmonitor.bean.OneHostBaseInfo;
import com.cesgroup.cesmonitor.bean.OneHostConfig;
import com.cesgroup.cesmonitor.bean.OneHostDetailInfo;
import com.cesgroup.cesmonitor.bean.OneHostUsedRateInfo;
import com.cesgroup.cesmonitor.bean.ResourceAlarmInfo;
import com.cesgroup.cesmonitor.bean.TopologicalInfo;
import com.cesgroup.cesmonitor.bean.WebMonitorStatus;
import com.cesgroup.cesmonitor.common.Constant;
import com.cesgroup.cesmonitor.common.JSON;
import com.cesgroup.cesmonitor.common.Util;
import com.cesgroup.cesmonitor.dao.FormViewMapper;
import com.cesgroup.cesmonitor.dao.MonitorConfigMapper;
import com.cesgroup.cesmonitor.service.screen.ScreenService;
import com.zabbix4j.ZabbixApi;
import com.zabbix4j.ZabbixApiException;
import com.zabbix4j.ZabbixApiParamter;
import com.zabbix4j.host.HostObject;
import com.zabbix4j.hostgroup.HostgroupGetRequest;
import com.zabbix4j.hostgroup.HostgroupGetResponse;
import com.zabbix4j.map.MapGetRequest;
import com.zabbix4j.map.MapGetResponse;
import com.zabbix4j.trigger.TriggerGetRequest;
import com.zabbix4j.trigger.TriggerGetResponse;
import com.zabbix4j.trigger.TriggerGetResponse.Result;

/**
 * 监控概览service
 *
 * @author
 * @date 2016-07-11
 *
 */
@Service("overviewService")
public class OverviewService {

    @Autowired
    MonitorConfigMapper monitorConfigMapper;

    @Autowired
    FormViewMapper formViewMapper;

    @Autowired
    ScreenService screenService;

    //菜单打开
    @Value("${menu.Open}")
    private int Open;

    public int getOpen() {
        //Util.setMyOpen(Open);
        return Open;
    }

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     *
     * @return 返回主机组
     */
    @RequestMapping(value = "listHostGroupsWithHosts")
    public List<HostgroupGetResponse.Result> listHostGroupsWithHosts() {
        try {
            final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
            final HostgroupGetRequest request = new HostgroupGetRequest();
            final HostgroupGetRequest.Params params = request.getParams();
            params.setSelectHosts(ZabbixApiParamter.QUERY.extend.name());
            params.setWith_hosts_and_templates(true);
            final HostgroupGetResponse response = zabbixApi.hostgroup().get(request);
            final List<com.zabbix4j.hostgroup.HostgroupGetResponse.Result> newlist = new ArrayList<>();
            for (final com.zabbix4j.hostgroup.HostgroupGetResponse.Result rs : response.getResult()) {
                if (null != rs.getHosts()) {
                    newlist.add(rs);
                }
            }
            for (final com.zabbix4j.hostgroup.HostgroupGetResponse.Result result : newlist) {
                for (final HostObject obj : result.getHosts()) {
                    obj.setState(formViewMapper.findHostStatus(obj.getHostid()));

                    final List<ResourceAlarmInfo> listResourceAlarmInfo = monitorConfigMapper
                        .findResouceAlamInfoByHostId(obj.getHostid().longValue());

                    int priority = 0;
                    for (int i = 0; i < listResourceAlarmInfo.size(); i++) {
                        final int myPriority = Integer.parseInt(listResourceAlarmInfo.get(i).getPriority());
                        if (myPriority > priority) {
                            priority = myPriority;
                        }
                    }

                    obj.setHighestAlarm(priority);

                }
            }
            return newlist;
        } catch (final ZabbixApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据主机ID获取当前主机的详细信息
     *
     * @param hostId
     *            主机的hostId
     *
     * @return 返回主机的详细信息（主机状态 :{status}、IP地址 :{ip}、操作系统: {os}、主机名称:
     *         {name}、描述:{description}、启动时间:{startTime}、持续时间:{duration}）
     */
    public OneHostDetailInfo oneHostDetailInfo(final Long hostId) {
        OneHostDetailInfo oneHostDetailInfo = new OneHostDetailInfo();
        try {
            oneHostDetailInfo = monitorConfigMapper.findPartDetailMsgByHostId(hostId);
            if (oneHostDetailInfo != null) {
                //获取IP地址
                final List<String> ipList = monitorConfigMapper.findIpByHostId(hostId);
                oneHostDetailInfo.setIp("");
                for (final String tempIp : ipList) {
                    if (!tempIp.equals("127.0.0.1")) {
                        oneHostDetailInfo.setIp(tempIp);
                        break;
                    }

                }

                String os = monitorConfigMapper.findOsforHostByHostId(Constant.ITEMS_OS, hostId,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA);
                if (os == null) {
                    os = "";
                }
                final Integer startIndex = os.lastIndexOf(Constant.WINDOW_OS_NAME);
                final Integer endIndex = os.length();
                if (startIndex > 0 && startIndex < endIndex) {
                    os = os.substring(startIndex, endIndex);
                }
                oneHostDetailInfo.setOs(os);
                /* String startTime = monitorConfigMapper.findStartTimeByHostId(Constant.ITEMS_SYSTEM_STARTTIME,
                 * hostId,new Date().getTime() / 1000 - Constant.LATEST_DATA);*/
                String startTime = "";

                String upTime = monitorConfigMapper.findUpTimeByHostId(Constant.ITEMS_SYSTEM_UPTIME, hostId,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA);
                Long tempStartTime = 0L;
                //启动时间=当前时间-持续时间；
                if (upTime != null) {
                    tempStartTime = new Date().getTime() / 1000 - Long.parseLong(upTime);
                }
                startTime = tempStartTime.toString();
                if (upTime != null) {
                    upTime = Util.getDiff(Long.parseLong(upTime));
                } else {
                    upTime = "";
                }
                oneHostDetailInfo.setDuration(upTime);
                oneHostDetailInfo.setStartTime(startTime);
            }

        } catch (final Exception e) {
            logger.debug("查询主机详细信息发生异常" + e.getMessage());
            e.printStackTrace();
        }

        return oneHostDetailInfo;
    }

    /**
     * 根据主机ID获取当前主机的CPU使用率和内存使用率
     *
     * @param hostId
     *            主机的hostId
     *
     * @return 反馈主机使用率信息（CPU使用率:{cpuRate} 、内存使用率:{memoryRate}）
     */
    public OneHostUsedRateInfo oneHostUsedRateInfo(final Long hostId) {
        //Util.setMyOpen(Open);
        //int a = Util.getMenuOpenProperties();
        final OneHostUsedRateInfo oneHostUsedRateInfo = new OneHostUsedRateInfo();
        try {
            //查找CPU使用率
            OneHostUsedRateInfo cpuUsedRateInfo = new OneHostUsedRateInfo();
            cpuUsedRateInfo = monitorConfigMapper.findCpuRateByHostId(Constant.CPU_USE_PERCENT, hostId,
                new Date().getTime() / 1000 - Constant.LATEST_DATA);
            if (cpuUsedRateInfo != null) { //使用agent监控获取CPU使用率和内存使用率
                Double usedCpuRate = cpuUsedRateInfo.getCpuRate();
                final String cpuRateItemId = cpuUsedRateInfo.getCpuRateItemId();
                List<String> cpuGraphIds = new ArrayList<String>();
                if (cpuRateItemId != null) {
                    cpuGraphIds = monitorConfigMapper.findcpuGraphIdByItemId(cpuRateItemId);
                    if (cpuGraphIds != null) {
                        for (final String temp : cpuGraphIds) {
                            oneHostUsedRateInfo.setCpuRateGraphId(temp);
                            break;
                        }
                    } else {
                        oneHostUsedRateInfo.setCpuRateGraphId("");
                    }
                }
                if (usedCpuRate != null) {
                    usedCpuRate = Util.round(usedCpuRate, 2);
                }
                oneHostUsedRateInfo.setCpuRate(usedCpuRate);

            } else { //windows服务器 snmp监控获取CPU使用率、内存使用率
                //snmp监控下的CPU使用率
                Double usedCpuRate = monitorConfigMapper.findAvgCpuRateByHostId(Constant.CPU_USE_PERCENT_FLAG, hostId,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA);
                if (usedCpuRate != null) {
                    usedCpuRate = Util.round(usedCpuRate, 2);

                    final List<OneHostConfig> listAvailable = formViewMapper.findAvailableByHostId(hostId);
                    if (listAvailable.get(0).getSnmpAvailable() == 1) {
                        oneHostUsedRateInfo.setCpuRate(usedCpuRate);
                        final String cpuRateGraphId = monitorConfigMapper.findsnmpCpuGraphIdByHostId(
                            Constant.CPU_USE_PERCENT_FLAG, hostId);
                        if (cpuRateGraphId != null) {
                            oneHostUsedRateInfo.setCpuRateGraphId(cpuRateGraphId);
                        }
                    }
                }
            }
            //内存使用率
            OneHostUsedRateInfo tempInfo = new OneHostUsedRateInfo();
            tempInfo = monitorConfigMapper.findMemoryRateByHostId(Constant.USE_MEMORY_RATE, hostId,
                new Date().getTime() / 1000 - Constant.LATEST_DATA);
            if (tempInfo != null) {
                final String memoryRateItemId = tempInfo.getMemoryRateItemId();
                List<String> memoryGraphIds = new ArrayList<String>();
                if (memoryRateItemId != null) {
                    memoryGraphIds = monitorConfigMapper.findMemoryGraphIdByItemId(memoryRateItemId);
                    if (memoryGraphIds != null) {
                        for (final String temp : memoryGraphIds) {
                            oneHostUsedRateInfo.setMemoryRateGraphId(temp);
                            break;
                        }
                    } else {
                        oneHostUsedRateInfo.setMemoryRateGraphId("");
                    }
                }
                Double memoryRate = tempInfo.getMemoryRate();//内存使用率
                if (memoryRate != null) {
                    memoryRate = Util.round(memoryRate, 2);
                }
                oneHostUsedRateInfo.setMemoryRate(memoryRate);
            } else {
                //windows服务器snmp监控下的内存使用率
                final List<DiskUsageInfo> freeRateInfo = monitorConfigMapper.findFreeRateByHostId(
                    Constant.DISK_UNUSE_PERCENT,
                    hostId, new Date().getTime() / 1000 - Constant.LATEST_DATA);
                final Integer length = freeRateInfo.size();
                for (Integer i = 0; i < length; i++) {
                    final String driveLetter = freeRateInfo.get(i).getDriveLetter();// 处理磁盘符
                    if (null != driveLetter && driveLetter.contains("Physical Memory")) {
                        final double total = 100;
                        final Double memoryRate = total - Util.round(freeRateInfo.get(i).getFreeRate(), 2);

                        final List<OneHostConfig> listAvailable = formViewMapper.findAvailableByHostId(hostId);
                        if (listAvailable.get(0).getSnmpAvailable() == 1) {
                            oneHostUsedRateInfo.setMemoryRate(memoryRate);
                        }

                    }
                }
                final String memoryRateGraphId = monitorConfigMapper.findPhysicalMemoryGraphIdByHostId(
                    Constant.USE_PHYSICAL_MEMORY_RATE, hostId);
                if (memoryRateGraphId != null) {
                    oneHostUsedRateInfo.setMemoryRateGraphId(memoryRateGraphId);
                }
            }

        } catch (final Exception e) {
            logger.debug("查询主机使用率（CPU使用率、内存使用率）信息发生异常" + e.getMessage());
            e.printStackTrace();
        }
        return oneHostUsedRateInfo;
    }

    /**
     *
     * @param hostId
     *            主机的hostId
     *
     * @return 返回主机的基本信息（响应时间:{responseTime}、丢包率:{packetLossRate}）
     */
    public OneHostBaseInfo oneHostBaseInfo(final Long hostId) {
        final OneHostBaseInfo oneHostBaseInfo = new OneHostBaseInfo();
        try {
            final List<Double> allResponseTime = monitorConfigMapper.findResponseTimeByHostId(Constant.ICMP_RESPONSE,
                hostId,
                new Date().getTime() / 1000 - Constant.DATE_TIME);
            Double avgResponseTime = 0.0;
            Double totalResponseTime = 0.0;
            Integer count = 0;
            for (final Double tempTime : allResponseTime) {
                if (tempTime != 0) {
                    totalResponseTime += tempTime;
                    count++;
                }
            }
            if (count != 0) {
                avgResponseTime = Util.round(totalResponseTime * 1000 / count, 2);
            }

            oneHostBaseInfo.setResponseTime(avgResponseTime);
            //获取丢包率数据
            Double packetLossRate = monitorConfigMapper.findPacketLossByHostId(Constant.ICMP_LOSS, hostId,
                new Date().getTime() / 1000 - Constant.LATEST_DATA);
            if (packetLossRate == null) {
                packetLossRate = 0.0;
            }
            oneHostBaseInfo.setPacketLossRate(packetLossRate);
        } catch (final Exception e) {
            logger.debug("查询主机使用率（响应时间、丢包率）信息发生异常" + e.getMessage());
            e.printStackTrace();
        }
        return oneHostBaseInfo;

    }

    /**
     *
     * @param hostId
     *            主机的hostId
     *            添加显示信息
     * @return 返回web监控状态的信息（名称：{name}、监测步骤：{stepNo}、最近检察时间：{recentTime}、状态：{status}）
     */
    public List<WebMonitorStatus> listHostWebMonitorInfo(final Long hostId) {
        List<WebMonitorStatus> webMonitorMsg = null;
        try {

            logger.debug("开始web监控状态信息的查询");
            webMonitorMsg = monitorConfigMapper.findWebMonitorStatusByHostId(hostId);
            for (Integer i = 0; i < webMonitorMsg.size(); i++) {
                String recentTime = webMonitorMsg.get(i).getRecentTime();
                if (!recentTime.equals("")) {
                    recentTime = Util.getDate(Long.parseLong(recentTime));
                }
                webMonitorMsg.get(i).setRecentTime(recentTime);

            }

        } catch (final Exception e) {
            logger.debug("web监控状态信息查询失败" + e.getMessage());
            e.printStackTrace();
        }
        //System.err.println("webMonitor" + webMonitorMsg);
        return webMonitorMsg;
    }

    /**
     *
     * @return 返回拓补图信息（拓扑图名字：{sysmapName}、拓扑图ID：{sysmapId}）
     */
    public List<TopologicalInfo> listTopologicalInfo() {
        /*  List<TopologicalInfo> topologicalInfo = null;
        //获取被选中拓扑图的id
        Integer selectedSysmapId = Integer.valueOf(JSON.getStringFromFile(new File("sysmapid.json")));
        try {
            topologicalInfo = monitorConfigMapper.findAllTopologicalInfo();
            for (TopologicalInfo temp : topologicalInfo) {
                String id = temp.getSysmapId();
                if (id.equals(selectedSysmapId.toString())) {
                    temp.setIsSelected("1");
                } else {
                    temp.setIsSelected("0");
                }
            }
        } catch (Exception e) {
            logger.debug("查询拓扑图信息失败" + e.getMessage());
            e.printStackTrace();
        }
        return topologicalInfo;*/

        final List<TopologicalInfo> topologicalInfo = new ArrayList<TopologicalInfo>();
        try {
            final String sysmapid = JSON.getStringFromFile(new File("sysmapid.json"));
            Integer selectedSysmapId = 0;
            if (sysmapid != null && !"".equals(sysmapid)) {
                selectedSysmapId = Integer.valueOf(sysmapid);
            }

            final MapGetRequest request = new MapGetRequest();
            final MapGetRequest.Params params = request.getParams();
            params.setSelectLinks(ZabbixApiParamter.QUERY.extend.name());
            params.setSelectSelements(ZabbixApiParamter.QUERY.extend.name());
            final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
            final MapGetResponse response = zabbixApi.map().get(request);
            final List<com.zabbix4j.map.MapGetResponse.Result> rList = response.getResult();
            boolean flag = false;                           //是否有拓扑图被选中
            for (int i = 0; i < rList.size(); i++) {
                final Integer sysmapId = rList.get(i).getSysmapid();
                final String sysmapName = rList.get(i).getName();
                final TopologicalInfo tempTopological = new TopologicalInfo();
                tempTopological.setSysmapId(sysmapId.toString());
                tempTopological.setSysmapName(sysmapName);

                if (sysmapId.toString().equals(selectedSysmapId.toString())) {
                    tempTopological.setIsSelected("1");
                    flag = true;
                } else {
                    tempTopological.setIsSelected("0");
                }
                topologicalInfo.add(tempTopological);
            }
            if (flag == false && topologicalInfo.size() > 0) {
                //如果没有拓扑图被选中，将第一个拓扑图设置被选中
                topologicalInfo.get(0).setIsSelected("1");
            }
        } catch (final ZabbixApiException e) {
            throw new RuntimeException(e);
        }
        return topologicalInfo;
    }

    /**
     * @param sysmapName
     *            拓扑图名称
     * @return 返回拓扑图信息（拓扑图名字：{sysmapName}、拓扑图ID：{sysmapId}）
     */
    public TopologicalInfo findToplogicalInfoByNameService(final String sysmapName) {
        final TopologicalInfo topologicalInfo = monitorConfigMapper.findToplogicalInfoByName(sysmapName);
        return topologicalInfo;
    }

    /**
     * 用于it拓扑图生成
     *
     * @param serviceId
     *            ITservice id
     * @return 返回拓扑图信息
     */
    public TopologicalInfo findToplogicalInfoByServiceIdService(final Integer serviceId) {
        return monitorConfigMapper.findToplogicalInfoByServiceId(serviceId);
    }

    /**
     *
     * @param hostId
     *            主机的hostId
     * @return 返回资源报警信息(主机：{host}、问题描述：{description}、
     *         上次修改于：{startClock}、历时：{subClock}、 信息：{messages}、
     *         确认：{acknowledged}、 动作 ：{action}、 状态：{status})
     */
    public Map<Integer, ResourceAlarmInfo> listHostResourceAlarmInfo(final Long hostId) {
        final Map<Integer, ResourceAlarmInfo> resourceAlarmMsg = new HashMap<Integer, ResourceAlarmInfo>();
        final TriggerGetRequest request = new TriggerGetRequest();
        final TriggerGetRequest.Params params = request.getParams();
        params.setExpandDescription(true);
        params.setExpandExpression(true);
        TriggerGetResponse response = null;
        final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
        try {
            logger.debug("根据主机hostId查询资源报警信息");
            final List<ResourceAlarmInfo> listResourceAlarmInfo = monitorConfigMapper
                .findResouceAlamInfoByHostId(hostId);
            final Integer[] indexs = new Integer[listResourceAlarmInfo.size()];
            int index = 0;
            for (final ResourceAlarmInfo resourceAlarm : listResourceAlarmInfo) {
                indexs[index] = index;
                final ResourceAlarmInfo resourceAlarmInfo = new ResourceAlarmInfo();

                final Integer objectId = resourceAlarm.getObjectid();
                if (objectId != null) {
                    final List<String> eventids = monitorConfigMapper.findEventidsByObjectid(objectId);
                    if (eventids.size() > 0) {
                        for (final String eventid : eventids) {
                            resourceAlarmInfo.setEventid(eventid);
                            break;
                        }
                    }
                }
                //对eventid判断，防止转换错误
                if (null != resourceAlarmInfo.getEventid() && !"".equals(resourceAlarmInfo.getEventid())) {
                    resourceAlarmInfo.setAlertTime(
                        monitorConfigMapper.countAlertTime(Integer.valueOf(resourceAlarmInfo.getEventid())));
                }
                resourceAlarmInfo.setHost(resourceAlarm.getHost());
                resourceAlarmInfo.setPriority(resourceAlarm.getPriority());
                resourceAlarmInfo.setEndClock(new Date().getTime() / 1000);
                final int acknowledged;
                //查出资源报警的确认状态
                //System.err.println("objectid" + objectId);
                String flag = monitorConfigMapper.findAcknowledgeByObjectId(objectId);
                //System.err.println("flag" + flag);
                if (null != flag) {
                    acknowledged = Integer.valueOf(monitorConfigMapper.findAcknowledgeByObjectId(objectId));
                    resourceAlarmInfo.setAcknowledged(acknowledged);
                    System.err.println("acknow" + acknowledged);
                }

                //根据objectId获取当前资源报警的活动记录
                final List<EventInfo> tempEventsMsg = findEventMsgByObjectId(objectId);
                Collections.sort(tempEventsMsg);
                resourceAlarmInfo.setEventMsg(tempEventsMsg);
                resourceAlarmInfo.setMessages(resourceAlarm.getMessages());
                resourceAlarmInfo.setAction(resourceAlarm.getAction());
                resourceAlarmInfo.setStatus(resourceAlarm.getStatus());

                //System.err.println("resourceAlarm.getObjectid()" + resourceAlarm.getObjectid());

                resourceAlarmInfo.setObjectid(resourceAlarm.getObjectid());
                resourceAlarmMsg.put(indexs[index], resourceAlarmInfo);
                index++;
            }
            for (int i = 0; i < indexs.length; i++) {
                final ResourceAlarmInfo old = resourceAlarmMsg.get(indexs[i]);
                if (old != null) {
                    params.addTriggerid(old.getObjectid());
                    try {
                        response = zabbixApi.trigger().get(request);
                        final List<Result> lr = response.getResult();
                        for (final Result rs : lr) {
                            old.setDescription(rs.getDescription());
                            params.getTriggerids().clear();
                        }
                    } catch (final ZabbixApiException e1) {
                        e1.printStackTrace();
                    }
                    final Long startClock = monitorConfigMapper.findStartClock(old.getObjectid());
                    old.setStartClock(startClock);
                    if (old.getEndClock() > old.getStartClock()) {
                        old.setSubClock(Util.getDiff(old.getEndClock() - old.getStartClock()));
                    } else {
                        old.setSubClock("");
                    }
                }
            }
        } catch (final Exception e) {
            logger.debug("根据主机Hostid查询资源报警信息失败" + e.getMessage());
            e.printStackTrace();
        }
        return resourceAlarmMsg;
    }

    /**
     * 智慧政务接口
     *
     * @param startTime
     *            开始时间
     * @param endTime
     *            结束时间
     * @return
     *         资源报警信息
     */
    public List<FaultWarningDto> listsResourceAlarmInfo(Date startTime, Date endTime) {
        screenService.initUser();
        if (startTime != null) {
            startTime = new Date(startTime.getTime() / 1000);
        }
        if (endTime != null) {
            endTime = new Date(endTime.getTime() / 1000);
        }
        final Map<Integer, FaultWarningDto> resourceAlarmMsg = new HashMap<Integer, FaultWarningDto>();
        final TriggerGetRequest request = new TriggerGetRequest();
        final TriggerGetRequest.Params params = request.getParams();
        params.setExpandDescription(true);
        params.setExpandExpression(true);
        TriggerGetResponse response = null;
        final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
        try {
            if (null != startTime && null != endTime) {
                //把Date类型转换成Long类型
                final List<FaultWarningDto> listResourceAlarmInfo = monitorConfigMapper.listsAlamInfo(
                    startTime.getTime(), endTime.getTime());
                /*  List<FaultWarningDto> listResourceAlarmInfo = monitorConfigMapper.listsAlamInfo(
                 * new Date().getTime()
                 * / 1000- 3600, new Date().getTime() / 1000);*/
                final Integer[] indexs = new Integer[listResourceAlarmInfo.size()];
                int index = 0;
                for (final FaultWarningDto resourceAlarm : listResourceAlarmInfo) {
                    indexs[index] = index;
                    final FaultWarningDto resourceAlarmInfo = new FaultWarningDto();
                    resourceAlarmInfo.setWarningTime(resourceAlarm.getWarningTime());
                    resourceAlarmInfo.setWarningMessage(resourceAlarm.getWarningMessage());
                    resourceAlarmInfo.setWarningLevel(resourceAlarm.getWarningLevel());
                    resourceAlarmInfo.setFaultStatus(resourceAlarm.getFaultStatus());
                    resourceAlarmInfo.setHostName(resourceAlarm.getHostName());
                    resourceAlarmInfo.setTriggerId(resourceAlarm.getTriggerId());
                    resourceAlarmInfo.setObjectid(resourceAlarm.getObjectid());
                    resourceAlarmInfo.setIp("10.250.198.199");
                    resourceAlarmInfo.setSystemType("");
                    final String hostId = resourceAlarm.getHostId();
                    resourceAlarmInfo.setHostIp("127.0.0.1");
                    //获取IP地址
                    final List<String> ipList = monitorConfigMapper.findIpByHostId(Long.parseLong(hostId));
                    for (final String tempIp : ipList) {
                        if (!tempIp.equals("127.0.0.1")) {
                            resourceAlarmInfo.setHostIp(tempIp);
                            break;
                        }

                    }
                    resourceAlarmMsg.put(indexs[index], resourceAlarmInfo);
                    index++;
                }
                for (int i = 0; i < indexs.length; i++) {
                    final FaultWarningDto old = resourceAlarmMsg.get(indexs[i]);
                    if (old != null) {
                        params.addTriggerid(old.getObjectid());
                        try {
                            response = zabbixApi.trigger().get(request);
                            final List<Result> lr = response.getResult();
                            for (final Result rs : lr) {
                                old.setWarningMessage(rs.getDescription());
                                params.getTriggerids().clear();
                            }
                        } catch (final ZabbixApiException e1) {
                            e1.printStackTrace();
                        }
                        final Long startClock = monitorConfigMapper.findStartClock(old.getObjectid());
                        if (startClock != null) {
                            final java.util.Date date = new Date(startClock * 1000);
                            old.setWarningTime(date);
                        }
                    }
                }
            }
        } catch (final Exception e) {
            logger.debug("查询资源报警信息失败" + e.getMessage());
            e.printStackTrace();
        }
        final List<FaultWarningDto> lists = new ArrayList<FaultWarningDto>(resourceAlarmMsg.values());
        return lists;
    }

    /**
     *
     * @param eventId
     *            事件id
     * @return 资源告警
     */
    public List<Alert> resourceAlertService(final Integer eventId) {
        final List<Alert> alerts = monitorConfigMapper.findResourceAlertByEventId(eventId);
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        for (int i = 0; i < alerts.size(); i++) {
            try {
                date = sdf.parse(alerts.get(i).getTime()); //格式化日期格式
                alerts.get(i).setTime(sdf.format(date));

                if (alerts.get(i).getError().contains("\"")) {
                    final String error = alerts.get(i).getError().replace("\"", "\\'");
                    alerts.get(i).setError(error);
                }
            } catch (final ParseException e) {
                e.printStackTrace();
            }
        }
        return alerts;
    }

    /**
     *
     * @param objectid
     *            触发器的objectid
     * @return 通过触发器id获取当前触发器的信息(事件发生时间:{startClock}、状态：{status}、持续时间：{subClock}、时长：{duration}、是否确认：{acknowledged})
     */
    public List<EventInfo> findEventMsgByObjectId(final Integer objectid) {

        final Map<Integer, EventInfo> tempEventsMsg = new HashMap<Integer, EventInfo>();
        List<EventInfo> eventsMsg = new ArrayList<EventInfo>();
        try {
            eventsMsg = monitorConfigMapper.findEventInfoByObjectid(objectid);
            final Integer[] indexs = new Integer[eventsMsg.size()];
            int index = 0;
            for (final EventInfo info : eventsMsg) {
                indexs[index] = index;
                final EventInfo event = new EventInfo();
                event.setStartClock(info.getStartClock());
                event.setStatus(info.getStatus());
                event.setAcknowledged(info.getAcknowledged());
                tempEventsMsg.put(indexs[index], event);
                index++;
            }
            Long tempEndTime = new Date().getTime() / 1000;
            Long tempDuration = 0L;
            for (int i = 0; i < indexs.length; i++) {
                final EventInfo old = tempEventsMsg.get(indexs[i]);
                old.setSubClock(Util.getDiff(tempEndTime - old.getStartClock()));
                old.setDuration(Util.getDiff(tempEndTime - old.getStartClock() + tempDuration));
                tempDuration = tempEndTime - old.getStartClock() + tempDuration;
                tempEndTime = old.getStartClock();
            }
        } catch (final Exception e) {
            logger.debug("根据主机Hostid查询资源报警信息失败" + e.getMessage());
            e.printStackTrace();
        }

        final List<EventInfo> list = new ArrayList<>(tempEventsMsg.values());
        //        Collections.sort(list);
        return list;
    }

    /**
     *
     * @param hostId
     *            主机的hostId
     * @return 返回主机的磁盘使用信息（盘符：{driveLetter}、总容量：{totalCapacity}、使用量：{usedCapacity}、空闲率：{freeRate}）
     */
    public Map<Integer, DiskUsageInfo> listHostsDiskUsageInfo(final Long hostId) {
        final Map<Integer, DiskUsageInfo> diskUsageInfo = new HashMap<Integer, DiskUsageInfo>();
        try {
            final List<DiskUsageInfo> freeRateInfo = monitorConfigMapper.findFreeRateByHostId(
                Constant.DISK_UNUSE_PERCENT,
                hostId, new Date().getTime() / 1000 - Constant.LATEST_DATA);
            final List<DiskUsageInfo> totalCapacityInfo = monitorConfigMapper.findTotalCapacityByHostId(
                Constant.DICK_TOTAL_CAPACITY, hostId, new Date().getTime() / 1000 - Constant.LATEST_DATA - 60000);
            final List<DiskUsageInfo> usedCapacityInfo = monitorConfigMapper.findUsedCapacityByHostId(
                Constant.DISK_USED_CAPACITY, hostId, new Date().getTime() / 1000 - Constant.LATEST_DATA);
            final Integer length = totalCapacityInfo.size();
            for (Integer i = 0; i < length; i++) {
                final DiskUsageInfo tempDiskUsageInfo = new DiskUsageInfo();
                diskUsageInfo.put(i, tempDiskUsageInfo);
            }

            if (usedCapacityInfo != null) {
                for (Integer i = 0; i < length; i++) {
                    final Double totalCapacity = totalCapacityInfo.get(i).getTotalCapacity();
                    if (totalCapacity > 0) {
                        String driveLetter = null;
                        if (i < usedCapacityInfo.size()) {
                            driveLetter = usedCapacityInfo.get(i).getDriveLetter();// 处理磁盘符
                        }
                        if (null != driveLetter) {

                            if (driveLetter.contains("\\")) {
                                final int startIndex = driveLetter.indexOf("[");
                                final int endIndex = driveLetter.indexOf("\\");
                                if (endIndex > startIndex) {
                                    driveLetter = driveLetter.substring(startIndex + 1, endIndex);
                                }

                                Double usedCapacity = 0.0;
                                String usageItemid = "";
                                if (usedCapacityInfo != null) {
                                    usedCapacity = usedCapacityInfo.get(i).getUsedCapacity();
                                    usageItemid = usedCapacityInfo.get(i).getUsageItemid();
                                }
                                final DiskUsageInfo tmpDiskUsageInfo = diskUsageInfo.get(i);
                                final String totalItemid = totalCapacityInfo.get(i).getTotalItemid();
                                if (!"".equals(totalItemid) && totalItemid != null) {
                                    List<String> graphIds = new ArrayList<String>();
                                    graphIds = monitorConfigMapper.findGraphidByItemids(totalItemid, usageItemid);
                                    if (graphIds != null) {
                                        for (final String temp : graphIds) {
                                            tmpDiskUsageInfo.setGraphId(temp);
                                            break;
                                        }
                                    } else {

                                        tmpDiskUsageInfo.setGraphId("");
                                    }
                                }
                                if (freeRateInfo != null) {
                                    final Double freeRate = freeRateInfo.get(i).getFreeRate();
                                    tmpDiskUsageInfo.setUsedRate(Util.round(100 - freeRate, 2));// 使用率
                                }
                                final Double freeCapacity = totalCapacity - usedCapacity;
                                tmpDiskUsageInfo.setTotalItemid(totalItemid);
                                tmpDiskUsageInfo.setUsageItemid(usageItemid);
                                tmpDiskUsageInfo.setDriveLetter(driveLetter);// 盘符
                                tmpDiskUsageInfo.setTotalCapacity(Util.getCapacityConversion(totalCapacity));// 总容量
                                tmpDiskUsageInfo.setUsedCapacity(Util.getCapacityConversion(usedCapacity));// 使用量
                                tmpDiskUsageInfo.setFreeCapacity(Util.getCapacityConversion(freeCapacity));// 空闲量

                            } else if (driveLetter.contains("Physical Memory")) {
                                continue;
                            } else if (driveLetter.contains("Virtual Memory")) {
                                continue;
                            } else {
                                final int startIndex = driveLetter.indexOf("[");
                                final int endIndex = driveLetter.indexOf(",");
                                final int snmpLinuxIndex = driveLetter.indexOf("]");//snmp监控模式下 盘符的处理情况[/xx]
                                if (endIndex > startIndex) {
                                    driveLetter = driveLetter.substring(startIndex + 1, endIndex);
                                } else if (endIndex == -1 && snmpLinuxIndex > startIndex) {
                                    driveLetter = driveLetter.substring(startIndex + 1, snmpLinuxIndex);
                                }
                                Double usedCapacity = 0.0;
                                String usageItemid = "";
                                if (usedCapacityInfo != null) {
                                    usedCapacity = usedCapacityInfo.get(i).getUsedCapacity();
                                    usageItemid = usedCapacityInfo.get(i).getUsageItemid();
                                }
                                final DiskUsageInfo tmpDiskUsageInfo = diskUsageInfo.get(i);
                                final String totalItemid = totalCapacityInfo.get(i).getTotalItemid();
                                if (!"".equals(totalItemid) && totalItemid != null) {
                                    List<String> graphIds = new ArrayList<String>();
                                    graphIds = monitorConfigMapper.findGraphidByItemids(totalItemid, usageItemid);
                                    if (graphIds != null) {
                                        for (final String temp : graphIds) {
                                            tmpDiskUsageInfo.setGraphId(temp);
                                            break;
                                        }
                                    } else {

                                        tmpDiskUsageInfo.setGraphId("");
                                    }
                                }
                                if (freeRateInfo != null) {
                                    final Double freeRate = freeRateInfo.get(i).getFreeRate();
                                    if (freeRate == 100.0) {
                                        tmpDiskUsageInfo.setUsedRate(0.0);// 使用率
                                    } else if (usedCapacityInfo.get(i).getUsedCapacity() == 0.0) {
                                        tmpDiskUsageInfo.setUsedRate(0.0);// 使用率
                                    } else {
                                        tmpDiskUsageInfo.setUsedRate(Util.round(100 - freeRate, 2));// 使用率
                                    }

                                }
                                final Double freeCapacity = totalCapacity - usedCapacity;
                                tmpDiskUsageInfo.setTotalItemid(totalItemid);
                                tmpDiskUsageInfo.setUsageItemid(usageItemid);
                                tmpDiskUsageInfo.setDriveLetter(driveLetter);// 盘符
                                tmpDiskUsageInfo.setTotalCapacity(Util.getCapacityConversion(totalCapacity));// 总容量
                                tmpDiskUsageInfo.setUsedCapacity(Util.getCapacityConversion(usedCapacity));// 使用量
                                tmpDiskUsageInfo.setFreeCapacity(Util.getCapacityConversion(freeCapacity));// 空闲量

                            }

                        }
                    }
                }
            }

        } catch (final Exception e) {
            logger.debug("根据主机Hostid查询磁盘使用量信息" + e.getMessage());
            e.printStackTrace();
        }
        return diskUsageInfo;
    }

    /**
     *
     * @param totalItemid
     *            总容量监控项itemid
     * @param usageItemid
     *            使用量监控项itemid
     * @return 返回graphIds
     */
    public List<String> getGraphidByItemids(final String totalItemid, final String usageItemid) {
        List<String> graphIds = new ArrayList<String>();
        try {
            graphIds = monitorConfigMapper.findGraphidByItemids(totalItemid, usageItemid);
        } catch (final Exception e) {
            logger.debug("根据磁盘总使用量itemid和使用量itemid查询磁盘图形graphid信息" + e.getMessage());
            e.printStackTrace();
        }

        return graphIds;
    }

    /**
     *
     * @param hostId
     *            主机的hostId
     * @return 返回接口信息(状态:{status}、名称:{interfaceName}、进口流程：{inputFlow}、出口流程：{outputFlow}、状态变更时间：{statusChangedTime})
     */
    public Map<Integer, InterfaceInfo> listHostInterfaceInfo(final Long hostId) {

        final Map<Integer, InterfaceInfo> interfaceInfo = new HashMap<Integer, InterfaceInfo>();

        final List<InterfaceInfo> inputFlowMsg = monitorConfigMapper.findInputFlowInfoByHostId(
            Constant.INTERFACE_INPUT_FLOW,
            hostId, new Date().getTime() / 1000 - Constant.LATEST_DATA);

        final List<InterfaceInfo> outputFlowMsg = monitorConfigMapper.findOutputFlowInfoByHostId(
            Constant.INTERFACE_OUTPUT_FLOW, hostId, new Date().getTime() / 1000 - Constant.LATEST_DATA);
        final Integer length = inputFlowMsg.size();

        for (Integer i = 0; i < length; i++) {
            final InterfaceInfo interfaceMsg = new InterfaceInfo();
            interfaceInfo.put(i, interfaceMsg);
        }

        for (Integer i = 0; i < length; i++) {
            String interfaceName = inputFlowMsg.get(i).getInterfaceName();// 接口名称
            final Integer startIndex = interfaceName.indexOf("[");
            final Integer endIndex = interfaceName.lastIndexOf("]");
            if (startIndex < endIndex) {
                interfaceName = interfaceName.substring(startIndex + 1, endIndex);
            }
            String statusChangedTime = inputFlowMsg.get(i).getStatusChangedTime();
            final InterfaceInfo tempInterfaceMsg = interfaceInfo.get(i);
            if (!statusChangedTime.equals("")) {
                statusChangedTime = Util.getDate(Long.parseLong(statusChangedTime));
            }
            final String status = inputFlowMsg.get(i).getStatus();
            final String inputItemid = inputFlowMsg.get(i).getInputItemid();//进口流量监控项inputItemid
            final String outputItemid = outputFlowMsg.get(i).getOutputItemid();//出口流量监控项outputItemid
            if (inputItemid != null && outputItemid != null) {
                List<String> graphIds = new ArrayList<String>();
                graphIds = monitorConfigMapper.findGraphidByItemids(inputItemid, outputItemid);
                if (graphIds != null) {
                    for (final String temp : graphIds) {
                        tempInterfaceMsg.setGraphId(temp);
                        break;
                    }
                } else {

                    tempInterfaceMsg.setGraphId("");
                }
            }
            final Double inputFlow = inputFlowMsg.get(i).getInputFlow();
            final Double outputFlow = outputFlowMsg.get(i).getOutputFlow();
            tempInterfaceMsg.setStatus(status);
            tempInterfaceMsg.setInterfaceName(interfaceName);
            tempInterfaceMsg.setInputFlow(Util.getFlowConversion(inputFlow));
            tempInterfaceMsg.setOutputFlow(Util.getFlowConversion(outputFlow));
            tempInterfaceMsg.setStatusChangedTime(statusChangedTime);
        }

        return interfaceInfo;
    }
}
