/**
 * <p>Copyright:Copyright(c) 2017</p>
 * <p>Company:上海中信信息发展股份有限公司</p>
 * <p>包名:com.cesgroup.cesmonitor.service.screen</p>
 * <p>文件名:ScreenService.java</p>
 * <p>创建时间:2017年6月9日 下午1:16:12</p>
 * <p>作者:Administrator</p>
 */

package com.cesgroup.cesmonitor.service.screen;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.shiro.util.ThreadContext;
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.common.Constant;
import com.cesgroup.cesmonitor.common.Util;
import com.cesgroup.cesmonitor.dao.ScreenMapper;
import com.cesgroup.cesmonitor.screenbean.AbnormalAlarmScreen;
import com.cesgroup.cesmonitor.screenbean.AttentionedHost;
import com.cesgroup.cesmonitor.screenbean.AttentionedHostItem;
import com.cesgroup.cesmonitor.screenbean.CpuScreen;
import com.cesgroup.cesmonitor.screenbean.MonitorAlarm;
import com.cesgroup.cesmonitor.screenbean.NetWorkTraffic;
import com.cesgroup.cesmonitor.screenbean.NumberCount;
import com.cesgroup.cesmonitor.screenbean.PriorityCountScreen;
import com.cesgroup.cesmonitor.screenbean.PriorityDetailScreen;
import com.cesgroup.cesmonitor.screenbean.PriorityScreen;
import com.cesgroup.cesmonitor.screenbean.TopologicalScreen;
import com.cesgroup.cesmonitor.screenbean.Usability;
import com.cesgroup.cesmonitor.service.IdentityService;
import com.cesgroup.cesmonitor.service.LoginUser;
import com.zabbix4j.ZabbixApi;
import com.zabbix4j.ZabbixApiException;
import com.zabbix4j.ZabbixApiParamter;
import com.zabbix4j.host.HostObject;
import com.zabbix4j.itservice.ITServiceGetSlaRequest;
import com.zabbix4j.itservice.ITServiceGetSlaResponse;
import com.zabbix4j.itservice.ITServiceGetSlaResponse.Sla;
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;

/**
 * 大屏处理功能
 *
 * @author cloud
 * @version 1.0.0 2017年6月9日
 */
@Service("screenService")
public class ScreenService {

    @Autowired
    ScreenMapper screenMapper;

    //用户名
    @Value("${screen.userName}")
    private String userName;

    //密码
    @Value("${screen.password}")
    private String password;

    @Autowired
    protected IdentityService identityService;

    LoginUser user = null;

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

    /**
     *
     * @return 返回用户登录信息
     */
    public LoginUser initUser() {
        if (user == null) {
            user = identityService.login(userName, password);
        }
        ThreadContext.put(IdentityService.LOGIN_USER, userName);
        return user;
    }

    /**
     *
     * @return 返回节点数量，告警数量
     */
    public NumberCount findNumber() {
        final NumberCount numberCount = new NumberCount();
        numberCount.setMonitorAlarmNum(screenMapper.findMonitorAlarmNum());
        numberCount.setMonitorNodeNum(screenMapper.findMonitorNodeNum());
        numberCount.setFalutMonitorNodeNum(screenMapper.findFaultMonitorNodeNum());
        numberCount.setNormalMonitorNodeNum(screenMapper.findMonitorNodeNum() - screenMapper.findFaultMonitorNodeNum());
        return numberCount;
    }

    /**
     * @return 返回监控告警列表（最近20条数据）
     */
    public List<MonitorAlarm> findMonitorAlarmList() {
        initUser();
        final List<MonitorAlarm> listMonitorAlarm = screenMapper.findMonitorAlarmList();
        if (listMonitorAlarm == null || 0 == listMonitorAlarm.size()) {
            return null;
        }
        final TriggerGetRequest request = new TriggerGetRequest();
        final TriggerGetRequest.Params params = request.getParams();
        params.setExpandDescription(true);
        params.setExpandExpression(true);
        TriggerGetResponse response = null;
        final Map<Long, MonitorAlarm> messagemap = new HashMap<Long, MonitorAlarm>();
        final Long[] symbol = new Long[listMonitorAlarm.size()];
        int index = 0;
        for (final MonitorAlarm ma : listMonitorAlarm) {
            symbol[index] = (long) index;
            final MonitorAlarm monitorAlarm = new MonitorAlarm();
            monitorAlarm.setHost(ma.getHost());
            monitorAlarm.setNumber(index + 1);
            monitorAlarm.setPriority(ma.getPriority());
            monitorAlarm.setTriggerid(ma.getTriggerid());
            messagemap.put(symbol[index], monitorAlarm);
            index++;
        }
        final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
        for (int i = 0; i < symbol.length; i++) {
            final MonitorAlarm old = messagemap.get(symbol[i]);
            params.addTriggerid(old.getTriggerid());
            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 e) {
                e.printStackTrace();
            }
        }

