/**
 * <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.util.ArrayList;
import java.util.Calendar;
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 com.cesgroup.cesmonitor.bean.Cpu;
import com.cesgroup.cesmonitor.bean.Disk;
import com.cesgroup.cesmonitor.bean.DiskUsageInfo;
import com.cesgroup.cesmonitor.bean.HostByGroup;
import com.cesgroup.cesmonitor.bean.Memory;
import com.cesgroup.cesmonitor.bean.OneHostConfig;
import com.cesgroup.cesmonitor.bean.PriorityCount;
import com.cesgroup.cesmonitor.bean.PriorityDetail;
import com.cesgroup.cesmonitor.bean.ResponseTime;
import com.cesgroup.cesmonitor.bean.Timetemp;
import com.cesgroup.cesmonitor.common.Constant;
import com.cesgroup.cesmonitor.common.EhcacheUtil;
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.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.trigger.TriggerGetRequest;
import com.zabbix4j.trigger.TriggerGetResponse;
import com.zabbix4j.trigger.TriggerGetResponse.Result;

/**
 * 这个类是图表总览的业务层阶段，在这里会调用DAO层的代码
 */
@Service("formViewService")
public class FormViewService {

    @Autowired
    FormViewMapper formViewMapper;

    @Autowired
    MonitorConfigMapper monitorConfigMapper;

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

    public int getOpen() {
        return Open;
    }

    public void setOpen(final int open) {
        Open = open;
    }

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

