package com.cesgroup.cesmonitor.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cesgroup.cesmonitor.bean.AlarmInfo;
import com.cesgroup.cesmonitor.common.Util;
import com.cesgroup.cesmonitor.dao.AlarmListMapper;
import com.zabbix4j.ZabbixApi;
import com.zabbix4j.ZabbixApiException;
import com.zabbix4j.ZabbixApiParamter;
import com.zabbix4j.host.HostGetRequest;
import com.zabbix4j.host.HostGetResponse;
import com.zabbix4j.trigger.TriggerGetRequest;
import com.zabbix4j.trigger.TriggerGetResponse;
import com.zabbix4j.trigger.TriggerGetResponse.Result;

@Service("alarmListService")
public class AlarmListService {

    @Autowired
    AlarmListMapper alarmListMapper;


    /**
     * 查找所有事件信息
     *
     * @param groupId
     *            群组Id
     * @param hostId
     *            主机Id
     * @param objectId
     *            触发器Id
     * @param status
     *            时间状态
     * @param warningLevel
     *            事件严重性
     * @param startTime
     *            开始时间
     * @param endTime
     *            结束时间
     * @return
     *         所有事件告警信息列表
     */
    public List<AlarmInfo> findAllAlarmEventInfo(final Integer groupId, final Integer hostId, final Integer objectId,
        final Integer status, final Integer warningLevel, final Long startTime, final Long endTime) {

        String groupIdS;
        String hostIdS;
        String objectIdS;

        if (groupId != -1) {
            groupIdS = "g.groupid ='" + groupId + "'";
        } else {
            groupIdS = "1=1";
        }
        if (hostId != -1) {
            hostIdS = "h.hostid ='" + hostId + "'";
        } else {
            hostIdS = "1=1";
        }
        if (objectId != -1) {
            objectIdS = "e.objectid ='" + objectId + "'";
        } else {
            objectIdS = "1=1";
        }

        final List<AlarmInfo> list1 = alarmListMapper.filterAlarmInfo(groupIdS, hostIdS, objectIdS);


        final List<AlarmInfo> list2 = new ArrayList<>();
        if (list1.get(0).getStatus() == 1) {
            final Long tempEndTime = new Date().getTime() / 1000;
            list1.get(0).setSubClock(Util.getDiff(tempEndTime - list1.get(0).getStartClock()));
            list2.add(list1.get(0));
        }
        for (int i = 0; i < list1.size() - 1; i++) {
            final AlarmInfo upper = list1.get(i);
            final AlarmInfo lower = list1.get(i + 1);

            if (upper.getObjectId() == lower.getObjectId()
                && upper.getStatus() == 0 && lower.getStatus() == 1) {
                lower.setStatus(0);
                lower.setSubClock(Util.getDiff(upper.getStartClock() - lower.getStartClock()));
                list2.add(lower);
            } else if (upper.getObjectId() != lower.getObjectId()
                && lower.getStatus() == 1) {
                final Long tempEndTime = new Date().getTime() / 1000;
                lower.setSubClock(Util.getDiff(tempEndTime - lower.getStartClock()));
                list2.add(lower);
            }
        }

        final Iterator<AlarmInfo> listIterator = list2.iterator();
        while (listIterator.hasNext()) {
            final AlarmInfo info = listIterator.next();
            if (status != -1) {
                if (!info.getStatus().equals(status)) {
                    listIterator.remove();
                    continue;
                }
            }
            if (warningLevel != -1) {
                if (!info.getWarningLevel().equals(warningLevel)) {
                    listIterator.remove();
                    continue;
                }
            }
            if (startTime != (long) 0 && endTime != (long) 0) {
                if (info.getStartClock() < startTime || info.getStartClock() > endTime) {
                    listIterator.remove();
                    continue;
                }
            }
        }

        Collections.sort(list2);

        return list2;

    }