        return new ArrayList<>(messagemap.values());
    }

    /**
     *
     * @return 返回可用性列表
     */
    public List<Usability> findUseAbilty(final Integer time) {
        initUser();
        final List<Usability> listUsability = screenMapper.findUseAbilty();
        if (null == listUsability || 0 == listUsability.size()) {
            return null;
        }
        final Integer[] symbol = new Integer[listUsability.size()];
        final Map<Integer, Usability> abiltyMap = new HashMap<>();
        final ITServiceGetSlaRequest request = new ITServiceGetSlaRequest();
        final ITServiceGetSlaRequest.Params params = request.getParams();
        final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
        int index = 0;
        for (final Usability ualty : listUsability) {
            symbol[index] = index;
            final Usability usability = new Usability();
            usability.setName(ualty.getName());
            usability.setServiceid(ualty.getServiceid());
            abiltyMap.put(symbol[index], usability);
            index++;
        }
        Long timetemp = null;
        switch (time) {
        case 0:
            timetemp = Util.getDayBegin().getTime() / 1000;
            break;
        case 1:
            timetemp = Util.getBeginDayOfWeek().getTime() / 1000 - 24 * 3600;
            break;
        case 2:
            timetemp = Util.getBeginDayOfMonth().getTime() / 1000;
            break;
        case 3:
            timetemp = Util.getBeginDayOfYear().getTime() / 1000;
            break;
        case 4:
            timetemp = new Date().getTime() / 1000 - 24 * 3600;
            break;
        case 5:
            timetemp = new Date().getTime() / 1000 - 7 * 24 * 3600;
            break;
        case 6:
            timetemp = new Date().getTime() / 1000 - 30 * 24 * 3600;
            break;
        case 7:
            timetemp = new Date().getTime() / 1000 - 365 * 24 * 3600;
            break;
        }
        params.addInterval(timetemp, new Date().getTime() / 1000);
        for (int i = 0; i < symbol.length; i++) {
            final Usability old = abiltyMap.get(symbol[i]);
            try {
                params.addSerivceId(old.getServiceid());
                final ITServiceGetSlaResponse response = zabbixApi.itservice().getSla(request);
                final Map<String, com.zabbix4j.itservice.ITServiceGetSlaResponse.Result> lr = response.getResult();
                for (final com.zabbix4j.itservice.ITServiceGetSlaResponse.Result rs : lr.values()) {
                    final List<Sla> listSla = rs.getSla();
                    for (final Sla sla : listSla) {
                        old.setShowsla(sla.getSla());
                    }
                    params.getServiceids().clear();
                }
            } catch (final ZabbixApiException e) {
                e.printStackTrace();
            }
        }
        final List<Usability> list = new ArrayList<>(abiltyMap.values());
        Collections.sort(list);
        return list;
    }

    /**
     *
     * @param limit
     *            取20还是50条数据
     * @return 返回当前故障列表
     */
    public List<PriorityDetailScreen> findPriorityDetailScreen(final Integer priority, final Integer limit) {

        initUser();
        final Map<Long, PriorityDetailScreen> messagemap = new HashMap<Long, PriorityDetailScreen>();
        final TriggerGetRequest request = new TriggerGetRequest();
        final TriggerGetRequest.Params params = request.getParams();
        params.setExpandDescription(true);
        TriggerGetResponse response = null;
        final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
        final List<PriorityDetailScreen> listPriorityDetailScreen = screenMapper.findAlarmList(priority, limit);
        Long index = 0L;
        for (final PriorityDetailScreen pd : listPriorityDetailScreen) {
            final PriorityDetailScreen alarmList = new PriorityDetailScreen();
            alarmList.setPriority(pd.getPriority());
            alarmList.setObjectid(pd.getObjectid());
            alarmList.setEndClock(new Date().getTime() / 1000);
            alarmList.setHost(pd.getHost());
            messagemap.put(index, alarmList);
            final PriorityDetailScreen old = messagemap.get(index);
            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());
                    final String replaceString = "{HOST.NAME}";
                    String description;
                    if (old.getDescription().contains(replaceString)) {
                        description = old.getDescription().replace(replaceString, old.getHost());
                        old.setDescription(description);
                    } else if (old.getDescription().contains(replaceString.toLowerCase())) {
                        description = old.getDescription().replace(replaceString.toLowerCase(), old.getHost());
                        old.setDescription(description);
                    }
                    params.getTriggerids().clear();
                }
            } catch (final ZabbixApiException e1) {
                e1.printStackTrace();
            }
            final List<PriorityDetailScreen> lp = screenMapper.findStartClock(old.getObjectid());
            for (final PriorityDetailScreen pd2 : lp) {
                old.setStartClock(pd2.getStartClock());
            }
            old.setSubClock(Util.getDiff(old.getEndClock() - old.getStartClock()));
            index++;
        }
        final List<PriorityDetailScreen> list = new ArrayList<>(messagemap.values());

        Collections.sort(list);

        return list;
    }

    /**
     *
     * @param limit
     *            取几位
     * @return 所有主机CPU利用率
     */
    public List<CpuScreen> allHostsCpu(final Integer threshold, final Integer limit) {
        if (limit <= 0) {
            return null;
        }
        List<CpuScreen> listCpu = null;
        try {
            listCpu = screenMapper.findComputerConfigMessageforCpu(Constant.CPU_USE_PERCENT,
                new Date().getTime() / 1000 - Constant.LATEST_DATA, threshold, limit);
            for (final CpuScreen cpu : listCpu) {
                final double rate = cpu.getCpuRate();
                cpu.setCpuRate(Util.round(rate, 2));
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return listCpu;
    }

    /**
     *
     * @param name
     *            具体组名
     * @return 这个组下的异常分布情况
     */
    public List<PriorityCountScreen> findCountByName(String name) {
        if (name != null && !"".equals(name.trim())) {
            /*  name = "g.name ='" + name + "'";*/
            if (name.equals("PC机")) {
                name = "h.host_type=6";//设备类型host_type的值
            } else if (name.equals("交换机")) {
                name = "h.host_type=1";
            } else if (name.equals("服务器")) {
                name = "h.host_type=2";
            }
        } else {
            name = "1=1";
        }
        final List<PriorityCountScreen> listPriorityCountScreen = screenMapper.findCountByPriority(name);
        if (0 == listPriorityCountScreen.size()) {
            return null;
        }
        return listPriorityCountScreen;
    }

    /**
     *
     * @return 返回异常分组信息
     */
    public List<PriorityScreen> findCountGroupByPriority() {
        final List<PriorityScreen> listPriorityScreen = screenMapper.findCountGroupByPriority();
        if (0 == listPriorityScreen.size()) {
            return null;
        }
        return listPriorityScreen;
    }

    private final Long todayStartTime = Util.getYesterdayLastTimeTime() + 1;

    /**
     * 统计网络流量service
     *
     * @param host
     *            主机
     * @return 网络流量
     */
    public List<NetWorkTraffic> sumNetWorkTrafficService(final String host) {
        final Long timeFormat = 60 * 60L; //时间格式，一个小时
        final Long currentTime = new Date().getTime() / 1000; //单位为s
        final Long size = (currentTime - todayStartTime) / timeFormat; //获取小时数
        final List<NetWorkTraffic> netWorkTraffics = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            NetWorkTraffic netWorkTraffic = screenMapper.sumNetWorkTrafficMapper(host, todayStartTime + i * timeFormat,
                todayStartTime + (i + 1) * timeFormat);
            if (netWorkTraffic == null) {
                netWorkTraffic = new NetWorkTraffic();
                netWorkTraffic.setHost(host);
                netWorkTraffic.setValue(0L);
            }
            netWorkTraffics.add(netWorkTraffic);
        }
        return netWorkTraffics;
    }

    /**
     * 时间段内的异常告警数量
     *
     * @param interval
     *            时间间隔
     * @return 时间段内的异常告警数量
     */
    public List<AbnormalAlarmScreen> countAbnormalAlarmScreenService(final Integer interval) {
        final List<AbnormalAlarmScreen> abnormalAlarmScreens = new ArrayList<>();
        SimpleDateFormat sdf = null;
        Long timeFormat = 0L;
        Long startTime = 0L;
        final Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        if (interval == 24) { //近24小时，不包括当前的一个小时
            timeFormat = 60 * 60L;
            sdf = new SimpleDateFormat("MM-dd HH:mm");
            calendar.add(Calendar.HOUR_OF_DAY, -24);
            startTime = calendar.getTime().getTime() / 1000;
            for (int i = 0; i < interval; i++) {
                final Date date = calendar.getTime();
                final String s = sdf.format(date);
                calendar.add(Calendar.HOUR, 1);
                AbnormalAlarmScreen abnormalAlarmScreen = screenMapper
                    .countAbnormalAlarmScreenMapper(startTime + i * timeFormat, startTime + (i + 1) * timeFormat);
                if (abnormalAlarmScreen == null) {
                    abnormalAlarmScreen = new AbnormalAlarmScreen();
                    abnormalAlarmScreen.setNum(0);
                }
                abnormalAlarmScreen.setTime(s);
                abnormalAlarmScreens.add(abnormalAlarmScreen);
            }
        } else if (interval == 30) { //近30天，不包括今天
            timeFormat = 60 * 60 * 24L;
            sdf = new SimpleDateFormat("MM-dd");
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            calendar.add(Calendar.DAY_OF_YEAR, -31);
            startTime = calendar.getTime().getTime() / 1000;
            for (int i = 0; i < interval; i++) {
                final Date date = calendar.getTime();
                final String s = sdf.format(date);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                AbnormalAlarmScreen abnormalAlarmScreen = screenMapper
                    .countAbnormalAlarmScreenMapper(startTime + i * timeFormat, startTime + (i + 1) * timeFormat);
                if (abnormalAlarmScreen == null) {
                    abnormalAlarmScreen = new AbnormalAlarmScreen();
                    abnormalAlarmScreen.setNum(0);
                }
                abnormalAlarmScreen.setTime(s);
                abnormalAlarmScreens.add(abnormalAlarmScreen);
            }
        } else { //近一年，不包括当前月
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            timeFormat = 60 * 60 * 24L;
            sdf = new SimpleDateFormat("yyyy-MM");
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.add(Calendar.MONTH, -12);
            startTime = calendar.getTime().getTime() / 1000;
            Integer days = 0;
            for (int i = 0; i < interval; i++) {
                final Date date = calendar.getTime();
                final String s = sdf.format(date);
                final Integer day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); //获取每个月的天数
                calendar.add(Calendar.MONTH, 1);
                AbnormalAlarmScreen abnormalAlarmScreen = screenMapper.countAbnormalAlarmScreenMapper(
                    startTime + days * timeFormat, startTime + (days + day) * timeFormat);
                if (abnormalAlarmScreen == null) {
                    abnormalAlarmScreen = new AbnormalAlarmScreen();
                    abnormalAlarmScreen.setNum(0);
                }
                days = days + day; //天数
                abnormalAlarmScreen.setTime(s);
                abnormalAlarmScreens.add(abnormalAlarmScreen);
            }
        }
        return abnormalAlarmScreens;
    }

    /**
     * 查询被关注主机信息
     *
     * @param host
     *            主机
     * @return 主机信息
     */
    public AttentionedHost selectAttentionedHostInfoService(final String host) {
        AttentionedHost attentionedHost = screenMapper.selectAttentionedHostInfoMapper(host);
        final String hostOS = screenMapper.selectAttentionedHostOSMapper(host);
        if (attentionedHost == null) {
            attentionedHost = new AttentionedHost();
            attentionedHost.setHost(host);
            attentionedHost.setIp("0.0.0.0");
            attentionedHost.setStatus(1);
        }
        if (hostOS == null || hostOS.equals("")) {
            attentionedHost.setOs("无");
        } else {
            attentionedHost.setOs(hostOS);
        }
        return attentionedHost;
    }

    /**
     * 查询CPU使用率
     *
     * @param host
     *            主机
     * @return CPU数据
     */
    public AttentionedHostItem selectCpuUsageRateService(final String host) {
        AttentionedHostItem cpuUsageRateItem = screenMapper.selectCpuUsageRateMapper(host);
        if (cpuUsageRateItem == null) {
            cpuUsageRateItem = new AttentionedHostItem();
            cpuUsageRateItem.setHost(host);
            final Double cpuDate = screenMapper.findSnmpCpuRate(host);
            if (cpuDate != null) {
                cpuUsageRateItem.setValue(cpuDate);
            } else {
                cpuUsageRateItem.setValue(0.0);
            }
        }
        return cpuUsageRateItem;
    }

    /**
     * 查询内存使用率
     *
     * @param host
     *            主机
     * @return 内存数据
     */
    public AttentionedHostItem selectMemoryUsageRateService(final String host) {
        AttentionedHostItem memoryUsageRateItem = screenMapper.selectMemoryUsageRateMapper(host);

        boolean flag = false;

        final List<AttentionedHostItem> diskUsageRateItems = screenMapper.selectDiskUsageRateMapper(host);
        if (diskUsageRateItems.size() != 0) {
            for (final AttentionedHostItem diskUsageRateItem : diskUsageRateItems) {
                if (diskUsageRateItem.getItemName().contains("Physical Memory")) {
                    flag = true;
                    memoryUsageRateItem = new AttentionedHostItem();
                    memoryUsageRateItem.setValue(Util.round(diskUsageRateItem.getValue(), 2));
                    memoryUsageRateItem.setHost(host);
                }
            }
        }
        if (memoryUsageRateItem == null && flag == false) {
            memoryUsageRateItem = new AttentionedHostItem();
            memoryUsageRateItem.setHost(host);
            memoryUsageRateItem.setValue(0.0);
        }
        return memoryUsageRateItem;
    }

    /**
     * 查询出磁盘使用率
     *
     * @param host
     *            主机
     * @return 磁盘数据
     */
    public List<AttentionedHostItem> selectDiskUsageRateService(final String host) {
        final List<AttentionedHostItem> diskUsageRateItems = screenMapper.selectDiskUsageRateMapper(host);
        final List<AttentionedHostItem> finalDiskUsageRateItems = new ArrayList<AttentionedHostItem>();

        if (diskUsageRateItems.size() == 0) {
            final AttentionedHostItem attentionedHostItem = new AttentionedHostItem();
            attentionedHostItem.setHost(host);
            diskUsageRateItems.add(attentionedHostItem);
        } else {

            //final List<Integer> listIndex = new ArrayList<Integer>();
            for (final AttentionedHostItem diskUsageRateItem : diskUsageRateItems) {
                if (diskUsageRateItem.getItemName().contains("$")) {
                    final int begin = diskUsageRateItem.getItemKey().indexOf("["); //key_类似vfs.fs.size[C:,pfree]
                    final int end = diskUsageRateItem.getItemKey().indexOf(",");
                    final String drive = diskUsageRateItem.getItemKey().substring(begin + 1, end); //获取盘符,如D:
                    diskUsageRateItem.setItemName(drive);
                    finalDiskUsageRateItems.add(diskUsageRateItem);
                } else if (diskUsageRateItem.getItemName().contains("\\")) {
                    final int end = diskUsageRateItem.getItemName().indexOf("\\");
                    if (end != -1) {
                        final String drive = diskUsageRateItem.getItemName().substring(4, end);
                        diskUsageRateItem.setItemName(drive);
                    }
                    finalDiskUsageRateItems.add(diskUsageRateItem);
                }
                diskUsageRateItem.setValue(Util.round(diskUsageRateItem.getValue(), 2));

            }

        }
        return finalDiskUsageRateItems;
    }

    /**
     * 查询接口状态
     *
     * @param host
     *            主机
     * @return 接口数据
     */
    public List<AttentionedHostItem> selectInterfaceStatusService(final String host) {
        final List<AttentionedHostItem> interfaceStatusItems = screenMapper.selectInterfaceStatusMapper(host);
        if (interfaceStatusItems.size() == 0) {
            final AttentionedHostItem attentionedHostItem = new AttentionedHostItem();
            attentionedHostItem.setHost(host);
            attentionedHostItem.setStatus(Constant.INTERFACE_STATUS_ITEMS);
            interfaceStatusItems.add(attentionedHostItem);
        } else {
            //itemName类似Operational status of interface $1 需从itemKey中解析
            for (final AttentionedHostItem interfaceStatusItem : interfaceStatusItems) {
                if (interfaceStatusItem.getItemName().contains("$")) {
                    final int begin = interfaceStatusItem.getItemKey().indexOf("[");
                    final int end = interfaceStatusItem.getItemKey().indexOf("]");
                    final String interfaceName = interfaceStatusItem.getItemKey().substring(begin + 1, end);
                    interfaceStatusItem.setItemName(interfaceName);
                }
            }
        }
        Util.reduceList(interfaceStatusItems, 4);
        if (null == interfaceStatusItems.get(0).getItemKey()) {
            interfaceStatusItems.clear();
        }
        return interfaceStatusItems;
    }

    /**
     * 流入流量数据
     *
     * @param host
     *            主机
     * @return 流入流量数据
     */
    public List<AttentionedHostItem> selectInterfaceIncomingService(final String host) {
        //Long time = System.currentTimeMillis();
        final List<AttentionedHostItem> interfaceIncomings = screenMapper.selectInterfaceIncomingMapper(host);
        if (interfaceIncomings.size() == 0) {
            final AttentionedHostItem attentionedHostItem = new AttentionedHostItem();
            attentionedHostItem.setHost(host);
            attentionedHostItem.setValue(0.0);
            interfaceIncomings.add(attentionedHostItem);
        } else {
            //解析 $符号
            final Iterator<AttentionedHostItem> it = interfaceIncomings.iterator();
            while (it.hasNext()) {
                final AttentionedHostItem interfaceIncoming = it.next();
                if (interfaceIncoming.getValue() == 0) { //移除相关为0数据
                    it.remove();
                }
                if (interfaceIncoming.getItemName().contains("$")) {
                    final int begin = interfaceIncoming.getItemKey().indexOf("[");
                    final int end = interfaceIncoming.getItemKey().indexOf("]");
                    final String interfaceName = interfaceIncoming.getItemKey().substring(begin + 1, end);
                    interfaceIncoming.setItemName(interfaceName);
                }
                //设置接口状态触发器的等级
                if (screenMapper.selectMaxPriorityByInterfaceName(host, interfaceIncoming.getItemName()) == null) {
                    interfaceIncoming.setStatus(-1);
                } else {
                    interfaceIncoming.setStatus(
                        screenMapper.selectMaxPriorityByInterfaceName(host, interfaceIncoming.getItemName()));
                }
            }
        }
        //System.err.println("查询接口流量进"+(System.currentTimeMillis()-time));
        return interfaceIncomings;
    }

    /**
     * 特定接口的流入流量数据
     *
     * @param host
     *            主机
     * @param interfaceName
     *            接口
     * @return 特定接口的流入流量数据
     */
    public AttentionedHostItem selectInterfaceIncomingByInterfaceNameService(final String host,
        final String interfaceName) {
        //Long time = System.currentTimeMillis();
        AttentionedHostItem interfaceIncoming = screenMapper.selectInterfaceIncomingByInterfaceNameMapper(host,
            interfaceName);
        if (interfaceIncoming == null) {
            interfaceIncoming = new AttentionedHostItem();
            interfaceIncoming.setHost(host);
            interfaceIncoming.setItemName(interfaceName);
            interfaceIncoming.setValue(0.0);
        } else {
            interfaceIncoming.setItemName(interfaceName); //设置itemName为interfaceName
        }
        // System.err.println("查询特定接口流量进"+(System.currentTimeMillis()-time));
        return interfaceIncoming;
    }

    /**
     * 接口流出流量数据
     *
     * @param host
     *            主机
     * @return 流出流量数据
     */
    public List<AttentionedHostItem> selectInterfaceOutgoingService(final String host) {
        //Long time = System.currentTimeMillis();
        final List<AttentionedHostItem> interfaceOutgoings = screenMapper.selectInterfaceOutgoingMapper(host);
        if (interfaceOutgoings.size() == 0) {
            final AttentionedHostItem attentionedHostItem = new AttentionedHostItem();
            attentionedHostItem.setHost(host);
            attentionedHostItem.setValue(0.0);
            interfaceOutgoings.add(attentionedHostItem);
        } else {
            //解析 $符号
            final Iterator<AttentionedHostItem> it = interfaceOutgoings.iterator();
            while (it.hasNext()) {
                final AttentionedHostItem interfaceOutgoing = it.next();
                if (interfaceOutgoing.getValue() == 0) { //移除相关为0数据
                    it.remove();
                }
                if (interfaceOutgoing.getItemName().contains("$")) {
                    final int begin = interfaceOutgoing.getItemKey().indexOf("[");
                    final int end = interfaceOutgoing.getItemKey().indexOf("]");
                    final String interfaceName = interfaceOutgoing.getItemKey().substring(begin + 1, end);
                    interfaceOutgoing.setItemName(interfaceName);
                }
                interfaceOutgoing.setValue(Util.round(interfaceOutgoing.getValue() / 1024, 2)); //bps 转成kbps
            }
        }
        //System.err.println("查询接口流量出"+(System.currentTimeMillis()-time));
        return interfaceOutgoings;
    }

    /**
     * 特定接口的流出流量数据
     *
     * @param host
     *            主机
     * @param interfaceName
     *            接口
     * @return 特定接口的流入流量数据
     */
    public AttentionedHostItem selectInterfaceOutgoingByInterfaceNameService(final String host,
        final String interfaceName) {
        AttentionedHostItem interfaceOutgoing = screenMapper.selectInterfaceOutgoingByInterfaceNameMapper(host,
            interfaceName);
        if (interfaceOutgoing == null) {
            interfaceOutgoing = new AttentionedHostItem();
            interfaceOutgoing.setHost(host);
            interfaceOutgoing.setItemName(interfaceName);
            interfaceOutgoing.setValue(0.0);
        } else {
            interfaceOutgoing.setItemName(interfaceName); //设置itemName为interfaceName
        }
        return interfaceOutgoing;

    }

    /**
     * 特定接口的速率
     *
     * @param host
     *            主机
     * @param interfaceName
     *            接口
     * @return 特定接口的速率
     */
    public AttentionedHostItem selectInterfaceBySpeedInterfaceNameService(final String host,
        final String interfaceName) {
        AttentionedHostItem interfaceSpeed = screenMapper.selectInterfaceSpeedByInterfaceNameMapper(host,
            interfaceName);
        try {
            if (interfaceSpeed == null) {
                interfaceSpeed = new AttentionedHostItem();
                interfaceSpeed.setHost(host);
                interfaceSpeed.setItemName(interfaceName);
                interfaceSpeed.setValue(0D);
            }
        } catch (Exception e) {
            logger.debug("查询接口速率出错:" + e.getMessage());
            throw new RuntimeException(e);
        }
        return interfaceSpeed;
    }

    /**
     * 丢包率数据
     *
     * @param host
     *            主机
     * @return 丢包率数据
     */
    public AttentionedHostItem selectIcmppingLossService(final String host) {
        AttentionedHostItem icmppingLossItem = screenMapper.selectIcmppingLossMapper(host);
        if (icmppingLossItem == null) {
            icmppingLossItem = new AttentionedHostItem();
            icmppingLossItem.setHost(host);
            icmppingLossItem.setValue(100.0);
        }
        return icmppingLossItem;
    }

    /**
     * 获取特定主机组所属的单个主机
     *
     * @param group
     *            主机组名称
     * @return 单个主机
     */
    public AttentionedHost selectSingleHostByHostGroupNameService(final String group) {
        return screenMapper.selectSingleHostByHostGroupNameMapper(group);
    }

    /**
     * 获取特定主机组所属的全部主机
     *
     * @param group
     *            主机组名称
     * @return 特定主机组所属的全部主机
     */
    public List<HostObject> selectHostByHostGroupNameService(final String group) {
        return screenMapper.selectHostByHostGroupNameMapper(group);
    }

    /**
     * 获取特定主机组所属的全部主机，并包括ip
     *
     * @param group
     *            主机组名称
     * @return 特定主机组所属的全部主机
     */
    public List<AttentionedHost> selectInfoByGroupNameService(final String group) {
        return screenMapper.selectInfoByGroupNameMapper(group);
    }

    /**
     *
     * @return 返回拓补图信息
     */
    public List<TopologicalScreen> listTopologicalService() {
        initUser();
        final List<TopologicalScreen> topologicalInfo = new ArrayList<TopologicalScreen>();
        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();
        MapGetResponse response;
        try {
            response = zabbixApi.map().get(request);
            final List<com.zabbix4j.map.MapGetResponse.Result> rList = response.getResult();
            for (int i = 0; i < rList.size(); i++) {
                final Integer sysmapId = rList.get(i).getSysmapid();
                final String sysmapName = rList.get(i).getName();
                final TopologicalScreen tempTopological = new TopologicalScreen();
                tempTopological.setSysmapId(sysmapId.toString());
                tempTopological.setSysmapName(sysmapName);
                topologicalInfo.add(tempTopological);
            }
        } catch (final ZabbixApiException e) {
            e.printStackTrace();
        }
        return topologicalInfo;
    }

    /**
     *
     * @return 交换机组的主机
     */
    public List<AttentionedHost> selectChangeHostService() {
        return screenMapper.selectChangeHostMapper();
    }

    /**
     *
     * @param name
     *            主机
     * @return 被监控主机的流出流量接口名称
     */
    public List<AttentionedHostItem> selectInterfaceByHostService(final String name) {
        //final List<String> interfaces = new ArrayList<>();
        final List<AttentionedHostItem> attentionedHostItems = screenMapper.selectInterfaceByHostMapper(name);

        final Iterator<AttentionedHostItem> it = attentionedHostItems.iterator();
        while (it.hasNext()) {
            final AttentionedHostItem attentionedHostItem = it.next();
            if (attentionedHostItem.getItemKey().contains("{#")) {
                it.remove();
            }
            final int begin = attentionedHostItem.getItemKey().indexOf("[");
            final int end = attentionedHostItem.getItemKey().indexOf("]");
            final String interfaceName = attentionedHostItem.getItemKey().substring(begin + 1, end); //获取接口名称
            attentionedHostItem.setItemName(interfaceName);
        }
        return attentionedHostItems;
    }

    /**
     *
     * @param name
     *            主机
     * @param interfaceName
     *            接口名称
     * @param interval
     *            时间间隔
     * @return 时间间隔内的流量
     */
    public List<NetWorkTraffic> sumChangeNetWorkTrafficService(final String name, final String interfaceName,
        final Integer interval) {
        Long timeFormat = 0L; //时间格式，一个小时
        if (interval == 1) {
            timeFormat = 60L;
        } else if (interval == 2) {
            timeFormat = 60 * 2L;
        } else if (interval == 5) {
            timeFormat = 60 * 5L;
        } else if (interval == 10) {
            timeFormat = 60 * 10L;
        } else if (interval == 15) {
            timeFormat = 60 * 15L;
        }
        final Long currentTime = new Date().getTime() / 1000; //单位为s
        final Long startTime = currentTime - 60 * 60 * 2;
        final Long size = (long) (120 / interval) + 1; //两小时，获取size
        final List<NetWorkTraffic> netWorkTraffics = new ArrayList<>();
        final Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        calendar.add(Calendar.HOUR_OF_DAY, -2);
        final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        for (int i = 0; i < size; i++) {
            NetWorkTraffic netWorkTraffic;
            if (i == 0) {
                netWorkTraffic = screenMapper.sumChangeNetWorkTrafficMapper(name, interfaceName, startTime - timeFormat,
                    startTime);
            } else {
                netWorkTraffic = screenMapper.sumChangeNetWorkTrafficMapper(name, interfaceName,
                    startTime + (i - 1) * timeFormat, startTime + i * timeFormat);
            }

            if (netWorkTraffic == null) {
                netWorkTraffic = new NetWorkTraffic();
                netWorkTraffic.setHost(name);
                netWorkTraffic.setValue(0L);
            }
            final Date date = calendar.getTime();
            final String s = sdf.format(date);
            calendar.add(Calendar.MINUTE, interval);
            netWorkTraffic.setTime(s);
            netWorkTraffics.add(netWorkTraffic);
        }
        return netWorkTraffics;
    }

    /**
     *
     * @param name
     *            主机
     * @param interfaceName
     *            接口名称
     * @param interval
     *            时间间隔
     * @return 时间间隔内的流量，单个数据
     */
    public NetWorkTraffic sumSingleChangeNetWorkTrafficService(final String name, final String interfaceName,
        final Integer interval) {
        final Long currentTime = new Date().getTime() / 1000;
        final Long timeFormat = 60L;
        NetWorkTraffic netWorkTraffic = screenMapper.sumChangeNetWorkTrafficMapper(name, interfaceName,
            currentTime - interval * timeFormat, currentTime);
        if (netWorkTraffic == null) {
            netWorkTraffic = new NetWorkTraffic();
            netWorkTraffic.setHost(name);
            netWorkTraffic.setValue(0L);
        }
        final Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        final Date date = calendar.getTime();
        final String s = sdf.format(date);
        netWorkTraffic.setTime(s);
        return netWorkTraffic;
    }

    /**
     *
     * @return 返回用户刷新时间
     */
    public Integer findUserRefresh(final Integer userId) {
        final Integer time = screenMapper.findUserRefreshByUserId(userId);
        return time;
    }
}
