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

package com.cesgroup.cesmonitor.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

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

import com.cesgroup.cesmonitor.bean.QuickAccess;
import com.cesgroup.cesmonitor.bean.QuickAccessGraph;
import com.cesgroup.cesmonitor.bean.QuickAccessGraphList;
import com.cesgroup.cesmonitor.common.Util;
import com.cesgroup.cesmonitor.dao.QuickAccessMapper;
import com.zabbix4j.ZabbixApi;
import com.zabbix4j.ZabbixApiException;
import com.zabbix4j.ZabbixApiParamter;
import com.zabbix4j.graph.GraphGetRequest;
import com.zabbix4j.graph.GraphGetResponse;
import com.zabbix4j.graph.GraphObject;
import com.zabbix4j.host.HostObject;
import com.zabbix4j.hostgroup.HostgroupGetRequest;
import com.zabbix4j.hostgroup.HostgroupGetResponse;

/**
 * 上海中信信息发展股份有限公司;
 * 创建时间:2018年1月22日;
 *
 * @author user
 * @version 1.0.0
 */
@Service
public class QuickAccessService {

    @Autowired
    private QuickAccessMapper quickAccessMapper;

    /**
     * @param hostId
     *            主机id
     * @return
     *         图形
     */
    public List<GraphObject> getGraphByHostId(final Integer hostId) {
        ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
        GraphGetRequest request = new GraphGetRequest();
        GraphGetRequest.Params params = request.getParams();

        params.addHostId(hostId);
        params.setSelectGroups(ZabbixApiParamter.QUERY.extend.name());
        params.setSelectHosts(ZabbixApiParamter.QUERY.extend.name());
        GraphGetResponse response = null;
        try {
            response = zabbixApi.graph().get(request);
        } catch (ZabbixApiException e) {
            e.printStackTrace();

        }
        List<com.zabbix4j.graph.GraphObject> newlist = new ArrayList<>();
        /* if (null == response) {
            return newlist;
        }*/
        if (null != response) {
            for (com.zabbix4j.graph.GraphObject rs : response.getResult()) {
                newlist.add(rs);
            }
        }
        return newlist;
    }

    /**
     * @return
     *         用户群组
     */
    public List<String> findUsrGroup() {
        return quickAccessMapper.findUsrGroup();
    }

    /**
     * @param usrgrpid
     *            用户群组id
     * @return
     *         群组
     */
    public List<String> findGroupByUsrgroup(final String usrgrpid) {
        return quickAccessMapper.findNameByUsrgrpid(usrgrpid);
    }

    /**
     * @param usrgrpid
     *            用户群组id
     * @param groupid
     *            群组id
     * @return
     *         主机
     */
    public List<String> findHostByGroupId(final String usrgrpid, final String groupid) {
        return quickAccessMapper.findHostByGroupId(usrgrpid, groupid);
    }

    /**
     * @param usrgrpid
     *            用户群组id
     * @param groupid
     *            群组id
     * @param hostId
     *            主机id
     * @return
     *         图形
     */
    public List<String> getGraphByHostId2(final String usrgrpid, final String groupid, final String hostId) {
        return quickAccessMapper.getGraphByHostId2(usrgrpid, groupid, hostId);
    }