    /**
     * @return 返回组名及其下属的所有主机（这里只查我们需要展示的几种类型，具体可根据实际需求选择）
     */
    public List<HostgroupGetResponse.Result> listHostGroupsWithHosts() {
        try {
            logger.debug("查询组名及其下属的主机");
            final HostgroupGetRequest request = new HostgroupGetRequest();
            final HostgroupGetRequest.Params params = request.getParams();
            params.setSelectHosts(ZabbixApiParamter.QUERY.extend.name());
            final String[] names = new String[] { "PC机", "三层交换机", "交换机", "路由器", "服务器", "防火墙" };
            for (int i = 0; i < names.length; i++) {
                params.addGroupId(formViewMapper.findGroupIdByName(names[i]));
            }
            if (null == Util.getLoginUser()) {
                logger.debug("Util.getLoginUser()未登录");
            }
            //null
            final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
            final HostgroupGetResponse response = zabbixApi.hostgroup().get(request);
            final List<com.zabbix4j.hostgroup.HostgroupGetResponse.Result> newlist = new ArrayList<>();
            for (final com.zabbix4j.hostgroup.HostgroupGetResponse.Result result : response.getResult()) {
                if (null != result.getHosts()) {
                    for (final HostObject obj : result.getHosts()) {
                        obj.setState(formViewMapper.findHostStatus(obj.getHostid()));
                    }
                }
                newlist.add(result);
            }
            return newlist;
        } catch (final ZabbixApiException e) {
            logger.debug("查询组及其下属主机出错:" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @return 返回这个星期的每天异常数（这里不针对月的概念）
     */
    public Map<Integer, Integer> currentWeekExceptionData() {
        final LoginUser user = Util.getLoginUser();
        final Integer userId = user.getUserid();
        final boolean isSuperAdmin = user.isSuperAdmin();
        final Map<Integer, Integer> currentWeekmap = new HashMap<Integer, Integer>();
        final Calendar c = Calendar.getInstance();
        final int weekday = c.get(Calendar.DAY_OF_WEEK);
        c.setTime(new Date());
        int week = weekday;
        try {
            logger.debug("查询这个星期每天异常数开始");
            for (int i = 0; i < weekday; i++) {
                final Timetemp tt = Util.getTime(c, i);

                int num;
                if (isSuperAdmin) {
                    num = formViewMapper.findExceptionNumByDay(tt.getStartTime(), tt.getEndTime());
                } else {
                    num = formViewMapper.findExceptionNumByDayAndUserId(tt.getStartTime(), tt.getEndTime(), userId);
                }

                currentWeekmap.put(week--, num);
            }
        } catch (final Exception e) {
            logger.debug("查询这个星期每天异常数失败" + e.getMessage());
            e.printStackTrace();
        }
        return currentWeekmap;
    }

    /**
     *
     * @return 返回上个星期的每天异常数（这里不针对月的概念）
     */
    public Map<Integer, Integer> lastWeekExceptionData() {
        final LoginUser user = Util.getLoginUser();
        final Integer userId = user.getUserid();
        final boolean isSuperAdmin = user.isSuperAdmin();
        final Map<Integer, Integer> lastWeekmap = new HashMap<Integer, Integer>();
        final Calendar c = Calendar.getInstance();
        final int weekday = c.get(Calendar.DAY_OF_WEEK);
        c.add(Calendar.DAY_OF_YEAR, -weekday);
        c.setTime(c.getTime());
        int week = 7;
        try {
            logger.debug("查询上个星期每天的异常数开始");
            for (int i = 0; i < 7; i++) {
                final Timetemp tt = Util.getTime(c, i);

                int num;
                if (isSuperAdmin) {
                    num = formViewMapper.findExceptionNumByDay(tt.getStartTime(), tt.getEndTime());
                } else {
                    num = formViewMapper.findExceptionNumByDayAndUserId(tt.getStartTime(), tt.getEndTime(), userId);
                }
                lastWeekmap.put(week--, num);
            }
        } catch (final Exception e) {
            logger.debug("查询上个星期每天的异常数失败" + e.getMessage());
            e.printStackTrace();
        }
        return lastWeekmap;
    }

    /**
     *
     * @return 返回上个月每天异常数
     */
    public Map<Integer, Integer> lastMonthExceptionData() {
        final LoginUser user = Util.getLoginUser();
        final Integer userId = user.getUserid();
        final boolean isSuperAdmin = user.isSuperAdmin();
        final Map<Integer, Integer> lastMonthmap = new HashMap<Integer, Integer>();
        final int days = Util.lastMonthOfDays();
        final int currentdays = Util.currentMonthOfDays();
        int key = days;
        final Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -currentdays);
        calendar.setTime(calendar.getTime());
        try {
            logger.debug("查询上个月每天异常数开始");
            for (int i = 0; i < days; i++) {
                final Timetemp tt = Util.getTime(calendar, i);

                int exceptionNum;
                if (isSuperAdmin) {
                    exceptionNum = formViewMapper.findExceptionNumByDay(tt.getStartTime(), tt.getEndTime());
                } else {
                    exceptionNum = formViewMapper.findExceptionNumByDayAndUserId(tt.getStartTime(), tt.getEndTime(),
                        userId);
                }
                lastMonthmap.put(key--, exceptionNum);
                if (key == 29) {
                    final Calendar calendar2 = Calendar.getInstance();
                    calendar2.set(calendar2.get(Calendar.YEAR), calendar2.get(Calendar.MONTH + 1), 0);
                    final int day = calendar2.get(Calendar.DAY_OF_MONTH);
                    if (day == 31) {
                        lastMonthmap.put(31, null);
                    }

                }
            }
        } catch (final Exception e) {
            logger.debug("查询上个月每天异常数失败" + e.getMessage());
            e.printStackTrace();
        }
        return lastMonthmap;
    }

    /**
     * @return 返回当月每天异常数
     */
    public Map<Integer, Integer> currentMonthExceptionData() {
        final LoginUser user = Util.getLoginUser();
        final Integer userId = user.getUserid();
        final boolean isSuperAdmin = user.isSuperAdmin();
        final Map<Integer, Integer> currentMonthmap = new HashMap<Integer, Integer>();
        final int days = Util.currentMonthOfDays();
        int key = days;
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        try {
            logger.debug("查询当月每天异常数开始");
            for (int i = 0; i < days; i++) {
                final Timetemp tt = Util.getTime(calendar, i);
                int exceptionNum;
                if (isSuperAdmin) {
                    exceptionNum = formViewMapper.findExceptionNumByDay(tt.getStartTime(), tt.getEndTime());
                } else {
                    exceptionNum = formViewMapper.findExceptionNumByDayAndUserId(tt.getStartTime(), tt.getEndTime(),
                        userId);
                }
                currentMonthmap.put(key--, exceptionNum);
            }
        } catch (final Exception e) {
            logger.debug("查询当月每天异常数失败" + e.getMessage());
            e.printStackTrace();
        }
        return currentMonthmap;
    }

    /**
     *
     * @param order
     *            排序（DESC || ASC）
     * @param limit
     *            取几位
     * @return 所有主机响应时间排行
     */
    public List<ResponseTime> allHostsResponseTime(final String order, final Integer limit) {
        final LoginUser user = Util.getLoginUser();
        final Integer userId = user.getUserid();
        final boolean isSuperAdmin = user.isSuperAdmin();
        if (limit <= 0) {
            return null;
        }
        List<ResponseTime> listResponseTime = null;
        try {
            logger.debug("开始响应时间的排行查询");

            if (isSuperAdmin) {
                listResponseTime = formViewMapper.findComputerConfigMessageforResponseTime(Constant.ICMP_RESPONSE,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA, order, limit);
            } else {
                listResponseTime = formViewMapper.findComputerConfigMessageforResponseTimeByUser(Constant.ICMP_RESPONSE,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA, order, limit, userId);
            }
            Collections.sort(listResponseTime);
        } catch (final Exception e) {
            logger.debug("响应时间的排行查询失败" + e.getMessage());
            e.printStackTrace();
        }
        return listResponseTime;
    }

    /**
     *
     * @param order
     *            排序（DESC || ASC）
     * @param limit
     *            取几位
     * @return 所有主机磁盘利用率
     */
    public List<Disk> allHostsDisk(final String order, final Integer limit) {
        final LoginUser user = Util.getLoginUser();
        final Integer userId = user.getUserid();
        final boolean isSuperAdmin = user.isSuperAdmin();
        final List<Disk> listDisk2 = new ArrayList<Disk>();
        final List<Disk> listDisk3 = new ArrayList<Disk>();
        if (limit <= 0) {
            return null;
        }
        List<Disk> listDisk = null;
        try {
            logger.debug("开始磁盘利用率的排行查询");

            if (isSuperAdmin) {
                listDisk = formViewMapper.findComputerConfigMessageforDisk(Constant.DISK_UNUSE_PERCENT,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA, order, 100);
            } else {
                listDisk = formViewMapper.findComputerConfigMessageforDiskByUser(Constant.DISK_UNUSE_PERCENT,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA, order, limit, userId);
            }
            final ArrayList<Integer> removelist = new ArrayList<Integer>();

            for (int i = 0; i < listDisk.size(); i++) {
                final double rate = listDisk.get(i).getDiskRate();
                listDisk.get(i).setDiskRate(Util.round(100 - rate, 2));

                if (listDisk.get(i).getItemName().contains("$")) {
                    final int begin = listDisk.get(i).getItemKey().indexOf("["); //key_类似vfs.fs.size[C:,pfree]
                    final int end = listDisk.get(i).getItemKey().indexOf(",");
                    final String drive = listDisk.get(i).getItemKey().substring(begin + 1, end); //获取盘符,如D:
                    listDisk.get(i).setItemName(drive);
                } else if (listDisk.get(i).getItemKey().contains("\\")) {
                    final int begin = listDisk.get(i).getItemKey().indexOf("[");
                    final int end = listDisk.get(i).getItemKey().indexOf("\\");
                    final String drive = listDisk.get(i).getItemKey().substring(begin + 1, end); //获取盘符,如D:
                    listDisk.get(i).setItemName(drive);
                } else if (listDisk.get(i).getItemKey().contains("Physical Memory")) {
                    removelist.add(i);
                } else if (listDisk.get(i).getItemKey().contains("Virtual Memory")) {
                    removelist.add(i);
                } else if (listDisk.get(i).getItemName().contains("空闲率")) {
                    final int begin = listDisk.get(i).getItemKey().indexOf("[");
                    final int end = listDisk.get(i).getItemKey().indexOf("]");
                    final String drive = listDisk.get(i).getItemKey().substring(begin + 1, end); //获取盘符,如D:
                    listDisk.get(i).setItemName(drive);
                }
            }

            for (int j = 0; j < listDisk.size(); j++) {
                if (!removelist.contains(j)) {
                    listDisk2.add(listDisk.get(j));
                }
            }

            Collections.sort(listDisk2, Collections.reverseOrder());
            //修复数组越界问题
            if (listDisk2.size() > limit) {
                listDisk3.addAll(listDisk2.subList(0, limit));
            } else {
                listDisk3.addAll(listDisk2.subList(0, listDisk2.size()));
            }
            //listDisk3.subList(0, limit);
        } catch (final Exception e) {
            logger.debug("磁盘利用率的排行查询失败" + e.getMessage());
            e.printStackTrace();
        }
        return listDisk3.subList(0, limit);
    }

    /**
     *
     * @param order
     *            排序（DESC || ASC）
     * @param limit
     *            取几位
     * @return 所有主机CPU利用率
     */
    public List<Cpu> allHostsCpu(final String order, final Integer limit) {
        final LoginUser user = Util.getLoginUser();
        final Integer userId = user.getUserid();
        final boolean isSuperAdmin = user.isSuperAdmin();
        if (limit <= 0) {
            return null;
        }
        List<Cpu> listCpu = null;
        try {
            logger.debug("开始CPU利用率的排行查询");
            if (isSuperAdmin) {
                listCpu = formViewMapper.findComputerConfigMessageforCpu(Constant.CPU_USE_PERCENT,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA, order, limit);
            } else {
                listCpu = formViewMapper.findComputerConfigMessageforCpuByUser(Constant.CPU_USE_PERCENT,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA, order, limit, userId);
            }
            for (final Cpu cpu : listCpu) {
                final double rate = cpu.getCpuRate();
                cpu.setCpuRate(Util.round(rate, 2));
            }
            Collections.sort(listCpu);
        } catch (final Exception e) {
            logger.debug("CPU利用率的排行查询失败" + e.getMessage());
            e.printStackTrace();
        }
        return listCpu;
    }

    /**
     *
     * @param order
     *            排序（DESC || ASC）
     * @param limit
     *            取几位
     * @return 所有主机内存利用率
     */
    public List<Memory> allHostsMemory(final String order, final Integer limit) {
        final LoginUser user = Util.getLoginUser();
        final Integer userId = user.getUserid();
        final boolean isSuperAdmin = user.isSuperAdmin();

        if (limit <= 0) {
            return null;
        }
        List<Memory> listMemory = null;
        final List<Memory> listMemory3 = new ArrayList<Memory>();
        final List<Memory> listMemory2 = new ArrayList<Memory>();
        try {
            logger.debug("开始内存使用率的排行查询");
            if (isSuperAdmin) {
                listMemory = formViewMapper.findComputerConfigMessageforMemoryRate(Constant.USE_MEMORY_RATE,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA, order, limit);

                final List<Long> hostsId = formViewMapper.findAllSnmpFreeRateHost(
                    Constant.DISK_UNUSE_PERCENT, new Date().getTime() / 1000 - Constant.LATEST_DATA);

                for (int i = 0; i < hostsId.size(); i++) {
                    final String myhostsId = String.valueOf(hostsId.get(i));
                    final List<DiskUsageInfo> freeRateInfo = formViewMapper.findFreeRateByHostId(
                        Constant.DISK_UNUSE_PERCENT,
                        myhostsId, new Date().getTime() / 1000 - Constant.LATEST_DATA);

                    for (Integer j = 0; j < freeRateInfo.size(); j++) {
                        final String driveLetter = freeRateInfo.get(j).getDriveLetter();// 处理磁盘符
                        if (null != driveLetter && driveLetter.contains("Physical Memory")) {
                            final double total = 100;
                            final Double snmpMemoryRate = total - Util.round(freeRateInfo.get(j).getFreeRate(), 2);

                            final String hostname = formViewMapper.findHostNameByHostId(hostsId.get(i));
                            final Memory m2 = new Memory();
                            m2.setHostId(hostsId.get(i));
                            m2.setHostName(hostname);
                            m2.setMemoryRate(snmpMemoryRate);
                            listMemory2.add(m2);
                        }
                    }

                }

            } else {
                listMemory = formViewMapper.findComputerConfigMessageforMemoryRateByUser(Constant.USE_MEMORY_RATE,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA, order, limit, userId);
            }
            listMemory.addAll(listMemory2);

            for (final Memory m : listMemory) {
                final double rate = m.getMemoryRate();
                m.setMemoryRate(Util.round(rate, 2));
            }
            Collections.sort(listMemory);
            if (listMemory.size() > limit) {
                listMemory3.addAll(listMemory.subList(0, limit));
            } else {
                listMemory3.addAll(listMemory.subList(0, listMemory.size()));
            }

        } catch (final Exception e) {
            logger.debug("内存使用率的排行查询失败" + e.getMessage());
            e.printStackTrace();
        }
        return listMemory3;
        /*
        if (limit <= 0) {
            return null;
        }
        int index = 0;
        Map<Long, Memory> memoryData = new HashMap<Long, Memory>();
        List<Memory> listMemory = null;
        try {
            logger.debug("开始查询内存利用率信息");
            List<Memory> freeMemory = formViewMapper.findComputerConfigMessageforFreeMemory(Constant.ITEMS_FREE_MEMORY,
                new Date().getTime() / 1000 - Constant.LATEST_DATA, order, limit);
            Long[] memoryId = new Long[freeMemory.size()];
            for (Memory memory : freeMemory) {
                memoryId[index] = memory.getHostId();
                index++;
            }
            for (int i = 0; i < memoryId.length; i++) {
                Memory memory = new Memory();
                memoryData.put(memoryId[i], memory);
            }
            int j = 0;
            for (Memory memory : freeMemory) {
                Memory old = memoryData.get(memoryId[j]);
                old.setFreeMemory(memory.getFreeMemory());
                old.setHostId(memory.getHostId());
                old.setHostName(memory.getHostName());
                j++;
            }
            for (int i = 0; i < memoryId.length; i++) {
                List<Memory> totalMemory = formViewMapper.findComputerConfigMessageforTotalMemory(
                    Constant.ITEMS_TOTAL_MEMORY, memoryId[i], new Date().getTime() / 1000 - Constant.LATEST_DATA);
                if (0 == totalMemory.size()) {
                    Memory old = memoryData.get(memoryId[i]);
                    old.setTotalMemory(-1l);
                    old.setMemoryRate(-1d);
                } else {
                    for (Memory memory : totalMemory) {
                        Memory old = memoryData.get(memoryId[i]);
                        old.setTotalMemory(memory.getTotalMemory());
                        Long fm = old.getFreeMemory();
                        Long tm = old.getTotalMemory();
                        double rate = (double) (tm - fm) / tm;
                        old.setMemoryRate(Util.round(rate * 100, 2));
                    }
                }
            }
            listMemory = new ArrayList<Memory>(memoryData.values());
            Collections.sort(listMemory);
        } catch (Exception e) {
            logger.debug("查询内存利用率信息失败" + e.getMessage());
            e.printStackTrace();
        }
        return listMemory;
         */
    }

    /**
     *
     * @param hostId
     *            主机id
     * @return 群组id
     */
    public Long findGroupIdByHostId(final Long hostId) {
        final Long groupId = formViewMapper.findGroupIdByHostId(hostId);
        return groupId;
    }

    /**
     *
     * @param hosts
     *            前端页面保存的ID 当前关注
     * @return 单个主机的查询，返回主机CPU，磁盘，内存，可用性等信息
     */
    public Map<Long, OneHostConfig> currentFocus(final String hosts) {

        // final long startTime = System.currentTimeMillis(); //获取开始时间

        if (null == hosts || "".equals(hosts.trim())) {
            return null;
        }
        Map<Long, OneHostConfig> currentData = null;
        try {
            logger.debug("开始查询单个主机的各项配置信息");

            String[] hostids = hosts.split(",");

            final LoginUser user = Util.getLoginUser();
            user.getUserid();
            if (!user.isSuperAdmin()) {
                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<String> resposes = new ArrayList<String>();
                    if (null != response.getResult()) {
                        for (int i = 0; i < response.getResult().size(); i++) {
                            if (null != response.getResult().get(i).getHosts()) {
                                for (int j = 0; j < response.getResult().get(i).getHosts().size(); j++) {
                                    resposes.add(response.getResult().get(i).getHosts().get(j).getHostid().toString());
                                }
                            }
                        }
                    }
                    final List<String> myhostids2 = new ArrayList<String>();

                    for (int i = 0; i < hostids.length; i++) {
                        if (resposes.contains(hostids[i])) {
                            myhostids2.add(hostids[i]);
                        }
                    }
                    String[] myhostids;
                    myhostids = new String[myhostids2.size()];
                    for (int i = 0; i < myhostids2.size(); i++) {
                        myhostids[i] = myhostids2.get(i);
                    }
                    hostids = myhostids;
                } catch (final ZabbixApiException e) {
                    throw new RuntimeException(e);
                }

            } else {
                hostids = hosts.split(",");

            }

            currentData = new HashMap<Long, OneHostConfig>();
            for (int i = 0; i < hostids.length; i++) {
                final OneHostConfig host = new OneHostConfig();
                currentData.put(Long.valueOf(hostids[i]), host);
            }

            for (int i = 0; i < hostids.length; i++) {

                final OneHostConfig old = currentData.get(Long.valueOf(hostids[i]));

                //memory,response,CPU
                final List<OneHostConfig> myOneHostConfig = formViewMapper.findOneHostConfigByHostidandTime(
                    Long.valueOf(hostids[i]),
                    Constant.USE_MEMORY_RATE, Constant.ICMP_RESPONSE, Constant.CPU_USE_PERCENT,
                    new Date().getTime() / 1000 - Constant.LATEST_DATA);

                //trigger
                final List<OneHostConfig> listHostConfig = formViewMapper
                    .findOneHostConfigByHostId(Long.valueOf(hostids[i]));

                Double memoryRate2;
                if (0 != myOneHostConfig.size()) {
                    memoryRate2 = Util.round(myOneHostConfig.get(0).getMemoryRate(), 2);
                    old.setMemoryRate(memoryRate2);
                } else {

                    final Double memoryRate = formViewMapper.findMemoryRateByHostId(Constant.USE_MEMORY_RATE,
                        hostids[i],
                        new Date().getTime() / 1000 - Constant.LATEST_DATA);

                    if (null != memoryRate) {
                        memoryRate2 = Util.round(memoryRate, 2);
                        old.setMemoryRate(memoryRate);
                    } else {
                        //windows服务器snmp监控下的内存使用率
                        final List<DiskUsageInfo> freeRateInfo = formViewMapper.findFreeRateByHostIdAndPhysicalMemory(
                            Constant.DISK_UNUSE_PERCENT, Constant.PHISICAL_MEMORY,
                            hostids[i], new Date().getTime() / 1000 - Constant.LATEST_DATA);

                        if (listHostConfig.get(0).getSnmpAvailable() == 1) {
                            final Integer length = freeRateInfo.size();
                            for (Integer j = 0; j < length; j++) {
                                final String driveLetter = freeRateInfo.get(j).getDriveLetter();// 处理磁盘符
                                if (null != driveLetter && driveLetter.contains("Physical Memory")) {
                                    final double total = 100;
                                    final Double snmpMemoryRate = total
                                        - Util.round(freeRateInfo.get(j).getFreeRate(), 2);
                                    old.setMemoryRate(snmpMemoryRate);
                                }
                            }
                        }
                    }

                }

                //host detail

                for (final OneHostConfig host : listHostConfig) {

                    if (null == host) {
                        old.setTotalException(-1);
                        old.setMaxPriority(-1);

                    } else {

                        old.setName(host.getName());
                        old.setAvailable(host.getAvailable());
                        old.setSnmpAvailable(host.getSnmpAvailable());
                        old.setJmxAvailable(host.getJmxAvailable());
                        old.setIpmiAvailable(host.getIpmiAvailable());
                        old.setTotalException(host.getTotalException());

                        //groupId,hostType,hostId
                        old.setHostType(host.getHostType());
                        old.setGroupId(host.getGroupId());
                        old.setHostId(Long.parseLong(hostids[i]));

                        if (null == old.getGroupId()) {
                            Long groupId = this.findGroupIdByHostId(old.getHostId());
                            old.setGroupId(groupId);
                        }
                        //异常为0
                        if (Integer.valueOf(host.getTotalException()) == 0) {
                            old.setMaxPriority(-1);
                        } else if (Integer.valueOf(host.getTotalException()) > 0) {
                            old.setMaxPriority(host.getMaxPriority());
                        }

                    }

                }

                if (0 == myOneHostConfig.size()) {
                    final List<OneHostConfig> listInterface = formViewMapper.findTotalInterface(
                        Long.valueOf(hostids[i]),
                        Constant.ICMP_RESPONSE, new Date().getTime() / 1000 - Constant.LATEST_DATA);
                    if (0 == listInterface.size()) {
                        old.setTotalInterFace(-1d);
                    } else {
                        for (final OneHostConfig host : listInterface) {
                            if (null == host || 0 == host.getTotalInterFace()) {
                                old.setTotalInterFace(-1d);
                            } else {
                                old.setTotalInterFace(host.getTotalInterFace());
                            }
                        }
                    }
                } else {
                    for (final OneHostConfig host : myOneHostConfig) {
                        if (null == host || 0 == myOneHostConfig.get(0).getTotalInterFace()) {
                            old.setTotalInterFace(-1d);
                        } else {
                            old.setTotalInterFace(myOneHostConfig.get(0).getTotalInterFace());
                        }
                    }
                }

                if (myOneHostConfig.size() >= 1) {
                    if (myOneHostConfig.get(0).getCpuRate() == 0) {
                        final List<OneHostConfig> listCpu = formViewMapper.findComputerConfigforCpuByHostId(
                            Constant.CPU_USE_PERCENT,
                            Long.valueOf(hostids[i]), new Date().getTime() / 1000 - Constant.LATEST_DATA);
                        if (listCpu.size() == 0) {
                            old.setCpuRate(-1d);
                        } else {
                            for (final OneHostConfig host : listCpu) {
                                if (null == host) {
                                    old.setCpuRate(-1d);
                                } else {
                                    old.setCpuRate(Util.round(host.getCpuRate(), 2));
                                }
                            }
                        }

                    } else {
                        for (final OneHostConfig host : myOneHostConfig) {
                            if (null == host) {
                                old.setCpuRate(-1d);
                            } else {
                                old.setCpuRate(Util.round(myOneHostConfig.get(0).getCpuRate(), 2));
                            }
                        }
                    }
                } else {
                    //snmp监控下的CPU使用率
                    Double usedCpuRate = monitorConfigMapper.findAvgCpuRateByHostId(Constant.CPU_USE_PERCENT_FLAG,
                        Long.valueOf(hostids[i]),
                        new Date().getTime() / 1000 - Constant.LATEST_DATA);
                    if (usedCpuRate != null) {
                        usedCpuRate = Util.round(usedCpuRate, 2);
                        old.setCpuRate(usedCpuRate);
                        final String cpuRateGraphId = monitorConfigMapper.findsnmpCpuGraphIdByHostId(
                            Constant.CPU_USE_PERCENT_FLAG, Long.valueOf(hostids[i]));
                        if (cpuRateGraphId != null) {
                            //old.setCpuRateGraphId(cpuRateGraphId);
                        }
                    }
                }
            }
        } catch (final NumberFormatException e) {
            logger.debug("查询单个主机的各项配置信息失败" + e.getMessage());
            e.printStackTrace();
        } catch (final Exception e) {
            logger.debug("查询单个主机的各项配置信息失败" + e.getMessage());
            e.printStackTrace();
        }

        return currentData;
    }

    /**
     *
     * @param groupName
     *            组名
     * @param hostIp
     *            主机的名字
     * @return 在当前关注页面弹出框中根据组名查主机
     */
    public List<HostByGroup> findHostByGroup(final String groupName, String hostIp) {
        List<HostByGroup> listHostByGroup = null;
        try {
            logger.debug("开始根据组名查询主机");
            if (hostIp != null && !"".equals(hostIp.trim())) {
                hostIp = "h. name ='" + hostIp + "'";
            } else {
                hostIp = "1=1";
            }
            listHostByGroup = formViewMapper.findHostByGroup(groupName, hostIp);
        } catch (final Exception e) {
            logger.debug("根据组名查询主机失败" + e.getMessage());
            e.printStackTrace();
        }
        return listHostByGroup;
    }

    /**
     *
     * @param groupId
     *            群组id
     * @param hostIp
     *            主机ip
     * @return
     *         相应群组主机
     */

    public List<HostByGroup> findHostByGroupId(final String groupId, String hostIp) {
        List<HostByGroup> listHostByGroup = null;
        try {
            logger.debug("开始根据组名查询主机");
            if (hostIp != null && !"".equals(hostIp.trim())) {
                //hostIp = "h. name ='" + hostIp + "'";
                hostIp = "h. name like '" + "%" + hostIp + "%" + "'";
                //System.out.println(hostIp);
            } else {
                hostIp = "1=1";
            }
            listHostByGroup = formViewMapper.findHostByGroupId(groupId, hostIp);
        } catch (final Exception e) {
            logger.debug("根据组名查询主机失败" + e.getMessage());
            e.printStackTrace();
        }
        return listHostByGroup;
    }

    /**
     *
     * @param name
     *            主机组名
     * @return 这个组下的异常分布情况
     */
    public List<PriorityCount> findCountByPriority(final String name) {
        final LoginUser user = Util.getLoginUser();
        final Integer userId = user.getUserid();
        final boolean isSuperAdmin = user.isSuperAdmin();
        if (null == name || "".equals(name.trim())) {
            return null;
        }
        List<PriorityCount> listPriorityCount = null;

        try {
            logger.debug("开始查询异常数量");
            //sql语句拼接 选择"所有" 1=1
            if (name.trim().equals("全部")) {
                if (isSuperAdmin) {
                    listPriorityCount = formViewMapper.findCountByPriority("1=1");
                } else {
                    listPriorityCount = formViewMapper.findCountByPriorityByUser(userId);
                }
                //listPriorityCount = formViewMapper.findCountByPriority("1=1");
                // listPriorityCount = formViewMapper.findCountByPriorityByUser(userId);
            } else {
                listPriorityCount = formViewMapper.findCountByPriority("g.name='" + name + "'");
            }

        } catch (final Exception e) {
            logger.debug("查询异常数量失败" + e.getMessage());
            e.printStackTrace();
        }
        return listPriorityCount;
    }

    /**
     * @param priority
     *            等级
     * @param name
     *            主机组的名字
     * @return 根据饼状图点击查出来具体哪个主机组下哪个告警等级的的触发器异常信息
     */
    @SuppressWarnings("unchecked")
    public List<PriorityDetail> findMessageByPriority(final Integer priority, final String name) {
        final Map<Long, PriorityDetail> messagemap = new HashMap<Long, PriorityDetail>();
        List<PriorityDetail> list = null;
        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();
        //不同模块的缓存名称不同，带参数，便于匹配
        String ehcacheKey = "messageByPriority" + priority + name;
        //根据对应点击模块匹配相应的缓存内容,第一次查询SQL无缓存
        if (null != EhcacheUtil.get(ehcacheKey)) {
            //logger.info("ehcache:{}", EhcacheUtil.get("messageByPriority" + priority + name));
            list = (ArrayList<PriorityDetail>) EhcacheUtil.get("messageByPriority" + priority + name);
            Collections.sort(list);
            return list;
        }

        try {
            logger.debug("开始根据异常等级查出具体主机异常信息");
            List<PriorityDetail> listPriorityDetail = new ArrayList<>();
            //sql语句拼接 选择"所有" 1=1
            if (name.equals("全部")) {
                listPriorityDetail = formViewMapper.findMessageByPriority(priority, "1=1");
            } else {
                listPriorityDetail = formViewMapper.findMessageByPriority(priority, "g.name='" + name + "'");
            }
            //logger.info("1:{}",listPriorityDetail);

            final Long[] eventid = new Long[listPriorityDetail.size()];
            int index = 0;
            for (final PriorityDetail pd : listPriorityDetail) {
                eventid[index] = (long) index;
                final PriorityDetail priorityDetail = new PriorityDetail();
                priorityDetail.setObjectid(pd.getObjectid());
                priorityDetail.setHost(pd.getHost());
                priorityDetail.setName(pd.getName());
                priorityDetail.setEndClock(new Date().getTime() / 1000);
                messagemap.put(eventid[index], priorityDetail);
                index++;
            }
            for (int i = 0; i < eventid.length; i++) {
                final PriorityDetail old = messagemap.get(eventid[i]);
                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 List<PriorityDetail> lp = formViewMapper.findStartClock(old.getObjectid());
                for (final PriorityDetail pd : lp) {
                    old.setStartClock(pd.getStartClock());
                }
                /*  final List<PriorityDetail> acknowledge = formViewMapper
                        .findAcknowledgeByObjectId(old.getObjectid());
                    for (final PriorityDetail ac : acknowledge) {
                        old.setAcknowledged(ac.getAcknowledged());
                    }*/
                old.setSubClock(Util.getDiff(old.getEndClock() - old.getStartClock()));
            }
        } catch (final Exception e) {
            logger.debug("根据异常等级查出具体主机异常信息失败" + e.getMessage());
            e.printStackTrace();
        }

        //final List<PriorityDetail> list = new ArrayList<>(messagemap.values());
        list = new ArrayList<>(messagemap.values());
        Collections.sort(list);

        // logger.info("{}", ehcacheKey);
        //存入缓存,方便二次查询
        EhcacheUtil.put(ehcacheKey, list);
        // logger.info("ehcache:{}",EhcacheUtil.get(ehcacheKey));
        return list;
    }

    // }

    /**
     *
     * @param str
     *            当前关注框字符串
     */
    public void saveConfig(final String str) {
        JSON.saveStringToFile(str, Constant.FILEPATH);
    }

    /**
     *
     * @param str
     *            页面中的组件设置字符串
     */
    public void savePageCfg(final String str) {
        JSON.saveStringToFile(str, Constant.PAGECFGPATH);
    }

    /**
     *
     * @return 从文件中取出字符串
     */
    public Map<Integer, Map<String, String>> getConfig() {
        final String str = JSON.getStringFromFile(Constant.FILEPATH);
        if (str == null || "".equals(str.trim())) {
            return null;
        }
        final List<String> myhostids = new ArrayList<String>();

        final List<String> myhostids2 = new ArrayList<String>();

        final String[] array = str.split(";");
        final List<String> list = new ArrayList<>();
        final Map<Integer, Map<String, String>> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            final String str2 = array[i];
            final Integer id = Integer.valueOf(str2.substring(str2.lastIndexOf(",") + 1, str2.length()));
            final Integer isExist = formViewMapper.findHostIsExist(id);
            if (isExist > 0) {
                list.add(str2);
            }
        }
        if (0 == list.size()) {
            return null;
        } else {
            final Object[] filterArray = list.toArray();
            for (int i = 0; i < filterArray.length; i++) {
                final Map<String, String> newMap = new HashMap<>();
                final String[] newArray = ((String) filterArray[i]).split(",");
                for (int j = 0; j < newArray.length; j++) {
                    if (j == 0) {
                        newMap.put("name", newArray[j]);
                    }
                    if (j == 1) {
                        newMap.put("ip", newArray[j]);
                    }
                    if (j == 2) {
                        newMap.put("id", newArray[j]);
                        myhostids.add(newArray[j]);
                        /*String hostId = newArray[j];
                        int hostType = formViewMapper.findHostType(hostId);
                        if(Constant.SWITCH_BOARD.equals(String.valueOf(hostType))){
                        newMap.put("name", "交换机");
                        }else if(hostType == Constant.SERVER){
                        newMap.put("name", "服务器");
                        }else if(hostType==Constant.ROUTER){
                        newMap.put("name", "路由器");
                        }else if(hostType == Constant.MIDDLEWARE){
                        newMap.put("name", "中间件");
                        }else if(hostType==Constant.FIREWALL){
                        newMap.put("name", "防火墙");
                        }else if(Constant.PC.equals(String.valueOf(hostType))){
                        newMap.put("name", "PC机");
                        }*/
                    }
                }
                map.put(i, newMap);
            }
        }
        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);
        HostgroupGetResponse response = null;
        try {
            response = zabbixApi.hostgroup().get(request);
        } catch (final ZabbixApiException e) {
            e.printStackTrace();
        }
        final List<String> resposes2 = new ArrayList<String>();