    /**
     * 分页查找所有事件信息
     *
     * @param groupId
     *            群组Id
     * @param hostId
     *            主机Id
     * @param objectId
     *            触发器Id
     * @param status
     *            时间状态
     * @param warningLevel
     *            事件严重性
     * @param startTime
     *            开始时间
     * @param endTime
     *            结束时间
     * @return
     *         当前页事件告警信息列表
     */
    public List<AlarmInfo> findAlarmEventInfo(final Integer groupId, final Integer hostId, final Integer objectId,
        final Integer status, final Integer warningLevel, final Long startTime, final Long endTime,
        final Integer pageNum) {
        List<AlarmInfo> list2 = new ArrayList<>();
        list2 = findAllAlarmEventInfo(groupId, hostId, objectId, status, warningLevel, startTime, endTime);
        Integer totalRecord = 0;
        if (list2 != null) {
            totalRecord = list2.size();
        }
        final List<AlarmInfo> list = new ArrayList<>();
        for (int i = 50 * (pageNum - 1); i < 50 * pageNum && i < list2.size(); i++) {
            list.add(list2.get(i));
        }

        list.get(0).setTotalRecord(totalRecord);
        try {

            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();

            final Map<Integer, String> dMap = new HashMap<Integer, String>();
            final Set<Integer> objSet = new HashSet<>();
            for (int i = 0; i < list.size(); i++) {
                objSet.add(list.get(i).getObjectId());
            }
            final Iterator<Integer> it = objSet.iterator();
            while (it.hasNext()) {
                final Integer objId = it.next();
                params.addTriggerid(objId);
                //                    response = zabbixApi.trigger().get(request);
                //                    Result rs = response.getResult().get(0);
                //                    dMap.put(objId, rs.getDescription());
                //                    params.getTriggerids().clear();
            }
            response = zabbixApi.trigger().get(request);
            final List<Result> rs = response.getResult();
            for (final Result result : rs) {
                dMap.put(result.getTriggerid(), result.getDescription());
            }

            for (int i = 0; i < list.size(); i++) {
                final String description = dMap.get(list.get(i).getObjectId());
                list.get(i).setDescription(description);
            }
        } catch (final ZabbixApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;

    }

    /**
     * 查找所有触发器
     *
     * @return
     *         所有触发器
     */
    public List<TriggerGetResponse.Result> getAllTriggers(final Integer hostId) {
        List<TriggerGetResponse.Result> list = new ArrayList<>();
        try {
            final TriggerGetRequest request = new TriggerGetRequest();
            final TriggerGetRequest.Params params = request.getParams();
            params.setExpandDescription(true);
            params.setExpandExpression(true);
            if (hostId != -1) {
                params.addHostid(hostId);
            }
            final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
            TriggerGetResponse response;
            response = zabbixApi.trigger().get(request);
            list = response.getResult();
        } catch (final ZabbixApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 根据群组查找触发器
     *
     * @param groupId
     *            群组Id
     * @return
     *         某个群组的触发器
     */
    public List<TriggerGetResponse.Result> getTriggersByGroup(final Integer groupId) {
        List<TriggerGetResponse.Result> list = new ArrayList<>();
        try {
            final TriggerGetRequest request = new TriggerGetRequest();
            final TriggerGetRequest.Params params = request.getParams();
            params.setExpandDescription(true);
            params.setExpandExpression(true);
            params.addGroupid(groupId);
            final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
            TriggerGetResponse response;
            response = zabbixApi.trigger().get(request);
            list = response.getResult();
        } catch (final ZabbixApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

    public HostGetResponse.Result getHostByTriggerId(final Integer triggerId) {
        HostGetResponse.Result result = null;
        try {
            final HostGetRequest request = new HostGetRequest();
            final HostGetRequest.Params params = request.getParams();
            final ArrayList<Integer> triggerids = new ArrayList<Integer>();
            triggerids.add(triggerId);
            params.setTriggerids(triggerids);
            params.setSelectGroups(ZabbixApiParamter.QUERY.extend.name());
            final ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
            HostGetResponse response;
            response = zabbixApi.host().get(request);
            result = response.getResult().get(0);
        } catch (final ZabbixApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

}