    /**
     *
     * @return 返回主机组
     */
    public List<HostgroupGetResponse.Result> listHostGroupsWithHosts() {
        try {
            ZabbixApi zabbixApi = Util.getLoginUser().getZabbixApi();
            HostgroupGetRequest request = new HostgroupGetRequest();
            HostgroupGetRequest.Params params = request.getParams();
            params.setSelectHosts(ZabbixApiParamter.QUERY.extend.name());
            params.setWith_hosts_and_templates(true);
            HostgroupGetResponse response = zabbixApi.hostgroup().get(request);
            List<com.zabbix4j.hostgroup.HostgroupGetResponse.Result> newlist = new ArrayList<>();
            for (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(quickAccessMapper.findHostStatus(obj.getHostid()));
                }
            }
            return newlist;
        } catch (ZabbixApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param fastGroupName
     *            快速访问群组名
     * @param userId
     *            用户id
     * @param graphName
     *            图形名
     * @param groupId
     *            群组id
     * @param hostId
     *            主机id
     * @param graphId
     *            图形id
     * @return
     *         快速访问
     */
    public List<String> saveQuickAccess(final String fastGroupName, final String userId, final String graphName,
        final int groupId, final int hostId,
        final int graphId) {
        String myresult = "";
        List<String> result2 = new ArrayList<String>();
        List<String> usrGrpIds = quickAccessMapper.findUsrGrpByUserId(userId);
        try {
            String fastGroupId;
            String latFastGroupId = quickAccessMapper.findFastGroupByName(fastGroupName);
            if (null != latFastGroupId) {
                latFastGroupId = latFastGroupId.toString().replace("-", "");
            }
            if (null == latFastGroupId || "".equals(latFastGroupId)) {
                fastGroupId = UUID.randomUUID().toString();
                fastGroupId = fastGroupId.toString().replace("-", "");
                quickAccessMapper.addFastGroup(fastGroupId, fastGroupName);
                for (int i = 0; i < usrGrpIds.size(); i++) {
                    String usrGroupId = usrGrpIds.get(i);
                    quickAccessMapper.addFastGroupUsrGroup(fastGroupId, usrGroupId);
                }
            } else {
                fastGroupId = latFastGroupId;
            }
            String fastGroupGraphId = UUID.randomUUID().toString();
            fastGroupGraphId = fastGroupGraphId.toString().replace("-", "");
            myresult = fastGroupId;
            result2.add(myresult);
            quickAccessMapper.addFastGroupGraph(fastGroupGraphId, fastGroupId, graphName, groupId, hostId, graphId);
            System.out.println(myresult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result2;
    }

    /**
     * @param fastGroupId
     *            群组id
     *
     * @return
     *         删除快速访问
     */
    public int deleteQuickAccess(final String fastGroupId) {
        int success1 = -1;
        int success2 = -1;
        int success3 = -1;
        try {
            success1 = quickAccessMapper.deleteFastGroup(fastGroupId);
            success2 = quickAccessMapper.deleteFastGroupUsrGroup(fastGroupId);
            success3 = quickAccessMapper.deleteFastGroupGraph(fastGroupId);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return success1 + success2 + success3;
    }

    /**
     * @param fastGroupGraphId
     *            快速访问群组图片id
     * @return
     *         删除
     */
    public int deleteQuickAccessGraph(final String fastGroupGraphId) {
        String fastGroupId = quickAccessMapper.findFastGroupIdByFastGroupGraphId(fastGroupGraphId);
        ArrayList<String> fastGroupGraphs = quickAccessMapper.findFastGroupGraphsByFastGroupId(fastGroupId);
        int returndata;
        if (fastGroupGraphs.size() == 1) {
            quickAccessMapper.deleteFastGroup(fastGroupId);
            quickAccessMapper.deleteFastGroupUsrGroup(fastGroupId);
            returndata = quickAccessMapper.deleteQuickAccessGraph(fastGroupGraphId);
        } else {
            returndata = quickAccessMapper.deleteQuickAccessGraph(fastGroupGraphId);
        }

        return returndata;
    }

    /**
     * 校验是否创建过该图形名
     *
     * @param fastGroupName
     *            快速访问群组名
     * @param usrGroupId
     *            用户群组id
     * @param graphName
     *            图形名
     * @param groupId
     *            群组id
     * @param hostId
     *            主机id
     * @param graphId
     *            图形id
     * @return
     *         校验是否创建过该图形名
     */
    public boolean validateQuickAccess(final String fastGroupName, final String usrGroupId, final String graphName,
        final int groupId,
        final int hostId, final int graphId) {
        String validateResult = quickAccessMapper.findFastGroupGraphBySelfdefineName(fastGroupName);
        if (null == validateResult || "".equals(validateResult)) {
            return true;
        }
        return false;
    }

    /**
     * 校验是否创建过该图形组
     *
     * @param fastGroupName
     *            快速群组名
     * @return
     *         校验是否创建过该图形组
     */
    public boolean validateQuickAccessGroupName(final String fastGroupName) {
        String validateResult = quickAccessMapper.findFastGroupByName(fastGroupName);
        if (null == validateResult || "".equals(validateResult)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param userId
     *            用户id
     * @return
     *         快速访问组
     */
    public List<QuickAccessGraphList> findFastGroupGraphByUserId(final String userId) {
        List<QuickAccessGraph> fastGroupGraphs;
        LoginUser user = Util.getLoginUser();
        if (user.isSuperAdmin()) {
            // 超级管理员返回所有快速访问组
            fastGroupGraphs = quickAccessMapper.superAdminfindFastGroupGraphByUserId(userId);
        } else {
            fastGroupGraphs = quickAccessMapper.findFastGroupGraphByUserId(userId);
        }

        Set<String> fastGroupIdSet = new HashSet<String>();
        String fastGroupGraphId = null;
        List<QuickAccessGraphList> QuickAccessGraphList = new ArrayList<QuickAccessGraphList>();
        for (int i = 0; i < fastGroupGraphs.size(); i++) {
            fastGroupGraphId = fastGroupGraphs.get(i).getGroupId();
            fastGroupIdSet.add(fastGroupGraphId);//?
        }
        for (String groupId : fastGroupIdSet) {
            int i = 0;
            ArrayList<String> fastGroupGraphsByGroupId;
            String fastGroupNameByGroupId;
            if (user.isSuperAdmin()) {
                // 超级管理员返回所有快速访问组
                fastGroupGraphsByGroupId = quickAccessMapper.findFastGroupGraphsByFastGroupId(groupId);
                fastGroupNameByGroupId = quickAccessMapper.findFastGroupNameByGroupId(groupId);
            } else {
                fastGroupGraphsByGroupId = quickAccessMapper.findFastGroupGraphsByFastGroupIdandUser(groupId, userId);
                fastGroupNameByGroupId = quickAccessMapper.findFastGroupNameByGroupIdandUser(groupId);
            }

            QuickAccessGraphList qag = new QuickAccessGraphList();
            qag.setGroupId(groupId);
            qag.setGroupName(fastGroupNameByGroupId);
            qag.setGraphName(fastGroupGraphsByGroupId);
            QuickAccessGraphList.add(i, qag);
            i++;
        }
        return QuickAccessGraphList;
    }

    /**
     * @param userId
     *            用户id
     * @return
     *         用户群组
     */
    public List<String> findUsrGrpByUserId(final String userId) {
        List<String> UsrGrps = quickAccessMapper.findUsrGrpByUserId(userId);
        return UsrGrps;
    }

    /**
     * @param fastGroupId
     *            快速访问组id
     * @return
     *         图形
     */
    public List<QuickAccess> getGraphsByFastGroupId(final String fastGroupId) {
        LoginUser user = Util.getLoginUser();
        Integer userId = user.getUserid();
        List<QuickAccess> myGraphs;
        if (user.isSuperAdmin()) {
            myGraphs = quickAccessMapper.getGraphsByFastGroupId(fastGroupId);
        } else {
            myGraphs = quickAccessMapper.getGraphsByFastGroupIdandUserId(fastGroupId, userId);
        }

        return myGraphs;
    }

    /**
     * @param fastGroupName
     *            快速访问组名
     * @param usrGroupId
     *            用户群组id
     * @param graphName
     *            图形名
     * @param groupId
     *            群组id
     * @param hostId
     *            主机id
     * @param graphId
     *            图形id
     * @return
     *         保存快速群组
     */
    public List<String> saveQuickGroup(final String fastGroupName, final String usrGroupId, final String graphName,
        final int groupId,
        final int hostId, final int graphId) {

        return null;
    }

    /**
     * @param fastGroupId
     *            快速访问组id
     * @param fastGroupName
     *            快速访问组名
     * @return
     *         更新群组
     *
     */
    public Integer updateGroup(final String fastGroupId, final String fastGroupName) {

        return quickAccessMapper.updateFastGroup(fastGroupId, fastGroupName);
    }

    /**
     * @param fastGroupGraphIds
     *            快速访问组图形ids
     * @return
     *         删除群组
     */
    public int deleteByFastGroupId(final String fastGroupGraphIds) {
        int success1 = -1;
        int success2 = -1;
        int success3 = -1;
        String[] listfastGroupGraphIds = fastGroupGraphIds.split(",");

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

            try {
                success1 = quickAccessMapper.deleteFastGroup(listfastGroupGraphIds[i]);
                success2 = quickAccessMapper.deleteFastGroupUsrGroup(listfastGroupGraphIds[i]);
                success3 = quickAccessMapper.deleteFastGroupGraph(listfastGroupGraphIds[i]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return success1 + success2 + success3;
    }

    /**
     * @param graphArray
     *            图形组
     * @return
     *         快速访问组
     *
     */
    public int saveQuickAccessList(String graphArray) {

        int fastGroupNamePos = graphArray.indexOf("fastGroupName"); //为null校验
        String fastGroupNamePosString = graphArray.substring(fastGroupNamePos);
        int endFastGroupNamePos = fastGroupNamePosString.indexOf("}");
        String fastGroupName = fastGroupNamePosString.substring(16, endFastGroupNamePos);
        fastGroupName = fastGroupName.replace("\"", "");
        String fastGroupId = UUID.randomUUID().toString();
        fastGroupId = fastGroupId.toString().replace("-", "");
        graphArray = graphArray.replace("\"", "");
        String[] myGraphArray = graphArray.split("},");
        String userId = null;
        String[] myGraph1 = myGraphArray[0].split(",");
        List<String> graphList1 = new ArrayList<String>();
        for (int j = 0; j < myGraph1.length; j++) {
            int startIndex = myGraph1[j].indexOf(":");
            String graph = myGraph1[j].substring(startIndex + 1);
            graph = graph.trim();
            graphList1.add(graph);
        }
        for (int m = 0; m < graphList1.size(); m++) {
            // fastGroupName = graphList1.get(1);
            userId = graphList1.get(1);
            graphList1.clear();
        }

        List<String> usrGrpIds = quickAccessMapper.findUsrGrpByUserId(userId);
        try {
            String latFastGroupId = quickAccessMapper.findFastGroupByName(fastGroupName);
            if (null != latFastGroupId) {
                latFastGroupId = latFastGroupId.toString().replace("-", "");
            }
            if (null == latFastGroupId || "".equals(latFastGroupId)) {
                fastGroupId = UUID.randomUUID().toString();
                fastGroupId = fastGroupId.toString().replace("-", "");
                quickAccessMapper.addFastGroup(fastGroupId, fastGroupName);
                for (int i = 0; i < usrGrpIds.size(); i++) {
                    String usrGroupId = usrGrpIds.get(i);
                    quickAccessMapper.addFastGroupUsrGroup(fastGroupId, usrGroupId);
                }
            } else {
                fastGroupId = latFastGroupId;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        graphArray = graphArray.replace("\"", "");
        myGraphArray = graphArray.split("},");
        for (int i = 0; i < myGraphArray.length - 1; i++) {
            String[] myGraph = myGraphArray[i].split(",");
            String fastGroupGraphId;
            String graphName;
            int graphId;
            int hostId;
            int groupId;
            List<String> graphList = new ArrayList<String>();
            for (int j = 0; j < myGraph.length; j++) {
                int startIndex = myGraph[j].indexOf(":");
                String graph = myGraph[j].substring(startIndex + 1);
                graph = graph.trim();
                if (graph.contains("}]")) {
                    int start = graph.indexOf("}]");
                    graph = graph.substring(0, start);
                }
                graphList.add(graph);
            }
            for (int m = 0; m < graphList.size(); m++) {
                fastGroupGraphId = graphList.get(0);
                graphName = graphList.get(2);

                groupId = Integer.parseInt(graphList.get(3));
                hostId = Integer.parseInt(graphList.get(4));
                graphId = Integer.parseInt(graphList.get(5));
                int a = quickAccessMapper.addFastGroupGraph(fastGroupGraphId, fastGroupId, graphName, groupId, hostId,
                    graphId);
                graphList.clear();
                System.out.println(a);
            }
        }
        return 0;
    }

    /**
     * @param fastGroupGraphIds
     *            快速访问组图形id
     * @return
     *         删除快速访问图形列表
     */
    public int deleteQuickAccessGraphList(String fastGroupGraphIds) {

        fastGroupGraphIds = fastGroupGraphIds.replace("\"", "");
        String[] myGraphArray = fastGroupGraphIds.split("},");
        List<String> graphList = new ArrayList<String>();
        int returndata = 0;
        for (int j = 0; j < myGraphArray.length; j++) {
            int startIndex = myGraphArray[j].indexOf(":");
            String graph = myGraphArray[j].substring(startIndex + 1);
            graph = graph.trim();
            if (graph.contains("}]")) {
                int start = graph.indexOf("}]");
                graph = graph.substring(0, start);
            }
            graphList.add(graph);
        }

        for (int i = 0; i < graphList.size(); i++) {
            String deleteId = graphList.get(i);

            String fastGroupId = quickAccessMapper.findFastGroupIdByFastGroupGraphId(deleteId);
            ArrayList<String> fastGroupGraphs = quickAccessMapper.findFastGroupGraphsByFastGroupId(fastGroupId);

            if (fastGroupGraphs.size() == 1) {
                quickAccessMapper.deleteFastGroup(fastGroupId);
                quickAccessMapper.deleteFastGroupUsrGroup(fastGroupId);
                returndata = quickAccessMapper.deleteQuickAccessGraph(deleteId);
            } else {
                returndata = quickAccessMapper.deleteQuickAccessGraph(deleteId);
            }

        }
        return returndata;
    }

}