        if (null != response && null != response.getResult()) {
            for (int i = 0; i < response.getResult().size(); i++) {
                if (null != response.getResult().get(i).getHosts()) {
                    for (int j = 0; j < response.getResult().get(i).getHosts().size(); j++) {
                        resposes2.add(response.getResult().get(i).getHosts().get(j).getHostid().toString());
                    }
                }
            }
        }
        for (int i = 0; i < myhostids.size(); i++) {
            if (resposes2.contains(myhostids.get(i))) {
                myhostids2.add(myhostids.get(i));
            }
        }

        final Map<Integer, Map<String, String>> map2 = new HashMap<>();
        int i = 0;
        for (final Integer in : map.keySet()) {
            final Map<String, String> hostMap = map.get(in);
            final String hostId = hostMap.get("id");
            if (myhostids2.contains(hostId)) {
                map2.put(i, hostMap);
                i++;
            }
        }
        return map2;
    }

    /**
     *
     * @return 从文件中取出保存的组件字符串
     */
    public Map<Integer, String[]> getPageConfig() {
        final String str = JSON.getStringFromFile(Constant.PAGECFGPATH);
        if (str == null || "".equals(str.trim())) {
            return null;
        }
        final String[] array = str.split(";");
        final Map<Integer, String[]> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            if (!"".equals(array[i]) || null != (array[i])) {
                map.put(i, array[i].split(","));
            }
        }
        return map;
    }

    public Integer findUserRefresh(final Integer userId) {
        final Integer time = formViewMapper.findUserRefreshByUserId(userId);
        return time;
    }

    /**
     *
     * @return 返回主机组
     *
     */

    public List<HostgroupGetResponse.Result> getHostGroups() {
        try {
            final HostgroupGetRequest request = new HostgroupGetRequest();
            final HostgroupGetRequest.Params params = request.getParams();
            params.setSelectHosts(ZabbixApiParamter.QUERY.extend.name());
            final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
            final HostgroupGetResponse response = zabbixApi.hostgroup().get(request);
            final List<com.zabbix4j.hostgroup.HostgroupGetResponse.Result> newlist = new ArrayList<>();
            for (final com.zabbix4j.hostgroup.HostgroupGetResponse.Result result : response.getResult()) {
                newlist.add(result);
            }
            return newlist;
        } catch (final ZabbixApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @return 触发器
     *
     */

    public List<TriggerGetResponse.Result> getTriggers(final int hostId) {
        try {
            final TriggerGetRequest request = new TriggerGetRequest();
            final TriggerGetRequest.Params params = request.getParams();
            params.setExpandDescription(true);
            params.setExpandExpression(true);
            params.addHostid(hostId);

            final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();

            final TriggerGetResponse response = zabbixApi.trigger().get(request);
            final List<TriggerGetResponse.Result> newlist = new ArrayList<>();
            for (final TriggerGetResponse.Result result : response.getResult()) {
                newlist.add(result);
            }
            return newlist;
        } catch (final ZabbixApiException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @return 返回主机组
     */

    public List<HostgroupGetResponse.Result> listHostGroups() {
        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 (com.zabbix4j.hostgroup.HostgroupGetResponse.Result result : newlist) {
              for (HostObject obj : result.getHosts()) {
                  obj.setState(formViewMapper.findHostStatus(obj.getHostid()));
              }
             }*/
            return newlist;
        } catch (final ZabbixApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @return 返回主机类型
     *
     */
    public List<String> getType(final String hostId) {
        final List<String> type = new ArrayList<String>();
        final int hostType = formViewMapper.findHostType(hostId);
        type.add(String.valueOf(hostType));

        return type;
    }

}
