# encoding=utf8

import json
from django.db import connections
from django.shortcuts import render
from common.mymako import render_mako_context, render_json
import time
# import pymssql
import datetime
from event_analysis.models import *
from django.http import HttpResponseRedirect,StreamingHttpResponse,FileResponse
from django.shortcuts import HttpResponse
from django.core.paginator import Paginator
import xlwt
import os
import sys
from blueking.component.shortcuts import get_client_by_request
import requests
from conf.default import APP_ID, APP_TOKEN
from biz_utils import get_app_by_user
from account.decorators import login_exempt

reload(sys)
sys.setdefaultencoding('utf8')

def eventmanagement_display(request):
    return render_mako_context(request, '/event_analysis/eventmanagement_display.html')
def event_edit(request):
    return render_mako_context(request, '/event_analysis/event_edit.html')
def error_alarm(request):
    return render_mako_context(request, '/event_analysis/error_alarm.html')
def alarm_count(request):
    return render_mako_context(request, '/event_analysis/alarm_count.html')
def alarm_edit(request):
    return render_mako_context(request, '/event_analysis/alarm_edit.html')


# 事件多条件查询
def condition_search(request):
    req = json.loads(request.body)
    req = req["data"]

    # 先查出所有的事件
    eventList = EventInfo.objects.all().order_by('-event_happened_time')

    # 用户组
    # gruop_data = requests.get('http://192.168.1.246:8001/webapi/relationshipInstances/172?pageNum=1&pageSize=100')
    # gruop_data = gruop_data.text
    # gruop_data = eval(gruop_data)


    # 按事件编号查询
    if req['event_number']:
        eventList = eventList.filter(event_number__contains=req['event_number'])

    # 事件优先级
    if req['priority']:
        eventList = eventList.filter(event_priority=req['priority'])

    # 是否查询服务器硬件事件，以负责该事件的人名来过滤
    namelist = ['徐文', '刘骏']
    if req['hardware'] is True:
        eventList = eventList.filter(processing_person__in=namelist)
    else:
        eventList = eventList.exclude(processing_person__in=namelist)

    # 事件发生时间
    if req['event_hap_time'] == '' or req['event_hap_time'] == None:
        pass
    else:
        hptime_choose = req.get("event_hap_time")
        startTime = hptime_choose[0]
        startTime = datetime.datetime.strptime(startTime[0:10], "%Y-%m-%d")
        startTime = (startTime + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
        endTime = hptime_choose[1]
        endTime = datetime.datetime.strptime(endTime[0:10], "%Y-%m-%d")
        endTime = (endTime + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
        eventList = eventList.filter(event_happened_time__gte=startTime).filter(event_happened_time__lte=endTime)

    # 事件状态，已分析
    if req['event_state']:
        eventList = eventList.filter(event_analysis_state=req['event_state'])

    # 事件一级分类
    if req['event_first_cat']:
        eventList = eventList.filter(event_first_category=req['event_first_cat'])

    # 处理人
    if req['relate_me']:
        eventList = eventList.filter(processing_person=req['relate_me'])

    # 事件标签
    if req['event_label']:
        newEventList = []
        labelEvent = EventLabel.objects.all()
        if labelEvent:
            for i in req['event_label']:
                    for j in labelEvent:
                        for z in eval(j.event_label):
                            if i == z:
                                thisEvent = eventList.filter(event_number=j.event_number)
                                if thisEvent:
                                    newEventList.append(thisEvent[0])
                                    break
            eventList = []
            for i in newEventList:
                if i not in eventList:
                    eventList.append(i)
        else:
            eventList = []


    # 全局搜索(摘要、故障系统名称、受影响系统名称、现象)
    if req['all_fields']:
        special1_eventList = eventList.filter(event_summary__contains=req['all_fields'])
        special2_eventList = eventList.filter(failure_sys_name__contains=req['all_fields'])
        special3_eventList = eventList.filter(influenced_sys_name__contains=req['all_fields'])
        special4_eventList = eventList.filter(event_phenomenon__contains=req['all_fields'])
        total_eventList = special1_eventList | special2_eventList | special3_eventList | special4_eventList
        eventList = []
        for i in total_eventList:
            if i not in eventList:
                eventList.append(i)

    if request.body == "":
        current_page = 1
        page_size = 10
    else:
        req = json.loads(request.body)
        current_page = req.get("currentPage", 1)
        page_size = req.get("pageSize", 10)
    event_page = Paginator(eventList, page_size)
    event_list = event_page.page(current_page).object_list

    result_list = []
    if event_list:
        for eventinfo_result in event_list:
            data = {
                "event_number": eventinfo_result.event_number,
                "summary": eventinfo_result.event_summary,
                "priority": eventinfo_result.event_priority,
                "assignee": eventinfo_result.processing_person,
                "analy_state": eventinfo_result.event_analysis_state,
                # "data_src": 1 if eventinfo_result.data_src == u"同步" else 0,
                "data_src": 0,
                "update_time": eventinfo_result.event_happened_time.strftime('%Y-%m-%d %H:%M:%S')
            }
            result_list.append(data)

        return render_json(
            {
                "result": True,
                "message": u"查询数据成功",
                "code": 0,
                "results": {'results': result_list, 'count': event_page.count, 'currentPage': current_page},
            }
        )
    else:
        return render_json(
            {
                "result": True,
                "code": 0,
                "message": u"未找到匹配数据",
                "results": {},
            }

        )


# 获取当前登录用户中文名
def getuser(request):
    client = get_client_by_request(request)
    bk_token = request.COOKIES.get('bk_token')
    client.set_bk_api_ver('v2')
    parse = {
        'bk_token': bk_token,
        'bk_app_code': APP_ID,
        'bk_app_secret': APP_TOKEN,
    }
    result = client.bk_login.get_user(parse)
    login_person = result['data']['chname']
    return render_json({
        "result": True,
        "message": u"未分析情况的数据查询成功",
        "code": 0,
        "data": login_person
    })


# 事件新建
def new_create(request):
    try:
        re = json.loads(request.body)
        req = re["data"]
        res = re["alarmList"]

        # 获取当前登录用户的中文名
        client = get_client_by_request(request)
        bk_token = request.COOKIES.get('bk_token')
        client.set_bk_api_ver('v2')
        parse = {'bk_token': bk_token, 'bk_app_code': APP_ID, 'bk_app_secret': APP_TOKEN}
        result = client.bk_login.get_user(parse)
        login_person = result['data']['chname']

        '''
        urgencymeasure_dict--故障分析-自动化相关
        urgency_info：应急方案，auto_sys：系统所属名称，script_name：自动化方案
        urgency_auto_info：自动化完成情况单选框
        notbkautoinfo、cantautoinfo、notautoyetinfo：同属于autoinfo
        '''
        urgencymeasure_dict = req.get("urgency")
        # 判断是否写了其他自动化信息
        if urgencymeasure_dict.get("notbkautoinfo"):
            auto_info = {'notbkautoinfo': urgencymeasure_dict.get("notbkautoinfo")}
        elif urgencymeasure_dict.get("cantautoinfo"):
            auto_info = {'cantautoinfo': urgencymeasure_dict.get("cantautoinfo")}
        elif urgencymeasure_dict.get("notautoyetinfo"):
            auto_info = {'notautoyet': urgencymeasure_dict.get("notautoyetinfo")}
        else:
            auto_info = ''
        urgencymeasure_info = urgencymeasure_dict.get("urgency_info")
        urgencymeasure_autoinfo = urgencymeasure_dict.get("urgency_auto_info")
        sysname = urgencymeasure_dict.get("auto_sys")
        scriptname = urgencymeasure_dict.get("script_name")

        '''
        failuremeasure_dict--改进措施
        root_analysis:根因分析，solve_measure：解决方案措施
        '''
        failuremeasure_dict = req.get("failuremeasure")
        root_analysis = failuremeasure_dict.get("root_analysis")
        solve_measure = failuremeasure_dict.get("solve_measure")

        '''
        failureanalysis_dict--故障表象、机器与告警
        failure_surface：故障表象，
        '''
        failureanalysis_dict = req.get("failure_analysis")
        failure_surface = failureanalysis_dict.get("failure_surface")
        # 现为机器ip
        failure_actual_phenomenon = failureanalysis_dict.get('actual_phenomenon')
        related_alarm = failureanalysis_dict.get("related_alarm_info")
        monitor_src = str(res)
        deal_case = req.get("deal_processing") # 处理过程
        if failureanalysis_dict.get("notbkalarminfo"):
            monitor_info = {'notbkalarminfo': failureanalysis_dict.get("notbkalarminfo")}
        elif failureanalysis_dict.get("havemonitorinfo"):
            monitor_info = {'havemonitorinfo': failureanalysis_dict.get("havemonitorinfo")}
        elif failureanalysis_dict.get("notmonitorinfo"):
            monitor_info = {'notmonitorinfo': failureanalysis_dict.get("notmonitorinfo")}
        else:
            monitor_info = ''

        solve_detail = failureanalysis_dict.get("solve_detail")

        '''
        四个时间
        '''
        user_reporting_time = req.get("user_reporting_time")
        user_reporting_time = str(user_reporting_time)
        user_reporting_time = user_reporting_time.replace('T', ' ')
        user_reporting_time = user_reporting_time[0:-5]
        if user_reporting_time:
            user_reporting_time = datetime.datetime.strptime(user_reporting_time, "%Y-%m-%d %H:%M:%S")
            user_reporting_time = (user_reporting_time + datetime.timedelta(hours=16)).strftime("%Y-%m-%d %H:%M:%S")
        event_happened_time = req.get("event_happened_time")
        event_happened_time = str(event_happened_time)
        event_happened_time = event_happened_time.replace('T', ' ')
        event_happened_time = event_happened_time[0:-5]
        if event_happened_time:
            event_happened_time = datetime.datetime.strptime(event_happened_time, "%Y-%m-%d %H:%M:%S")
            hapTime = (event_happened_time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
            event_happened_time = (event_happened_time + datetime.timedelta(hours=16)).strftime("%Y-%m-%d %H:%M:%S")
            hapTime = hapTime.replace('-', '')
            hapTime = hapTime.replace(' ', '')
            hapTime = hapTime.replace(':', '')
            event_number = request.user.username + hapTime
        accept_time = req.get("event_accept_time")
        accept_time = str(accept_time)
        accept_time = accept_time.replace('T', ' ')
        accept_time = accept_time[0:-5]
        if accept_time:
            accept_time = datetime.datetime.strptime(accept_time, "%Y-%m-%d %H:%M:%S")
            accept_time = (accept_time + datetime.timedelta(hours=16)).strftime("%Y-%m-%d %H:%M:%S")
        failure_recovery_time = req.get("failure_recovery_time")
        failure_recovery_time = str(failure_recovery_time)
        failure_recovery_time = failure_recovery_time.replace('T', ' ')
        failure_recovery_time = failure_recovery_time[0:-5]
        if failure_recovery_time:
            failure_recovery_time = datetime.datetime.strptime(failure_recovery_time, "%Y-%m-%d %H:%M:%S")
            failure_recovery_time = (failure_recovery_time + datetime.timedelta(hours=16)).strftime("%Y-%m-%d %H:%M:%S")

        '''
        其他字段
        '''
        failure_sys_name = req.get("failure_sys_name") # 故障系统，str
        inflenced_sys_name = req.get("influenced_sys_name") # 受影响系统，list，可多选
        event_type = req.get("event_type") # 事件类型，str
        phenomenon = req.get("phenomenon") # 现象，str
        event_summary = req.get("event_summary") # 摘要
        change_number = req.get("change_number") # 紧急变更单号
        first_category = req.get("first_category") # 一级分类
        second_category = req.get("second_category") # 二级分类
        third_category = req.get("third_category") # 三级分类
        impact_degree = req.get("impact_degree") # 影响度
        urgency_degree = req.get("urgency_degree") # 紧急度
        priority = req.get("priority") # 优先级
        report_source = req.get("report_source") # 报告来源
        dealer = req.get("dealer")
        failure_cause_preliminary_analysis = req.get("failure_cause_preliminary_analysis") # 故障原因初步分析

        # 判断必填字段和四个时间点的先后顺序
        if not all([event_summary, priority, event_happened_time]):
            return render_json({"result": False, "code": 1, "message": u"有必填字段未填写", "data": {}})
        if failure_recovery_time and event_happened_time > failure_recovery_time:
            return render_json({"result": False, "code": 1, "message": u"事件发生时间不能大于恢复时间", "data": {}})
        if user_reporting_time and event_happened_time > user_reporting_time:
            return render_json({"result": False, "code": 1, "message": u"事件发生时间不能大于报障时间", "data": {}})
        if accept_time and event_happened_time > accept_time:
            return render_json({"result": False, "code": 1, "message": u"事件发生时间不能大于受理时间", "data": {}})
        if failure_recovery_time and user_reporting_time and user_reporting_time > failure_recovery_time:
            return render_json({"result": False, "code": 1, "message": u"报障时间不能大于恢复时间", "data": {}})
        if failure_recovery_time and accept_time and accept_time > failure_recovery_time:
            return render_json({"result": False, "code": 1, "message": u"受理时间不能大于恢复时间", "data": {}})
        if user_reporting_time and accept_time and user_reporting_time > accept_time:
            return render_json({"result": False, "code": 1, "message": u"报障时间不能大于受理时间", "data": {}})

        # 判断事件分析状态
        if not all([deal_case, root_analysis, solve_measure, failure_surface,
                 related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                 solve_detail, user_reporting_time, event_happened_time, accept_time,
                 failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                 event_summary, first_category, second_category, third_category, impact_degree,
                 urgency_degree, priority, report_source, failure_cause_preliminary_analysis]):
            event_analysis_state = u"未分析"
        else:
            # 有监控有告警+已自动化
            if urgencymeasure_autoinfo == 4 and related_alarm == 1 and eval(monitor_src) and all([sysname, scriptname]):
                event_analysis_state = u"已分析"
            # 非有监控有告警+已自动化
            elif urgencymeasure_autoinfo == 4 and related_alarm != 1 and all([sysname, scriptname]):
                event_analysis_state = u"已分析"
            elif urgencymeasure_autoinfo != 4 and related_alarm == 1 and eval(monitor_src):
                event_analysis_state = u"已分析"
            elif urgencymeasure_autoinfo != 4 and related_alarm != 1:
                event_analysis_state = u"已分析"
            else:
                event_analysis_state = u"未分析"

        # 保存时提示用户哪些字段没有填
        listt = [u'处理过程', u'根因分析', u'解决方案措施', u'故障表象', u'相关告警', u'应急方案', u'应急方案自动化', u'是否解决', u'用户报障时间',
                 u'事件发生时间', u'受理时间',
                 u'故障恢复时间', u'故障系统名称', u'受影响系统名', u'事件类型', u'现象', u'摘要', u'一级分类', u'二级分类', u'三级分类', u'影响度', u'紧急度',
                 u'优先级', u'报告来源', u'故障原因初步分析', u'系统所属名称', u'自动化方案']
        if urgencymeasure_autoinfo != 4 and related_alarm != 1:
            notedit = []
            newList = [deal_case, root_analysis, solve_measure, failure_surface,
                       related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                       solve_detail, user_reporting_time, event_happened_time, accept_time,
                       failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                       event_summary, first_category, second_category, third_category, impact_degree,
                       urgency_degree, priority, report_source,failure_cause_preliminary_analysis]
            for i in newList:
                if i == '' or i == None:
                    notedit.append(listt[newList.index(i) + len(notedit)])
                    newList.remove(i)
            notedit = ','.join(notedit)
            if len(notedit) > 0:
                edidflag = True
            else:
                edidflag = False

        elif urgencymeasure_autoinfo == 4 and related_alarm != 1:
            notedit = []
            newList = [deal_case, root_analysis, solve_measure, failure_surface,
                       related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                       solve_detail, user_reporting_time, event_happened_time, accept_time,
                       failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                       event_summary, first_category, second_category, third_category, impact_degree,
                       urgency_degree, priority, report_source,failure_cause_preliminary_analysis, sysname,
                       scriptname]
            for i in newList:
                if i == '' or i == None:
                    notedit.append(listt[newList.index(i) + len(notedit)])
                    newList.remove(i)
            notedit = ','.join(notedit)
            if scriptname == '':
                notedit += u',自动化方案'
            if len(notedit) > 0:
                edidflag = True
            else:
                edidflag = False

        elif urgencymeasure_autoinfo == 4 and related_alarm == 1:
            notedit = []
            newList = [deal_case, root_analysis, solve_measure, failure_surface,
                       related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                       solve_detail, user_reporting_time, event_happened_time, accept_time,
                       failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                       event_summary, first_category, second_category, third_category, impact_degree,
                       urgency_degree, priority, report_source,failure_cause_preliminary_analysis, sysname,
                       scriptname]
            for i in newList:
                if i == '' or i == None:
                    notedit.append(listt[newList.index(i) + len(notedit)])
                    newList.remove(i)
            notedit = ','.join(notedit)
            if not eval(monitor_src):
                notedit += u",告警实例"
            if scriptname == '':
                notedit += u',自动化方案'
            if len(notedit) > 0:
                edidflag = True
            else:
                edidflag = False

        elif urgencymeasure_autoinfo != 4 and related_alarm == 1:
            notedit = []
            newList = [deal_case, root_analysis, solve_measure, failure_surface,
                       related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                       solve_detail, user_reporting_time, event_happened_time, accept_time,
                       failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                       event_summary, first_category, second_category, third_category, impact_degree,
                       urgency_degree, priority, report_source,failure_cause_preliminary_analysis]
            for i in newList:
                if i == '' or i == None:
                    notedit.append(listt[newList.index(i) + len(notedit)])
                    newList.remove(i)
            notedit = ','.join(notedit)
            if not eval(monitor_src):
                notedit += u',告警实例'
            if len(notedit) > 0:
                edidflag = True
            else:
                edidflag = False

        # 获取事件标签并保存
        event_label_list = req.get('labelname')
        if event_label_list:
            event_label_data = EventLabel.objects.create(
                event_number=event_number,
                event_label=event_label_list
            )
            event_label_data.save()

        # 保存事件表
        event_info = EventInfo.objects.create(
            data_src=u"非同步",
            event_analysis_state=event_analysis_state,
            create_user=request.user.username,
            event_number=event_number,
            user_reporting_time=user_reporting_time if user_reporting_time else None,
            event_happened_time=event_happened_time if event_happened_time else None,
            reception_time=accept_time if accept_time else None,
            failure_recovery_time=failure_recovery_time if failure_recovery_time else None,
            failure_sys_name=failure_sys_name,
            influenced_sys_name=inflenced_sys_name,
            event_type=event_type,
            event_phenomenon=phenomenon,
            event_summary=event_summary,
            event_change_number=change_number,
            event_first_category=first_category,
            event_second_category=second_category,
            event_third_category=third_category,
            event_impact=impact_degree,
            event_urgency=urgency_degree,
            event_priority=priority,
            report_src=report_source,
            processing_person=login_person,
            event_exec_case=deal_case,
            failure_cause_preliminary_analysis=failure_cause_preliminary_analysis
        )
        event_info.save()
        # 根因分析、解决方案措施表
        failure_measure = FailureMeasure.objects.create(
            create_user=request.user.username,
            root_cause_analysis=root_analysis,
            solve_method=solve_measure,
            event_number=event_number,
        )
        failure_measure.save()
        # 故障表象、故障实质现象(改为故障机器ip)、
        failure_analysis = FailureAnalysis.objects.create(
            create_user=request.user.username,
            failure_representation=failure_surface,
            failure_sub_phenomenon=failure_actual_phenomenon,
            solve_detail_info=solve_detail,
            event_number=event_number,
            related_alarm_info=related_alarm,
            monitor_src=monitor_src,
            monitor_info=monitor_info
        )
        failure_analysis.save()
        #
        urgency_measure = UrgencyMeasure.objects.create(
            create_user=request.user.username,
            urgency_info=urgencymeasure_info,
            urgency_auto_info=urgencymeasure_autoinfo,
            auto_sys=sysname,
            script_name=scriptname,
            event_number=event_number,
            auto_info=auto_info
        )
        urgency_measure.save()
        return render_json(
            {
                "result": True,
                "code": 0,
                "message": u"新建任务成功",
                "data": {"editflag": edidflag, "notedit": notedit}
            }
        )
    except Exception as e:
        return render_json({
            "result": False,
            "code": 1,
            "message": u"未知错误:%s" % e,
            "data": {}
        })


# 编辑页面的显示
def edit_display(request):
    try:
        # 获取当前登录用户中文名
        client = get_client_by_request(request)
        bk_token = request.COOKIES.get('bk_token')
        client.set_bk_api_ver('v2')
        parse = {
            'bk_token': bk_token,
            'bk_app_code': APP_ID,
            'bk_app_secret': APP_TOKEN,
        }
        result = client.bk_login.get_user(parse)
        login_person = result['data']['chname']

        # 获取事件编号
        req = json.loads(request.body)
        eventNumber = req.get("event_number")

        '''
        故障分析-自动化相关
        '''
        urgencymeasure_edit = UrgencyMeasure.objects.filter(event_number=eventNumber)
        if urgencymeasure_edit:
            urgencymeasure_dict = {}
            urgencymeasure_dict["urgency_info"] = urgencymeasure_edit[0].urgency_info
            if urgencymeasure_edit[0].urgency_auto_info:
                urgencymeasure_dict["urgency_auto_info"] = int(urgencymeasure_edit[0].urgency_auto_info)
            else:
                urgencymeasure_dict["urgency_auto_info"] = urgencymeasure_edit[0].urgency_auto_info
            # 四个单选按钮
            if urgencymeasure_edit[0].urgency_auto_info and urgencymeasure_edit[0].urgency_auto_info == '4':
                # 已自动化情况the
                urgencymeasure_dict["autochange"] = 1
                urgencymeasure_dict["notbkauto"] = 0
                urgencymeasure_dict["cantauto"] = 0
                urgencymeasure_dict["notautoyet"] = 0
            elif urgencymeasure_edit[0].urgency_auto_info and urgencymeasure_edit[0].urgency_auto_info == '8':
                # 已自动化(非一体化平台)
                urgencymeasure_dict["autochange"] = 0
                urgencymeasure_dict["notbkauto"] = 1
                urgencymeasure_dict["cantauto"] = 0
                urgencymeasure_dict["notautoyet"] = 0
            elif urgencymeasure_edit[0].urgency_auto_info and urgencymeasure_edit[0].urgency_auto_info == '5':
                # 不可自动化
                urgencymeasure_dict["autochange"] = 0
                urgencymeasure_dict["notbkauto"] = 0
                urgencymeasure_dict["cantauto"] = 1
                urgencymeasure_dict["notautoyet"] = 0
            elif urgencymeasure_edit[0].urgency_auto_info and urgencymeasure_edit[0].urgency_auto_info == '6':
                # 未自动化
                urgencymeasure_dict["autochange"] = 0
                urgencymeasure_dict["notbkauto"] = 0
                urgencymeasure_dict["cantauto"] = 0
                urgencymeasure_dict["notautoyet"] = 1
            else:
                urgencymeasure_dict["autochange"] = 0
                urgencymeasure_dict["notbkauto"] = 0
                urgencymeasure_dict["cantauto"] = 0
                urgencymeasure_dict["notautoyet"] = 0
            # 已自动化下的系统和自动化作业
            urgencymeasure_dict["auto_sys"] = urgencymeasure_edit[0].auto_sys
            urgencymeasure_dict["script_name"] = urgencymeasure_edit[0].script_name
            # 其他三个自动化所填信息
            auto_info_dic = urgencymeasure_edit[0].auto_info
            if auto_info_dic == None:
                urgencymeasure_dict["notbkautoinfo"] = ''
                urgencymeasure_dict["cantautoinfo"] = ''
                urgencymeasure_dict["notautoyetinfo"] = ''
            elif '{' in auto_info_dic:
                auto_info_dic = eval(auto_info_dic)
                if auto_info_dic.has_key('notbkautoinfo'):
                    urgencymeasure_dict["notbkautoinfo"] = auto_info_dic['notbkautoinfo']
                    urgencymeasure_dict["cantautoinfo"] = ''
                    urgencymeasure_dict["notautoyetinfo"] = ''
                elif auto_info_dic.has_key('cantautoinfo'):
                    urgencymeasure_dict["notbkautoinfo"] = ''
                    urgencymeasure_dict["cantautoinfo"] = auto_info_dic['cantautoinfo']
                    urgencymeasure_dict["notautoyetinfo"] = ''
                elif auto_info_dic.has_key('notautoyet'):
                    urgencymeasure_dict["notbkautoinfo"] = ''
                    urgencymeasure_dict["cantautoinfo"] = ''
                    urgencymeasure_dict["notautoyetinfo"] = auto_info_dic['notautoyet']
            else:
                urgencymeasure_dict["notbkautoinfo"] = ''
                urgencymeasure_dict["cantautoinfo"] = ''
                urgencymeasure_dict["notautoyetinfo"] = ''
        else:
            urgencymeasure_dict = {}

        '''
        故障表象与告警
        '''
        failureanalysis_edit = FailureAnalysis.objects.filter(event_number=eventNumber)
        if failureanalysis_edit:  # type
            failureanalysis_dict = {}
            failure_surface = failureanalysis_edit[0].failure_representation
            failureanalysis_dict["failure_surface"] = failure_surface
            actual_phenomenon = failureanalysis_edit[0].failure_sub_phenomenon
            if actual_phenomenon:
                failureanalysis_dict["actual_phenomenon"] = eval(actual_phenomenon)
            else:
                failureanalysis_dict["actual_phenomenon"] = []
            solve_detail = failureanalysis_edit[0].solve_detail_info
            if solve_detail:
                if '10' in solve_detail or '11' in solve_detail:
                    solve_detail = int(solve_detail)
                else:
                    if '是' in solve_detail or '已' in solve_detail:
                        solve_detail = 10
                    else:
                        solve_detail = 11
            else:
                solve_detail = ''
            failureanalysis_dict["solve_detail"] = solve_detail
            failureanalysis_dict["related_alarm_info"] = failureanalysis_edit[0].related_alarm_info,
            if failureanalysis_dict["related_alarm_info"][0]:
                a=failureanalysis_dict["related_alarm_info"]
                b=failureanalysis_dict["related_alarm_info"][0]
                failureanalysis_dict["related_alarm_info"] = int(failureanalysis_dict["related_alarm_info"][0])
            else:
                failureanalysis_dict["related_alarm_info"] = failureanalysis_dict["related_alarm_info"][0]

            if failureanalysis_edit[0].related_alarm_info and failureanalysis_edit[0].related_alarm_info == '1':
                failureanalysis_dict["alarmchange"] = 1
                failureanalysis_dict["notbkalarm"] = 0
                failureanalysis_dict["havemonitor"] = 0
                failureanalysis_dict["notmonitor"] = 0
            elif failureanalysis_edit[0].related_alarm_info and failureanalysis_edit[0].related_alarm_info == '7':
                failureanalysis_dict["alarmchange"] = 0
                failureanalysis_dict["notbkalarm"] = 1
                failureanalysis_dict["havemonitor"] = 0
                failureanalysis_dict["notmonitor"] = 0
            elif failureanalysis_edit[0].related_alarm_info and failureanalysis_edit[0].related_alarm_info == '2':
                failureanalysis_dict["alarmchange"] = 0
                failureanalysis_dict["notbkalarm"] = 0
                failureanalysis_dict["havemonitor"] = 1
                failureanalysis_dict["notmonitor"] = 0
            elif failureanalysis_edit[0].related_alarm_info and failureanalysis_edit[0].related_alarm_info == '3':
                failureanalysis_dict["alarmchange"] = 0
                failureanalysis_dict["notbkalarm"] = 0
                failureanalysis_dict["havemonitor"] = 0
                failureanalysis_dict["notmonitor"] = 1
            else:
                failureanalysis_dict["alarmchange"] = 0
                failureanalysis_dict["notbkalarm"] = 0
                failureanalysis_dict["havemonitor"] = 0
                failureanalysis_dict["notmonitor"] = 0

            if failureanalysis_edit[0].monitor_info == None:
                failureanalysis_dict["notbkalarminfo"] = ''
                failureanalysis_dict["havemonitorinfo"] = ''
                failureanalysis_dict["notmonitorinfo"] = ''
            elif '{' in failureanalysis_edit[0].monitor_info:
                monitor_dic = eval(failureanalysis_edit[0].monitor_info)
                if monitor_dic.has_key('notbkalarminfo'):
                    failureanalysis_dict["notbkalarminfo"] = monitor_dic['notbkalarminfo']
                    failureanalysis_dict["havemonitorinfo"] = ''
                    failureanalysis_dict["notmonitorinfo"] = ''
                elif monitor_dic.has_key('havemonitorinfo'):
                    failureanalysis_dict["notbkalarminfo"] = ''
                    failureanalysis_dict["havemonitorinfo"] = monitor_dic['havemonitorinfo']
                    failureanalysis_dict["notmonitorinfo"] = ''
                elif monitor_dic.has_key('notmonitorinfo'):
                    failureanalysis_dict["notbkalarminfo"] = ''
                    failureanalysis_dict["havemonitorinfo"] = ''
                    failureanalysis_dict["notmonitorinfo"] = monitor_dic['notmonitorinfo']
            else:
                failureanalysis_dict["notbkalarminfo"] = ''
                failureanalysis_dict["havemonitorinfo"] = ''
                failureanalysis_dict["notmonitorinfo"] = ''

            failureanalysis_dict["failure_recovery_version"] = failureanalysis_edit[0].failure_recovery_version,
            failureanalysis_dict["failure_recovery_version"] = failureanalysis_dict["failure_recovery_version"][0]
            failureanalysis_dict["failure_in_version"] = failureanalysis_edit[0].failure_in_version

            failureanalysis_dict["monitor_src"] = failureanalysis_edit[0].monitor_src
            failureanalysis_dict["monitor_src"] = failureanalysis_dict["monitor_src"].encode('utf-8')
            failureanalysis_dict["monitor_src"] = eval(failureanalysis_dict["monitor_src"])

        else:
            failureanalysis_dict = {}

        failuremeasure_edit = FailureMeasure.objects.filter(event_number=eventNumber)

        if failuremeasure_edit:  # type
            failuremeasure_dict = {}
            failuremeasure_dict["root_analysis"] = failuremeasure_edit[0].root_cause_analysis
            failuremeasure_dict["solve_measure"] = failuremeasure_edit[0].solve_method
        else:
            failuremeasure_dict = {}

        eventinfo_edit = EventInfo.objects.filter(event_number=eventNumber)

        relevance_edit_list = RelevanceAnalysis.objects.filter(event_number=eventNumber)
        relevance_list = list()
        if relevance_edit_list:
            for relevance_edit in relevance_edit_list:  # type
                relevance_dict = {}
                if relevance_edit.event_number == eventNumber:
                    relevance_dict["relevance_type"] = relevance_edit.association_type,
                    relevance_dict["request_type"] = relevance_edit.request_type,
                    relevance_dict["relevance_result_change"] = relevance_edit.asso_result_change
                    relevance_list.append(relevance_dict)
        else:
            relevance_list = []

        if eventinfo_edit[0].data_src == '同步':
            if not eventinfo_edit[0].user_reporting_time:
                user_reporting_time = None
            else:
                user_reporting_time = (eventinfo_edit[0].user_reporting_time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
            if not eventinfo_edit[0].event_happened_time:
                event_happened_time = None
            else:
                event_happened_time = (eventinfo_edit[0].event_happened_time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
            if not eventinfo_edit[0].reception_time:
                reception_time = None
            else:
                reception_time = (eventinfo_edit[0].reception_time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
            if not eventinfo_edit[0].failure_recovery_time:
                failure_recovery_time = None
            else:
                failure_recovery_time = (eventinfo_edit[0].failure_recovery_time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
        else:
            if not eventinfo_edit[0].user_reporting_time:
                user_reporting_time = None
            else:
                user_reporting_time = eventinfo_edit[0].user_reporting_time.strftime('%Y-%m-%d %H:%M:%S')
            if not eventinfo_edit[0].event_happened_time:
                event_happened_time = None
            else:
                event_happened_time = eventinfo_edit[0].event_happened_time.strftime('%Y-%m-%d %H:%M:%S')
            if not eventinfo_edit[0].reception_time:
                reception_time = None
            else:
                reception_time = eventinfo_edit[0].reception_time.strftime('%Y-%m-%d %H:%M:%S')
            if not eventinfo_edit[0].failure_recovery_time:
                failure_recovery_time = None
            else:
                failure_recovery_time = eventinfo_edit[0].failure_recovery_time.strftime('%Y-%m-%d %H:%M:%S')

        label = EventLabel.objects.filter(event_number=eventNumber)
        if label:
            labelName = eval(label[0].event_label)
        else:
            labelName = []

        # 若不是当前登陆用户
        if eventinfo_edit[0].processing_person == login_person:
            show_src = 0
        else:
            show_src = 1

        # 之前的数据为单字符串，现改为列表
        influenced_sys_name = eventinfo_edit[0].influenced_sys_name
        if '[' in influenced_sys_name:
            influenced_sys_name = eval(influenced_sys_name)
        else:
            influenced_sys_name = [influenced_sys_name]

        data = {
            "urgency": urgencymeasure_dict,
            "failure_analysis": failureanalysis_dict,
            "failuremeasure": failuremeasure_dict,
            "event_analysis_state": eventinfo_edit[0].event_analysis_state,
            "relevance_analysis": relevance_list,
            "event_number": eventinfo_edit[0].event_number,
            "user_reporting_time": user_reporting_time,
            "event_happened_time": event_happened_time,
            "event_accept_time": reception_time,
            "failure_recovery_time": failure_recovery_time,
            "failure_sys_name": eventinfo_edit[0].failure_sys_name,
            "phenomenon": eventinfo_edit[0].event_phenomenon,
            "influenced_sys_name": influenced_sys_name,
            "event_summary": eventinfo_edit[0].event_summary,
            "change_number": eventinfo_edit[0].event_change_number,
            "event_type": eventinfo_edit[0].event_type,
            "first_category": eventinfo_edit[0].event_first_category,
            "impact_degree": eventinfo_edit[0].event_impact,
            "urgency_degree": eventinfo_edit[0].event_urgency,
            "second_category": eventinfo_edit[0].event_second_category,
            "priority": eventinfo_edit[0].event_priority,
            "third_category": eventinfo_edit[0].event_third_category,
            "report_source": eventinfo_edit[0].report_src,
            "dealer": eventinfo_edit[0].processing_person,
            "deal_processing": eventinfo_edit[0].event_exec_case,
            # "data_src": 1 if eventinfo_edit[0].data_src == u"同步" else 0,
            "data_src": 0,
            "failure_cause_preliminary_analysis": eventinfo_edit[0].failure_cause_preliminary_analysis,
            "if_cause": 1 if 'bug' in str(eventinfo_edit[0].failure_cause_preliminary_analysis) else 0,
            'show_src': show_src,
            'labelname': labelName
        }
        return render_json({
            "result": True,
            "message": u"未分析情况的数据查询成功",
            "code": 0,
            "results": data
        })

    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知异常：%s" % e,
                "results": {}

            }
        )


# 事件编辑
def commit_button(request):
    try:
        result = json.loads(request.body)
        req = result["data"]
        res = result["alarmList"]

        # 根据事件编号获取之前的所有信息
        event_number = req.get("event_number")

        # 事件标签
        event_label = req.get('labelname')
        event_label_list = EventLabel.objects.filter(event_number=event_number)
        if event_label_list:
            event_label_list[0].event_label = req.get('labelname')
            event_label_list[0].save()
        else:
            a = EventLabel.objects.create(event_number=event_number, event_label=req.get('labelname'))
            a.save()


        eventinfo_list = EventInfo.objects.filter(event_number=event_number)
        failuremeasure_list = FailureMeasure.objects.filter(event_number=event_number)
        failure_analysis_list = FailureAnalysis.objects.filter(event_number=event_number)
        if failure_analysis_list:
            monitor_src = failure_analysis_list[0].monitor_src
            monitor_src = monitor_src.encode('utf-8')
            monitor_src = eval(monitor_src)
        else:
            monitor_src = res
        urgencymeasure_list = UrgencyMeasure.objects.filter(event_number=event_number)


        urgencymeasure_dict = req.get("urgency")
        failureanalysis_dict = req.get("failure_analysis")
        failuremeasure_dict = req.get("failuremeasure")

        deal_case = req.get("deal_processing")
        root_analysis = failuremeasure_dict.get("root_analysis")
        solve_measure = failuremeasure_dict.get("solve_measure")
        failure_surface = failureanalysis_dict.get("failure_surface")
        failure_actual_phenomenon = failureanalysis_dict.get("actual_phenomenon")
        related_alarm = failureanalysis_dict.get("related_alarm_info")
        for alarm in res:
            if alarm not in monitor_src:
                monitor_src.append(alarm)
        monitor_src = str(monitor_src)
        solve_detail = failureanalysis_dict.get("solve_detail")
        urgencymeasure_info = urgencymeasure_dict.get("urgency_info")
        urgencymeasure_autoinfo = urgencymeasure_dict.get("urgency_auto_info")
        sysname = urgencymeasure_dict.get("auto_sys")
        scriptname = urgencymeasure_dict.get("script_name")
        if failureanalysis_dict.get("notbkalarminfo"):
            monitor_info = {'notbkalarminfo': failureanalysis_dict.get("notbkalarminfo")}
        elif failureanalysis_dict.get("havemonitorinfo"):
            monitor_info = {'havemonitorinfo': failureanalysis_dict.get("havemonitorinfo")}
        elif failureanalysis_dict.get("notmonitorinfo"):
            monitor_info = {'notmonitorinfo': failureanalysis_dict.get("notmonitorinfo")}
        else:
            monitor_info = ''
        if urgencymeasure_dict.get("notbkautoinfo"):
            auto_info = {'notbkautoinfo': urgencymeasure_dict.get("notbkautoinfo")}
        elif urgencymeasure_dict.get("cantautoinfo"):
            auto_info = {'cantautoinfo': urgencymeasure_dict.get("cantautoinfo")}
        elif urgencymeasure_dict.get("notautoyetinfo"):
            auto_info = {'notautoyetinfo': urgencymeasure_dict.get("notautoyetinfo")}
        else:
            auto_info = ''
        user_reporting_time = req.get("user_reporting_time")
        if user_reporting_time:
            user_reporting_time = str(user_reporting_time)
            if len(user_reporting_time) > 19:
                user_reporting_time = user_reporting_time.replace('T', ' ')
                user_reporting_time = user_reporting_time[0:-5]
                user_reporting_time = datetime.datetime.strptime(user_reporting_time, "%Y-%m-%d %H:%M:%S")
                user_reporting_time = (user_reporting_time + datetime.timedelta(hours=16)).strftime("%Y-%m-%d %H:%M:%S")
            else:
                user_reporting_time = datetime.datetime.strptime(user_reporting_time, "%Y-%m-%d %H:%M:%S")
                user_reporting_time = (user_reporting_time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
        event_happened_time = req.get("event_happened_time")
        if event_happened_time:
            event_happened_time = str(event_happened_time)
            if len(event_happened_time) > 19:
                event_happened_time = event_happened_time.replace('T', ' ')
                event_happened_time = event_happened_time[0:-5]
                event_happened_time = datetime.datetime.strptime(event_happened_time, "%Y-%m-%d %H:%M:%S")
                event_happened_time = (event_happened_time + datetime.timedelta(hours=16)).strftime("%Y-%m-%d %H:%M:%S")
            else:
                event_happened_time = datetime.datetime.strptime(event_happened_time, "%Y-%m-%d %H:%M:%S")
                event_happened_time = (event_happened_time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
        accept_time = req.get("event_accept_time")
        if accept_time:
            accept_time = str(accept_time)
            if len(accept_time) > 19:
                accept_time = accept_time.replace('T', ' ')
                accept_time = accept_time[0:-5]
                accept_time = datetime.datetime.strptime(accept_time, "%Y-%m-%d %H:%M:%S")
                accept_time = (accept_time + datetime.timedelta(hours=16)).strftime("%Y-%m-%d %H:%M:%S")
            else:
                accept_time = datetime.datetime.strptime(accept_time, "%Y-%m-%d %H:%M:%S")
                accept_time = (accept_time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
        failure_recovery_time = req.get("failure_recovery_time")
        if failure_recovery_time:
            failure_recovery_time = str(failure_recovery_time)
            if len(failure_recovery_time) > 19:
                failure_recovery_time = failure_recovery_time.replace('T', ' ')
                failure_recovery_time = failure_recovery_time[0:-5]
                failure_recovery_time = datetime.datetime.strptime(failure_recovery_time, "%Y-%m-%d %H:%M:%S")
                failure_recovery_time = (failure_recovery_time + datetime.timedelta(hours=16)).strftime("%Y-%m-%d %H:%M:%S")
            else:
                failure_recovery_time = datetime.datetime.strptime(failure_recovery_time, "%Y-%m-%d %H:%M:%S")
                failure_recovery_time = (failure_recovery_time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
        failure_sys_name = req.get("failure_sys_name")
        inflenced_sys_name = req.get("influenced_sys_name")
        event_type = req.get("event_type")
        phenomenon = req.get("phenomenon")
        event_summary = req.get("event_summary")
        change_number = req.get("change_number")
        first_category = req.get("first_category")
        second_category = req.get("second_category")
        third_category = req.get("third_category")
        impact_degree = req.get("impact_degree")
        urgency_degree = req.get("urgency_degree")
        priority = req.get("priority")
        report_source = req.get("report_source")
        dealer = req.get("dealer")
        failure_cause_preliminary_analysis = req.get("failure_cause_preliminary_analysis")




        # 判断必填字段和四个时间先后顺序
        if not all([event_summary, priority, event_happened_time]):
            return render_json({"result": False,"code": 1,"message": u"有必填字段未填写","data": {}})
        if failure_recovery_time and event_happened_time > failure_recovery_time:
            return render_json({"result": False,"code": 1,"message": u"事件发生时间不能大于恢复时间","data": {}})
        if user_reporting_time and event_happened_time > user_reporting_time:
            return render_json({"result": False,"code": 1,"message": u"事件发生时间不能大于报障时间","data": {}})
        if accept_time and event_happened_time > accept_time:
            return render_json({"result": False,"code": 1,"message": u"事件发生时间不能大于受理时间","data": {}})
        if failure_recovery_time and user_reporting_time and user_reporting_time > failure_recovery_time:
            return render_json({"result": False,"code": 1,"message": u"报障时间不能大于恢复时间","data": {}})
        if failure_recovery_time and accept_time and accept_time > failure_recovery_time:
            return render_json({"result": False,"code": 1,"message": u"受理时间不能大于恢复时间","data": {}})
        if user_reporting_time and accept_time and user_reporting_time > accept_time:
            return render_json({"result": False,"code": 1,"message": u"报障时间不能大于受理时间","data": {}})

        # 判断事件分析状态
        if urgencymeasure_autoinfo == 4 and related_alarm == 1 and eval(monitor_src) and all([deal_case, root_analysis, solve_measure, failure_surface,
                    related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                    solve_detail, user_reporting_time, event_happened_time, accept_time,
                    failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                    event_summary, first_category, second_category, third_category, impact_degree,
                    urgency_degree, priority, report_source, dealer, failure_cause_preliminary_analysis,sysname,scriptname]):
            event_analysis_state = u"已分析"
        elif urgencymeasure_autoinfo == 4 and related_alarm!=1  and  all([deal_case, root_analysis, solve_measure, failure_surface,
                    related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                    solve_detail, user_reporting_time, event_happened_time, accept_time,
                    failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                    event_summary, first_category, second_category, third_category, impact_degree,
                    urgency_degree, priority, report_source, dealer, failure_cause_preliminary_analysis,sysname,scriptname]):
            event_analysis_state = u"已分析"
        elif urgencymeasure_autoinfo!=4 and related_alarm==1 and  eval(monitor_src)  and  all([deal_case, root_analysis, solve_measure, failure_surface,
                    related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                    solve_detail, user_reporting_time, event_happened_time, accept_time,
                    failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                    event_summary, first_category, second_category, third_category, impact_degree,
                    urgency_degree, priority, report_source, dealer, failure_cause_preliminary_analysis]):
            event_analysis_state = u"已分析"
        elif urgencymeasure_autoinfo!=4 and related_alarm!=1  and  all([deal_case, root_analysis, solve_measure, failure_surface,
                    related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                    solve_detail, user_reporting_time, event_happened_time, accept_time,
                    failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                    event_summary, first_category, second_category, third_category, impact_degree,
                    urgency_degree, priority, report_source, dealer, failure_cause_preliminary_analysis]):
            event_analysis_state = u"已分析"
        else:
            event_analysis_state = u"未分析"

        # 保存事件时未填字段提示
        listt = [u'处理过程', u'根因分析', u'解决方案措施', u'故障表象', u'相关告警', u'应急方案',
                 u'应急方案自动化', u'是否解决', u'用户报障时间',u'事件发生时间', u'受理时间',u'故障恢复时间',
                 u'故障系统名称', u'受影响系统名', u'事件类型', u'现象', u'摘要', u'一级分类', u'二级分类',
                 u'三级分类', u'影响度', u'紧急度',u'优先级', u'报告来源', u'处理人',u'故障原因初步分析', u'系统所属名称', u'自动化方案']
        if urgencymeasure_autoinfo != 4 and related_alarm != 1:
            notedit=[]
            newList=[deal_case, root_analysis, solve_measure, failure_surface,
                    related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                    solve_detail, user_reporting_time, event_happened_time, accept_time,
                    failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                    event_summary, first_category, second_category, third_category, impact_degree,
                    urgency_degree, priority, report_source, dealer, failure_cause_preliminary_analysis]
            for i in newList:
                if i == '' or i==None :
                    notedit.append(listt[newList.index(i)+len(notedit)])
                    newList.remove(i)
            notedit=','.join(notedit)
            if len(notedit)>0:
                edidflag=True
            else:
                edidflag=False
        elif urgencymeasure_autoinfo == 4 and related_alarm != 1:
            notedit = []
            newList = [deal_case, root_analysis, solve_measure, failure_surface,
             related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
             solve_detail, user_reporting_time, event_happened_time, accept_time,
             failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
             event_summary, first_category, second_category, third_category, impact_degree,
             urgency_degree, priority, report_source, dealer, failure_cause_preliminary_analysis, sysname,
             scriptname]
            for i in newList:
                if i=='' or i==None :
                    notedit.append(listt[newList.index(i)+len(notedit)])
                    newList.remove(i)
            notedit=','.join(notedit)
            if scriptname == '':
                notedit += u',自动化方案'
            if len(notedit)>0:
                edidflag=True
            else:
                edidflag=False
        elif urgencymeasure_autoinfo==4 and related_alarm==1:
            notedit = []
            newList = [deal_case, root_analysis, solve_measure, failure_surface,
                       related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                       solve_detail, user_reporting_time, event_happened_time, accept_time,
                       failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                       event_summary, first_category, second_category, third_category, impact_degree,
                       urgency_degree, priority, report_source, dealer, failure_cause_preliminary_analysis, sysname,
                       scriptname]
            for i in newList:
                if i == '' or i == None:
                    notedit.append(listt[newList.index(i) + len(notedit)])
                    newList.remove(i)
            notedit = ','.join(notedit)
            if not eval(monitor_src):
                notedit += u",告警实例"
            if scriptname == '':
                notedit += u',自动化方案'
            if len(notedit)>0:
                edidflag=True
            else:
                edidflag=False
        elif urgencymeasure_autoinfo != 4 and related_alarm == 1:
            notedit = []
            newList = [deal_case, root_analysis, solve_measure, failure_surface,
                       related_alarm, urgencymeasure_info, urgencymeasure_autoinfo,
                       solve_detail, user_reporting_time, event_happened_time, accept_time,
                       failure_recovery_time, failure_sys_name, inflenced_sys_name, event_type, phenomenon,
                       event_summary, first_category, second_category, third_category, impact_degree,
                       urgency_degree, priority, report_source, dealer, failure_cause_preliminary_analysis]
            for i in newList:
                if i == '' or i == None:
                    notedit.append(listt[newList.index(i) + len(notedit)])
                    newList.remove(i)
            notedit = ','.join(notedit)
            if not eval(monitor_src):
                notedit += u',告警实例'
            if len(notedit)>0:
                edidflag=True
            else:
                edidflag=False

        # 更新、新建数据
        try:
            if len(eventinfo_list) != 0:
                eventinfo_list[0].event_analysis_state = event_analysis_state
                eventinfo_list[0].failure_cause_preliminary_analysis = failure_cause_preliminary_analysis
                eventinfo_list[0].create_user = request.user.username
                eventinfo_list[0].user_reporting_time = user_reporting_time
                eventinfo_list[0].event_happened_time = event_happened_time
                eventinfo_list[0].reception_time = accept_time
                eventinfo_list[0].failure_recovery_time = failure_recovery_time
                eventinfo_list[0].failure_sys_name = failure_sys_name
                eventinfo_list[0].influenced_sys_name = inflenced_sys_name
                eventinfo_list[0].event_type = event_type
                eventinfo_list[0].event_phenomenon = phenomenon
                eventinfo_list[0].event_summary = event_summary
                eventinfo_list[0].event_change_number = change_number
                eventinfo_list[0].event_first_category = first_category
                eventinfo_list[0].event_second_category = second_category
                eventinfo_list[0].event_third_category = third_category
                eventinfo_list[0].event_impact = impact_degree
                eventinfo_list[0].event_urgency = urgency_degree
                eventinfo_list[0].event_priority = priority
                eventinfo_list[0].report_src = report_source
                eventinfo_list[0].processing_person = dealer
                eventinfo_list[0].event_exec_case = deal_case
                eventinfo_list[0].save()
            if len(failuremeasure_list) != 0:
                failuremeasure_list[0].create_user = request.user.username
                failuremeasure_list[0].root_cause_analysis = root_analysis
                failuremeasure_list[0].solve_method = solve_measure
                failuremeasure_list[0].save()
            else:
                failuremeasure = FailureMeasure.objects.create(
                        event_number=event_number,
                        create_user=request.user.username,
                        root_cause_analysis=root_analysis,
                        solve_method=solve_measure,
                    )
                failuremeasure.save()
            if len(failure_analysis_list) != 0:
                failure_analysis_list[0].create_user = request.user.username
                failure_analysis_list[0].failure_representation = failure_surface
                failure_analysis_list[0].failure_sub_phenomenon = failure_actual_phenomenon
                failure_analysis_list[0].related_alarm_info = related_alarm
                failure_analysis_list[0].monitor_src = monitor_src
                failure_analysis_list[0].solve_detail_info = solve_detail
                failure_analysis_list[0].monitor_info = monitor_info
                failure_analysis_list[0].save()
            else:
                failure_analysis = FailureAnalysis.objects.create(
                        create_user=request.user.username,
                        failure_representation=failure_surface,
                        failure_sub_phenomenon=failure_actual_phenomenon,
                        related_alarm_info=related_alarm,
                        monitor_src=monitor_src,
                        solve_detail_info=solve_detail,
                        event_number=event_number,
                        monitor_info=monitor_info
                    )
                failure_analysis.save()
            if len(urgencymeasure_list) != 0:
                urgencymeasure_list[0].create_user = request.user.username
                urgencymeasure_list[0].urgency_info = urgencymeasure_info
                urgencymeasure_list[0].urgency_auto_info = urgencymeasure_autoinfo
                urgencymeasure_list[0].auto_sys = sysname
                urgencymeasure_list[0].script_name = scriptname
                urgencymeasure_list[0].auto_info = auto_info
                urgencymeasure_list[0].save()
            else:
                urgencymeasure = UrgencyMeasure.objects.create(
                        event_number=event_number,
                        create_user=request.user.username,
                        urgency_info=urgencymeasure_info,
                        urgency_auto_info=urgencymeasure_autoinfo,
                        auto_sys=sysname,
                        script_name=scriptname,
                        auto_info=auto_info
                    )
                urgencymeasure.save()
            return render_json({
                    "result": True,
                    "code": 0,
                    "message": u"新建过的数据编辑成功",
                    "data": {
                             "editflag":edidflag,"notedit":notedit}
                })
        except Exception as e:
            return render_json({
                    "result": False,
                    "code": 1,
                    "message": u"数据库更新错误：%s" % e,
                    "data": {}
                })

    except Exception as e:
        return render_json({
            "result": False,
            "code": 1,
            "message": u"未知错误:%s" % e,
            "data": {}
        })


# 一二三级事件分类后端接口
def event_category_list(request):
    second_dict = {}
    second_total_list = []
    third_total_list = []
    third_dict = {}
    try:
        category_list = ClassificationLayer.objects.all()
        first_list = list()
        # 先查询出一级分类
        for category in category_list:
            if category.category1 not in first_list:
                first_list.append(category.category1)
    except Exception as e:
        return render_json({
            "result": False,
            "code": 1,
            "message": u"一级分类事件查询失败:%s" % e,
            "data": {}
        })

    for first_event in first_list:
        try:
            second_list = []
            choose_list = ClassificationLayer.objects.filter(category1=first_event)
            for choose in choose_list:
                if choose.category2 not in second_list:
                    second_list.append(choose.category2)
                    second_total_list.append(choose.category2)
            second_dict[first_event] = second_list
        except Exception as e:
            return render_json({
                "result": False,
                "code": 1,
                "message": u"一级事件对应的二级事件查询失败:%s" % e,
                "data": {}
            })

    # 二级和三级的关系
    for second_event in second_total_list:
        try:
            third_list = []
            choose2_list = ClassificationLayer.objects.filter(category2=second_event)
            for choose2 in choose2_list:  # type
                if choose2.category3 not in third_list:
                    third_list.append(choose2.category3)
                    third_total_list.append(choose2.category3)
            third_dict[second_event] = third_list
        except Exception as e:
            return render_json({
                "result": False,
                "code": 1,
                "message": u"二级事件对应的三级事件查询失败:%s" % e,
                "data": {}
            })
    total_list = [first_list, second_dict, third_dict]

    return render_json({
        "result": True,
        "code": 0,
        "message": u"三级分类列表查询成功",
        "data": total_list,
    })


# 删除事件
def delete_event(request):
    req = json.loads(request.body)
    event_number = req.get("event_number")
    if event_number is None:
        return render_json({"result": False,"code": 1,"message": u"模板id不能为空","data": {}})
    try:
        EventInfo.objects.filter(event_number=event_number).delete()
        FailureMeasure.objects.filter(event_number=event_number).delete()
        if RelevanceAnalysis.objects.filter(event_number=event_number):
            RelevanceAnalysis.objects.filter(event_number=event_number).delete()
        FailureAnalysis.objects.filter(event_number=event_number).delete()
        UrgencyMeasure.objects.filter(event_number=event_number).delete()
        if EventLabel.objects.filter(event_number=event_number):
            EventLabel.objects.filter(event_number=event_number).delete()
        return render_json({"result": True,"code": 0,"message": u"删除事件成功","data": {'deleteState':0}})
    except Exception as e:
        return render_json({
            "result": False,
            "code": 1,
            "message": u"数据库操作错误:%s" % e,
            "data": {},
        })


# 设置导出Excel表格样式
def set_style(name, height, bold=False):
    style = xlwt.XFStyle()  # 初始化样式
    font = xlwt.Font()  # 为样式创建字体
    font.name = name
    font.bold = bold
    font.color_index = 4
    font.height = height
    style.font = font
    return style


# 生成导出文件
def event_out(request):
    # 将事件信息添加进列表中
    try:
        req = json.loads(request.body)
        event_number_list = []
        if isinstance(req, dict):
            event_list = req.get("eventList")
            for event in event_list:
                event = event.encode('utf-8')
                event_number_list.append(event)
        else:
            start_time = req[0]
            start_time = start_time[:10]
            start_time = datetime.datetime.strptime(start_time, "%Y-%m-%d")
            end_time = req[1]
            end_time = end_time[:10]
            end_time = datetime.datetime.strptime(end_time, "%Y-%m-%d")
            end_time = end_time + datetime.timedelta(days=2)
            time_event_list = EventInfo.objects.filter(event_happened_time__gte=start_time).filter(event_happened_time__lte=end_time)
            time_event_list = time_event_list.exclude(processing_person__in=[u'徐文', u'刘骏'])
            if time_event_list:
                for i in time_event_list:
                    event_number_list.append(i.event_number)
            else:
                return render_json(
                    {
                        "result": True,
                        "code": 0,
                        "message": u"没有事件",
                        "data": 0
                    }
                )

        data_list = []
        for i in event_number_list:
            new_list = []
            eventList = EventInfo.objects.filter(event_number=i)
            for event in eventList:
                # 事件编号
                new_list.append(event.event_number if event.event_number else '')
                # 事件状态
                new_list.append(event.event_analysis_state if event.event_analysis_state else '')
                # 处理人
                new_list.append(event.processing_person if event.processing_person else '')
                # 事件摘要
                new_list.append(event.event_summary if event.event_summary else '')
                # 紧急变更单号
                new_list.append(event.event_change_number if event.event_change_number else '')
                # 事件发生时间
                new_list.append(str(event.event_happened_time) if event.event_happened_time else '')
                # 用户报障事件
                new_list.append(str(event.user_reporting_time) if event.user_reporting_time else '')
                # 受理时间
                new_list.append(str(event.reception_time) if event.reception_time else '')
                # 故障恢复时间
                new_list.append(str(event.failure_recovery_time) if event.failure_recovery_time else '')
                # 故障系统名
                new_list.append(event.failure_sys_name if event.failure_sys_name else '')
                # 受影响系统名，部分数据只有一个，部分数据有多个(列表形式)
                if event.influenced_sys_name:
                    if '[' in event.influenced_sys_name:
                        influenced_sys_name = ''
                        for z in eval(event.influenced_sys_name):
                            influenced_sys_name += z
                    else:
                        influenced_sys_name = event.influenced_sys_name
                else:
                    influenced_sys_name = ''
                new_list.append(influenced_sys_name)
                # 事件类型
                new_list.append(event.event_type if event.event_type else '')
                # 现象
                new_list.append(event.event_phenomenon if event.event_phenomenon else '')
                # 一级分类
                new_list.append(event.event_first_category if event.event_first_category else '')
                # 二级分类
                new_list.append(event.event_second_category if event.event_second_category else '')
                # 三级分类
                new_list.append(event.event_third_category if event.event_third_category else '')
                # 故障原因初步分析
                new_list.append(event.failure_cause_preliminary_analysis if event.failure_cause_preliminary_analysis else '')
                # 影响度
                new_list.append(event.event_impact if event.event_impact else '')
                # 优先级
                new_list.append(event.event_priority if event.event_priority else '')
                # 紧急度
                new_list.append(event.event_urgency if event.event_urgency else '')
                # 报告来源
                new_list.append(event.report_src if event.report_src else '')
                # 处理过程
                new_list.append(event.event_exec_case if event.event_exec_case else '')

                # 根因分析、解决方案措施
                event1_list = FailureMeasure.objects.filter(event_number=i)
                # event11_list = []
                # for y in event1_list:
                #     event11_list.append(y[0])
                if event1_list:
                    event1 = FailureMeasure.objects.get(event_number=i)
                    new_list.append(event1.root_cause_analysis if event1.root_cause_analysis else '')
                    new_list.append(event1.solve_method if event1.solve_method else '')
                else:
                    new_list.append('')
                    new_list.append('')

                #
                event2_list = FailureAnalysis.objects.filter(event_number=i)
                # event22_list = []
                # for x in event2_list:
                #     event22_list.append(x[0])
                if event2_list:
                    event2 = FailureAnalysis.objects.get(event_number=i)
                    # 故障表象
                    new_list.append(event2.failure_representation if event2.failure_representation else '')
                    # 故障实质现象,旧数据是三个数据拼接，新的是ip
                    text = event2.failure_sub_phenomenon if event2.failure_sub_phenomenon else ''
                    if text:
                        if '[' in text:
                            Text = ''
                            for x in eval(text):
                                Text = Text + x['machine_ip'] + ','
                        else:
                            text = eval(text)
                            three = text['detail_alarm']
                            one = text['program']
                            two = text['alarm_total_type']
                            Text = ''
                            if one == None:
                                one = ''
                            if two == None:
                                two = ''
                            if three == None:
                                three = ''
                            Text = Text + one + '-' + two + '-' + three
                    else:
                        Text = ''
                    new_list.append(Text)
                    # 相关告警(事件告警状态)
                    alarm = event2.related_alarm_info
                    if alarm:
                        if alarm == '1':
                            alarm = u'有监控有报警'
                        elif alarm == '7':
                            alarm = u'有监控有报警(非一体化平台)'
                        elif alarm == '2':
                            alarm = u'有监控无报警'
                        elif alarm == '3':
                            alarm = u'无监控无报警'
                    else:
                        alarm = ''
                    new_list.append(alarm)
                    # 告警实例(‘有监控有报警’会有)
                    monitor = eval(event2.monitor_src)
                    if monitor:
                        alarm_text = ''
                        for j in monitor:
                            new_str = ''
                            new_str = new_str + '告警标题:' + "'" + j['alarm_title'] + "'" + ','
                            new_str = new_str + '告警内容:' + "'" + j['alarm_info'] + "'" + ','
                            new_str = new_str + '告警时间' + "'" + j['alarm_time'] + "'"
                            new_str += '||'
                            alarm_text += new_str
                        new_list.append(alarm_text)
                    else:
                        monitor = ''
                        new_list.append(monitor)
                    # 其他监控信息(非‘有监控有报警’时可能会有)
                    monitor_info = event2.monitor_info
                    if monitor_info == None:
                        new_list.append('')
                    elif '{' in monitor_info:
                        monitor_info = eval(monitor_info)
                        if monitor_info.has_key('notbkalarminfo'):
                            new_list.append(monitor_info['notbkalarminfo'])
                        elif monitor_info.has_key('havemonitorinfo'):
                            new_list.append(monitor_info['havemonitorinfo'])
                        elif monitor_info.has_key('notmonitorinfo'):
                            new_list.append(monitor_info['notmonitorinfo'])
                    else:
                        new_list.append('')
                else:
                    new_list.append('')
                    new_list.append('')
                    new_list.append('')
                    new_list.append('')
                    new_list.append('')

                event3_list = UrgencyMeasure.objects.filter(event_number=i)
                # event33_list = []
                # for z in event3_list:
                #     event33_list.append(z[0])
                if event3_list:
                    event3 = UrgencyMeasure.objects.get(event_number=i)
                    # 应急方案
                    new_list.append(event3.urgency_info if event3.urgency_info else '')
                    # 应急方案自动化情况
                    auto=event3.urgency_auto_info
                    if auto:
                        if auto == '4':
                            auto=u'已自动化'
                        elif auto == '8':
                            auto = u'已自动化(非一体化平台)'
                        elif auto == '5':
                            auto = u'不可自动化'
                        elif auto == '6':
                            auto = u'未自动化'
                    else:
                        auto = ''
                    new_list.append(auto)
                    # 自动化所属系统
                    new_list.append(event3.auto_sys if event3.auto_sys else '')
                    # 自动化方案
                    new_list.append(event3.script_name if event3.script_name else '')
                    auto_info = event3.auto_info
                    # 其他自动化信息(非‘已自动化’情况下可能会有)
                    if auto_info == None:
                        auto_info = ''
                    elif '{' in auto_info:
                        auto_info = eval(auto_info)
                        if auto_info.has_key('notbkautoinfo'):
                            auto_info = auto_info['notbkautoinfo']
                        elif auto_info.has_key('cantautoinfo'):
                            auto_info = auto_info['cantautoinfo']
                        elif auto_info.has_key('notautoyetinfo'):
                            auto_info = auto_info['notautoyetinfo']
                        else:
                            auto_info = ''
                    else:
                        auto_info = ''
                    new_list.append(auto_info)
                else:
                    new_list.append('')
                    new_list.append('')
                    new_list.append('')
                    new_list.append('')
                    new_list.append('')

                data_list.append(new_list)

        # 创建工作簿
        workbook = xlwt.Workbook(encoding='utf-8')
        # 创建sheet
        data_sheet = workbook.add_sheet('demo')
        # 填写表头信息
        row0 = ['事件编号', '事件状态', '处理人', '事件摘要', '紧急变更单号', '事件发生时间', '用户报障事件',
                '受理时间', '故障恢复时间', '故障系统名', '受影响系统名', '事件类型', '现象',
                '一级分类', '二级分类', '三级分类', '故障原因初步分析', '影响度', '优先级',
                '紧急度', '报告来源', '处理过程', '根因分析', '解决方案措施', '故障表象',
                '故障实质现象', '相关告警','告警实例', '其他监控信息', '应急方案', '应急方案自动化',
                '自动化所属系统', '自动化方案', '其他自动化信息']
        for i in range(len(row0)):
            data_sheet.write(0, i, row0[i], set_style(u'宋体', 220, True))

        a = 1
        while True:
            for i in range(len(row0)):
                data_sheet.write(a, i, data_list[0][i], set_style(u'宋体', 220, False))
            data_list.pop(0)
            a += 1
            if len(data_list) == 0:
                break
        file_name = u'事件信息.xls'
        save_path = file_name
        workbook.save(save_path)
        return render_json(
            {
                "result": True,
                "code": 0,
                "message": u"生成文件成功",
                "data": 1
            }
        )
    except Exception as e:
        return render_json({
            "result": False,
            "code": 1,
            "message": u"未知错误:%s" % e,
            "data": {}
        })


# 下载导出文件
def download(request):
    file_name = u'事件信息.xls'
    file = open(file_name, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="事件信息.xls"'
    return response


# 蓝鲸自动化接口
def auto(request):
    try:
        client = get_client_by_request(request)
        bk_token = request.COOKIES.get('bk_token')
        client.set_bk_api_ver('v2')
        app_list = get_app_by_user(request.COOKIES['bk_token'])
        for x in app_list:
            if x.get("app_name") == u'\u8d44\u6e90\u6c60' or x.get("app_name") == 'Resource pool':
                app_list.remove(x)
                break
        data_dict = {}
        platform_list = []
        business_name = {}
        for i in app_list:
            new_dic = {}
            new_dic['value'] = i['app_id']
            new_dic['label'] = i['app_name']
            business_name[i['app_id']] = i['app_name']
            platform_list.append(new_dic)
        data_dict['plat_form'] = platform_list

        bizId_list = []
        for i in app_list:
            bizId_list.append(i['app_id'])
        job_list = []

        for i in bizId_list:
            parse = {
                'bk_token': bk_token,
                'bk_app_code': APP_ID,
                'bk_app_secret': APP_TOKEN,
                "bk_biz_id": i
            }
            result = client.job.get_job_list(parse)
            new_dic = {}
            if isinstance(result['data'], list):
                if len(result['data']) != 0:
                    new_list = []
                    for x in enumerate(result['data']):
                        new_dict = {}
                        new_dict['value'] = x[0]
                        new_dict['label'] = x[1]['name']
                        new_list.append(new_dict)
                    new_dic['value'] = business_name[i]
                    new_dic['label'] = new_list
                    job_list.append(new_dic)
            else:
                job_list.append({"value": i, "label": [{"value": 1, "label": "无"}]})
        data_dict['job_list'] = job_list
        return render_json(
            {
                "result": True,
                "code": 0,
                "message": u"对接自动化平台成功",
                "data": data_dict
            }
        )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }

        )


# 一级事件和事件初步原因分析级联接口
def firstcate_analysis(request):
    event_pri_analysis_dict = {}
    try:
        category_analysis_list = FailureCateReason.objects.all()
        first_list = []
        for category_analysis in category_analysis_list:
            if category_analysis.first_event_category not in first_list:
                first_list.append(category_analysis.first_event_category)
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"一级分类事件查询失败:%s" % e,
                "data": {}
            }
        )
    # 一级分类和事件初步原因分析的关系
    for first_event in first_list:
        try:
            failure_primary_analysis_list = []
            choose_list = FailureCateReason.objects.filter(first_event_category=first_event)
            for choose in choose_list:
                if choose.failure_reason_primary_analysis not in failure_primary_analysis_list:
                    failure_primary_analysis_list.append(choose.failure_reason_primary_analysis)
            event_pri_analysis_dict[first_event] = failure_primary_analysis_list
        except Exception as e:
            return render_json(
                {
                    "result": False,
                    "code": 1,
                    "message": u"一级事件对应的事件初步原因分析查询失败:%s" % e,
                    "data": {}
                }
            )
    total_list = [first_list, event_pri_analysis_dict]
    return render_json({
        "result": True,
        "code": 0,
        "message": u"事件一级以及初步原因分析查询成功",
        "data": total_list
    })


# 查询告警实例
def search(request):
    try:
        req = json.loads(request.body)
        req = req['failure_analysis']
        if req.has_key('alarm_type') and req['alarm_type']:
            alarm_type = req['alarm_type']

        if req.has_key('host_computer') and req['host_computer']:
            host_computer = req['host_computer']
        else:
            host_computer = ''

        if req.has_key('key_word') and req['key_word']:
            key_word = req['key_word']
        else:
            key_word = ''

        if req.has_key('system_code') and req['system_code']:
            system_code = req['system_code']
        else:
            system_code = ''

        if req.has_key('start_time') and req['start_time']:
            start_time = req['start_time']
            start_time = time.strptime(start_time, "%Y-%m-%d %H:%M:%S")
            start_time = time.mktime(start_time)
            start_time = str(int(round(start_time*1000)))

        if req.has_key('end_time') and req['end_time']:
            end_time = req['end_time']
            end_time = time.strptime(end_time, "%Y-%m-%d %H:%M:%S")
            end_time = time.mktime(end_time)
            end_time = str(int(round(end_time * 1000)))

        wb_data = requests.get(
            'http://192.168.30.6:8080/webserver/externalapi/getAlarmInfoList.do?sysCode='+system_code+'&keyword='+key_word+'&startTime='+start_time+'&endTime='+end_time+'&hostName='+host_computer+'&pageNo=1&pageSize=40&alarmType='+alarm_type+'&sortOrder=DESC')
        # 国泰生产：10.240.1.72:8099，webserver
        # 国泰测试：10.189.161.104:8080
        # 公司环境：192.168.1.153:8088， webserver-guotai
        wb_data = wb_data.text
        wb_data = eval(wb_data)
        wb_data = wb_data['data']['message']
        data_list = []
        for i in wb_data:
            new_dict = {}
            new_dict['alarm_info']= i['content']
            new_dict['alarm_title'] = i['title']
            alarm_time = i['extFields']['alarmtime'][:19]
            alarm_time = alarm_time.replace('T', ' ')
            new_dict['alarm_time'] = alarm_time
            data_list.append(new_dict)
        return render_json({
            "result": True,
            "code": 0,
            "message": u"搜索成功",
            "data": data_list

        })
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


# 将告警显示在页面上
def save(request):
    result = json.loads(request.body)
    req = result["alarmList"]
    event_number = result["event_number"]
    event_numberList = FailureAnalysis.objects.filter(event_number=event_number)
    if event_numberList:
        monitor_src = event_numberList[0].monitor_src
        monitor_src = monitor_src.encode('utf-8')
        monitor_src = eval(monitor_src)
        for alarm in req:
            if alarm not in monitor_src:
                monitor_src.append(alarm)
    else:
        monitor_src = req
    return render_json({
        "result": True,
        "code": 0,
        "message": "获取筛选数据成功",
        "data": monitor_src,
    })


# 故障系统、受影响系统、查告警系统
def system(request):
    system = Syetem.objects.all()
    systemList = []
    for i in system:
        newdic = {}
        newdic['label'] = i.systemname
        newdic['value'] = i.systemcode
        systemList.append(newdic)
    return render_json({
        "result": True,
        "code": 0,
        "message": u"搜索成功",
        "data": systemList
    })


# 获取监控
def get_alarm_info(request):
    try:
        total_alarm_info = []
        alarm_data = requests.get('http://192.168.30.6:8080/webserver/alarmrule/getAlarmRules.do?ruletype=1&state=1&scene=use')
        alarm_data = alarm_data.text
        alarm_data = alarm_data.replace('null', '1')
        alarm_data = eval(alarm_data)
        alarm_data = alarm_data['data']
        for i in alarm_data:
            newDic = {}
            newDic['label'] = i['title']
            newDic['value'] = i['title']
            total_alarm_info.append(newDic)

        alarm_data2 = requests.get('http://192.168.30.6:8080/webserver/alarmrule/getAlarmRules.do?ruletype=2&state=1&scene=use')
        # 10.240.1.72:8099
        alarm_data2 = alarm_data2.text
        alarm_data2 = alarm_data2.replace('null', '1')
        alarm_data2 = eval(alarm_data2)
        alarm_data2 = alarm_data2['data']
        for i in alarm_data2:
            newDic = {}
            newDic['label'] = i['title']
            newDic['value'] = i['title']
            total_alarm_info.append(newDic)

        return render_json({
            "result": True,
            "code": 0,
            "message": u"搜索成功",
            "data": total_alarm_info
        })
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def get_cc_module_tree(request):
    """
    获取主机树
    :param request:
    :return:
    """
    client = get_client_by_request(request)
    client.set_bk_api_ver('v2')
    biz_id = request.body
    # 查询拓扑
    kwargs = {
        "bk_supplier_account": "0",
        "bk_biz_id": biz_id,
        'level': -1
    }
    res = client.cc.search_biz_inst_topo(kwargs)
    if res and res.get('result'):
        tree_data = get_biz_module_tree(res.get('data')[0]['child'], [], 0)
        return render_json(
            {
                "result": True,
                "code": 0,
                "message": u"查询成功",
                "data": tree_data
            })
    else:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"查询出错",
                "data": {}
            })


def search_host_by_module(request):
    """
    通过所属模块查询对应的主机
    :param request:
    :return:
    """
    client = get_client_by_request(request)
    client.set_bk_api_ver('v2')
    if not request.body:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未传递参数",
                "display": {}
            })
    req = json.loads(request.body)
    bk_biz_id = req.get("bizID")
    if not bk_biz_id:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未选择业务",
                "display": {}
            })
    bk_module_id = req.get("moduleID")
    if not bk_module_id:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未选择模块id",
                "display": {}
            })
    display_list = []
    bk_module_id = int(bk_module_id.split(":")[-1])
    param = {
        'bk_biz_id': bk_biz_id,
        'condition': [{
            "bk_obj_id": "module",
            "fields": [],
            "condition": [{
                    "field": "bk_module_id",
                    "operator": "$eq",
                    "value": bk_module_id
                }]
        }, ]
    }
    res = client.cc.search_host(param)
    if res.get('result', False):
        bk_host_list = res.get('data').get('info')
        if not bk_host_list:
            return render_json(
                {
                    "result": True,
                    "code": 0,
                    "message": u"主机列表为空",
                    "data": {"display": {}}
                })
    else:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"访问蓝鲸CMDB失败",
                "display": {}
            })
    agent_ip = []
    biz_host_arr = []
    for host in bk_host_list:
        temp = {
            'ip': host['host']['bk_host_innerip'],
            'bk_cloud_id': host['host']['bk_cloud_id'][0]['bk_inst_id']
        }
        data = {
            'bk_host_innerip': host['host']['bk_host_innerip'],
            'bk_host_name': host['host']['bk_host_name'],
            'bk_os_type': host['host']['bk_os_type'],
            'bk_cloud_id': host['host']['bk_cloud_id'][0]['bk_inst_id'],
            'bk_cloud_name': host['host']['bk_cloud_id'][0]['bk_inst_name'],
        }
        agent_ip.append(temp)
        biz_host_arr.append(data)
    agent_param = {
        'bk_supplier_id': "0",
        "hosts": agent_ip
    }
    agent_result = client.gse.get_agent_status(agent_param).get("data")
    for agent in biz_host_arr:
        key = str(agent.get("bk_cloud_id")) + ":" + agent.get("bk_host_innerip")
        agent["status"] = 0
        if agent_result[key]['bk_agent_alive'] != 0:
            agent["status"] = 1
        display_list.append(agent)
    return render_json(
        {
            "result": True,
            "code": 0,
            "message": u"查询成功",
            "data": display_list
        })


def get_biz_module_tree(child_dict, tree, count):
    """
    创建cmdb拓扑树
    :param child_dict:子节点树
    :param tree:返回的树的数据
    :param count:为了防止蓝鲸出现id一样的情况做区分
    :return:
    """
    if child_dict:
        for child in child_dict:
            temp_dict = {}
            if child["bk_obj_id"] == "set":
                temp_dict['id'] = 'children' + str(count) + ':' + str(child['bk_inst_id'])
                count += 1
                temp_dict['label'] = child['bk_inst_name']
                temp_childs = child.get('child')
                if temp_childs:
                    childrens = []
                    for temp_child in temp_childs:
                        childrens.append({"id": 'children' + str(count) + ':' + str(temp_child['bk_inst_id']),
                                          "label": temp_child['bk_inst_name']})
                    temp_dict["children"] = childrens
                tree.append(temp_dict)
            else:
                count += 1
                get_biz_module_tree(child['child'], tree, count)
            count += 1

        return tree
    else:
        return None


# 新建标签
def create_label(request):
    try:
        labelName = request.body
        name = Label.objects.filter(label_name=labelName)
        if name:
            return render_json(
                {
                    "result": False,
                    "code": 1,
                    "message": u"该标签已存在！",
                    "data": ''
                }
            )
        label = Label.objects.create(label_name=labelName)
        label.save()
        return render_json(
            {
                "result": True,
                "code": 0,
                "message": u"标签保存成功！",
                "data": ''
            }
        )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


# 获取所有标签
def get_label(request):
    try:
        label_list = []
        labels = Label.objects.all()
        if labels:
            for i in labels:
                label_list.append({'label': i.label_name, 'value': i.id})
            return render_json(
                {
                    "result": True,
                    "code": 0,
                    "message": u"标签查询成功！",
                    "data": label_list
                }
            )
        else:
            return render_json(
                {
                    "result": False,
                    "code": 1,
                    "message": u"还未有标签",
                    "data": ''
                }
            )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


# 删除标签
def del_label(request):
    try:
        labelName = request.body
        label = Label.objects.filter(label_name=labelName)
        if label:
            label = label[0]
            label.delete()
            return render_json(
                {
                    "result": True,
                    "code": 0,
                    "message": u"标签删除成功！",
                    "data": ''
                }
            )
        else:
            return render_json(
                {
                    "result": False,
                    "code": 1,
                    "message": u"删除失败！",
                    "data": {}
                }
            )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def search_user_group(request):
    try:
        gruop_data = requests.get('http://192.168.1.246:8001/webapi/relationshipInstances/172?pageNum=1&pageSize=100')
        gruop_data = gruop_data.text
        gruop_data = json.loads(gruop_data)
        gruop_data = gruop_data['data']['list']
        group_list = []
        group_user_list = []
        group_system_list = []
        for i in gruop_data:
            groupDic = {}
            groupDic['label'] = i[u'名称']
            groupDic['value'] = i[u'名称']
            group_list.append(groupDic)
            for j in i['relationshipInstance']:
                if j['ralationshipModule'] == u'支持人员':
                    userDic = {'group_name': i[u'名称'],'group_user': []}
                    for user in j['relationshipInstance']:
                        userDic['group_user'].append(user[u'名称'])
                    group_user_list.append(userDic)
                elif j['ralationshipModule'] == u'应用子系统':
                    systemDic = {'group_name': i[u'名称'],'group_system': []}
                    for system in j['relationshipInstance']:
                        systemDic['group_system'].append(system[u'名称'])
                    group_system_list.append(systemDic)
        return render_json({
            "result": True,
            "code": 0,
            "message": u"搜索成功",
            "data": {'group_list':group_list, 'group_user_list':group_user_list,'group_system_list':group_system_list}
        })
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def create_alarm(request):
    try:
        data = request.body
        data = eval(data)
        alarm_type = data['alarm_type']
        alarm_system = data['alarm_system']
        alarm_time = data['alarm_time']
        recover_time = data['recover_time']
        alarm_summary = data['alarm_summary']
        if_interpose = data['if_interpose']
        solve_process = data['solve_process']
        if_workday = data['if_workday']
        if_auto = data['if_auto']
        auto_sysname = data['auto_sysname']
        auto_name = data['auto_name']
        cant_auto_info = data['cantautoinfo']
        other_autoname = data['other_autoname']
        monitor_name = data['monitor_name']
        if_icube = data['if_icube']
        time = alarm_time.replace('T', ' ')
        time = time[0:-5]
        time = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
        time = (time + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
        time = time.replace('-', '')
        time = time.replace(' ', '')
        time = time.replace(':', '')
        alarm_number = 'alarm_' + time
        alarm_time = alarm_time.replace('T', ' ')
        alarm_time = alarm_time[0:-5]
        alarm_time = datetime.datetime.strptime(alarm_time, "%Y-%m-%d %H:%M:%S")
        alarm_time = (alarm_time + datetime.timedelta(hours=8))
        recover_time = recover_time.replace('T', ' ')
        recover_time = recover_time[0:-5]
        recover_time = datetime.datetime.strptime(recover_time, "%Y-%m-%d %H:%M:%S")
        recover_time = (recover_time + datetime.timedelta(hours=8))

        client = get_client_by_request(request)
        bk_token = request.COOKIES.get('bk_token')
        client.set_bk_api_ver('v2')
        parse = {'bk_token': bk_token, 'bk_app_code': APP_ID, 'bk_app_secret': APP_TOKEN}
        result = client.bk_login.get_user(parse)
        login_person = result['data']['chname']

        if_exit = Error_alarm.objects.filter(alarm_number__contains=alarm_number)
        alarm_number = alarm_number+'_'+str(len(if_exit))


        error_alarm = Error_alarm.objects.create(
            alarm_number = alarm_number,
            alarm_summary = alarm_summary,
            alarm_level = alarm_type,
            alarm_system = alarm_system,
            alarm_happen_time = alarm_time,
            alarm_recover_time = recover_time,
            if_interpose = if_interpose,
            solve_process = solve_process,
            if_workday = if_workday,
            if_auto = if_auto,
            auto_sysname = auto_sysname,
            auto_name = auto_name,
            other_autoname = other_autoname,
            monitor_name = monitor_name,
            if_icube = if_icube,
            cant_auto_info = cant_auto_info,
            user = login_person
        )
        error_alarm.save()
        return render_json(
            {
                "result": True,
                "code": 0,
                "message": u"预警新建成功！",
                "data": ''
            }
        )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def edit_alarm_display(request):
    try:
        req = json.loads(request.body)
        alarm_number = req['alarm_number']
        alarm = Error_alarm.objects.get(alarm_number=alarm_number)
        client = get_client_by_request(request)
        bk_token = request.COOKIES.get('bk_token')
        client.set_bk_api_ver('v2')
        parse = {'bk_token': bk_token, 'bk_app_code': APP_ID, 'bk_app_secret': APP_TOKEN}
        result = client.bk_login.get_user(parse)
        login_person = result['data']['chname']
        if login_person == alarm.user:
            show_src = 0
        else:
            show_src = 1

        data = {
            'alarm_type':alarm.alarm_level if alarm.alarm_level else '',
            'alarm_system':eval(alarm.alarm_system) if alarm.alarm_system else '',
            'alarm_time': alarm.alarm_happen_time.strftime('%Y-%m-%d %H:%M:%S') if alarm.alarm_happen_time else '',
            'recover_time': alarm.alarm_recover_time.strftime('%Y-%m-%d %H:%M:%S') if alarm.alarm_recover_time else '',
            'alarm_summary': alarm.alarm_summary if alarm.alarm_summary else '',
            'if_interpose': int(alarm.if_interpose) if alarm.if_interpose else '',
            'solve_process': alarm.solve_process if alarm.solve_process else '',
            'if_workday': int(alarm.if_workday) if alarm.if_workday else '',
            'if_auto': int(alarm.if_auto) if alarm.if_auto else '',
            'auto_sysname': alarm.auto_sysname if alarm.auto_sysname else '',
            'auto_name': alarm.auto_name if alarm.auto_name else '',
            'other_autoname': alarm.other_autoname if alarm.other_autoname else '',
            'monitor_name': alarm.monitor_name if alarm.monitor_name else '',
            'if_icube': int(alarm.if_icube) if alarm.if_icube else '',
            'show_src': show_src,
            'cantautoinfo': alarm.cant_auto_info if alarm.cant_auto_info else ''
        }
        return render_json(
            {
                "result": True,
                "message": u"查询数据成功",
                "code": 0,
                "results": data,
            }
        )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def edit_alarm(request):
    try:
        req = json.loads(request.body)
        data = req['info']
        alarm_number = req['number']
        alarm_type = data['alarm_type']
        alarm_system = data['alarm_system']
        alarm_time = data['alarm_time']
        recover_time = data['recover_time']
        alarm_summary = data['alarm_summary']
        if_interpose = data['if_interpose']
        solve_process = data['solve_process']
        if_workday = data['if_workday']
        if_auto = data['if_auto']
        auto_sysname = data['auto_sysname']
        auto_name = data['auto_name']
        other_autoname = data['other_autoname']
        monitor_name = data['monitor_name']
        cant_auto_info = data['cantautoinfo']
        if_icube = data['if_icube']
        alarm_time = alarm_time.replace('T', ' ')
        # alarm_time = alarm_time[0:-5]
        alarm_time = datetime.datetime.strptime(alarm_time, "%Y-%m-%d %H:%M:%S")
        alarm_time = (alarm_time + datetime.timedelta(hours=8))
        recover_time = recover_time.replace('T', ' ')
        # recover_time = recover_time[0:-5]
        recover_time = datetime.datetime.strptime(recover_time, "%Y-%m-%d %H:%M:%S")
        recover_time = (recover_time + datetime.timedelta(hours=8))

        alarm = Error_alarm.objects.get(alarm_number=alarm_number)
        alarm.alarm_number = alarm_number
        alarm.alarm_level = alarm_type
        alarm.alarm_system = alarm_system
        alarm.alarm_happen_time = alarm_time
        alarm.alarm_recover_time = recover_time
        alarm.alarm_summary = alarm_summary
        alarm.if_interpose = if_interpose
        alarm.solve_process = solve_process
        alarm.if_workday = if_workday
        alarm.if_auto = if_auto
        alarm.auto_sysname = auto_sysname
        alarm.auto_name = auto_name
        alarm.other_autoname = other_autoname
        alarm.monitor_name = monitor_name
        alarm.if_icube = if_icube
        cant_auto_info = cant_auto_info
        alarm.save()
        return render_json(
            {"result": True,
             "code": 0,
             "message": u"编辑成功！",
             "data": ''
             })
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def del_alarm(request):
    try:
        id = json.loads(request.body)
        alarm_number = id['alarm_number']
        alarm = Error_alarm.objects.filter(alarm_number=alarm_number)
        if alarm:
            alarm = alarm[0]
            alarm.delete()
            return render_json(
            {"result": True,
                "code": 0,
                "message": u"预警删除成功！",
                "data": ''
            })
        else:
            return render_json(
                {
                    "result": False,
                    "code": 1,
                    "message": u"删除失败！",
                    "data": {}
                }
            )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def create_alarm_by_icube(request):
    try:
        req = json.loads(request.body)
        client = get_client_by_request(request)
        bk_token = request.COOKIES.get('bk_token')
        client.set_bk_api_ver('v2')
        parse = {'bk_token': bk_token, 'bk_app_code': APP_ID, 'bk_app_secret': APP_TOKEN}
        result = client.bk_login.get_user(parse)
        login_person = result['data']['chname']
        for i in req['info']:
            time = i['alarm_time']
            time = time.replace('-', '')
            time = time.replace(' ', '')
            time = time.replace(':', '')
            alarm_number = 'alarm_' + time
            if_exit = Error_alarm.objects.filter(alarm_number__contains=alarm_number)
            alarm_number = alarm_number + '_' + str(len(if_exit))
            alarm_time = i['alarm_time']
            alarm_time = datetime.datetime.strptime(alarm_time, "%Y-%m-%d %H:%M:%S")
            system = req['system']
            system = Syetem.objects.get(systemcode=system)
            alarm_system = [system.systemname]
            error_alarm = Error_alarm.objects.create(
                alarm_number=alarm_number,
                alarm_summary=i['alarm_info'],
                alarm_level='',
                alarm_system=alarm_system,
                alarm_happen_time=alarm_time,
                alarm_recover_time=alarm_time,
                if_interpose='',
                solve_process='',
                if_workday='',
                if_auto='',
                auto_sysname='',
                auto_name='',
                other_autoname='',
                monitor_name='',
                if_icube='8',
                user=login_person
            )
            error_alarm.save()
        return render_json(
            {"result": True,
             "code": 0,
             "message": u"预警新建成功！",
             "data": ''
             })
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def search_alarm(request):
    try:
        req = json.loads(request.body)
        alarm_list = Error_alarm.objects.all().order_by('-alarm_happen_time')
        if req['data']['alarm_system']:
            alarm_list = alarm_list.filter(alarm_system__contains=req['data']['alarm_system'])
        if req['data']['priority']:
            alarm_list = alarm_list.filter(alarm_level=req['data']['priority'])

        if req['dateoutinfo']:
            hptime_choose = req['dateoutinfo']
            startTime = hptime_choose[0]
            startTime = datetime.datetime.strptime(startTime, "%Y-%m-%d")
            startTime = (startTime + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
            # endTime = hptime_choose[1]
            # endTime = datetime.datetime.strptime(endTime[0:10], "%Y-%m-%d")
            # endTime = (endTime + datetime   timedelta(days=1)).strftime("%Y-%m-%d")
            # eventList = eventList.filter(event_happened_time__gte=startTime).filter(
            #     event_happened_time__lte=endTime)

        if req['data']['alarm_number']:
            alarm_list = alarm_list.filter(alarm_number__contains=req['data']['alarm_number'])

        if request.body == "":
            current_page = 1
            page_size = 10
        else:
            current_page = req.get("currentPage", 1)
            page_size = req.get("pageSize", 10)
        event_page = Paginator(alarm_list, page_size)
        event_list = event_page.page(current_page).object_list

        result_list = []
        for i in event_list:
            # alarm_system = i.alarm_system
            data = {
                "alarm_number": i.alarm_number,
                'alarm_summary': i.alarm_summary,
                'alarm_level': i.alarm_level,
                'alarm_system': eval(i.alarm_system),
                'user': i.user
            }
            result_list.append(data)
        return render_json(
            {
                "result": True,
                "message": u"查询数据成功",
                "code": 0,
                "results": {'results': result_list, 'count': event_page.count, 'currentPage': current_page},
            }
        )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def alarm_count_info(request):
    try:
        req = json.loads(request.body)
        sysList = req.get('syslist')
        alarm_list = Error_alarm.objects.all()
        result = {}
        for alarm in alarm_list:
            sys_list = eval(alarm.alarm_system)
            for sys in sys_list:
                if result.has_key(sys):
                    pass
                else:
                    result[sys] = {'bad_work':0,'main_work':0,'normal_work':0,
                                    'bad_weekend':0,'main_weekend':0,'normal_weekend':0}
                if alarm.alarm_level == u'严重' and alarm.if_workday == u'3':
                    result[sys]['bad_work'] += 1
                elif alarm.alarm_level == u'主要' and alarm.if_workday == u'3':
                    result[sys]['main_work'] += 1
                elif alarm.alarm_level == u'次要' and alarm.if_workday == u'3':
                    result[sys]['normal_work'] += 1
                elif alarm.alarm_level == u'严重' and alarm.if_workday == u'4':
                    result[sys]['bad_weekend'] += 1
                elif alarm.alarm_level == u'主要' and alarm.if_workday == u'4':
                    result[sys]['main_weekend'] += 1
                elif alarm.alarm_level == u'次要' and alarm.if_workday == u'4':
                    result[sys]['normal_weekend'] += 1
        data_list = []
        for key,value in result.items():
            total = 0
            for v in value.values():
               total += v
            dic = {
                "system":key,
                "total":total,
                "bad_work":value["bad_work"],
                "main_work":value["main_work"],
                "normal_work": value["normal_work"],
                "bad_weekend": value["bad_weekend"],
                "main_weekend": value["main_weekend"],
                "normal_weekend": value["normal_weekend"],
            }
            data_list.append(dic)

        if request.body == "":
            current_page = 1
            page_size = 10
        else:
            current_page = req.get("currentPage", 1)
            page_size = req.get("pageSize", 10)
        event_page = Paginator(data_list, page_size)
        event_list = event_page.page(current_page).object_list
        return render_json(
            {
                "result": True,
                "code": 0,
                "message": u"查询成功！",
                "data": {'results': data_list, 'count': event_page.count, 'currentPage': current_page}
            }
        )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )


def monitor_excel(request):
    try:
        # req = json.loads(request.body)
        user_list = [u'叶飞']
        event_list = EventInfo.objects.all()

        total = 0
        have_alarm = 0
        have_auto = 0

        for i in user_list:
            event_total = event_list.filter(processing_person=i)
            total += len(event_total)
            event_number_list = []
            for j in event_total:
                event_number_list.append(j.event_number)
            for number in event_number_list:
                event_alarm = FailureAnalysis.objects.get(event_number=number)
                if event_alarm.related_alarm_info == u'1' or event_alarm.related_alarm_info == u'7' or event_alarm.related_alarm_info == u'2':
                    have_alarm += 1
                event_auto = UrgencyMeasure.objects.get(event_number=number)
                if event_auto.urgency_auto_info == u'4' or event_auto.urgency_auto_info == u'8':
                    have_auto += 1

        alarmNumber = (float(have_alarm)/float(total))*100
        autoNumber = (float(have_auto)/float(total))*100


        workbook = xlwt.Workbook(encoding='utf-8')
        data_sheet = workbook.add_sheet('demo')
        row0 = ['行政组名','事件总数','监控有效性','故障处理自动化率']
        for i in range(4):
            data_sheet.write(0, i, row0[i], set_style(u'宋体', 220, True))

        data_list = [u'组',str(total),u'50',u'30']
        for i in range(4):
            data_sheet.write(1, i, data_list[i], set_style(u'宋体', 220, False))

        workbook.save(u'统计报表.xls')
        return render_json(
            {
                "result": True,
                "message": u"查询数据成功",
                "code": 0,
                "results": {},
            }
        )
    except Exception as e:
        return render_json(
            {
                "result": False,
                "code": 1,
                "message": u"未知错误:%s" % e,
                "data": {}
            }
        )



# 同步事件
def sync(request):
    now_time = int(time.time())
    db_remote = pymssql.connect('10.240.1.130', 'InterfaceUser', 'InterfaceUser', 'ARSystem', charset='utf8')

    if os.path.exists('hpd_result.txt'):
        judge = 1
        with open('hpd_result.txt', 'r') as f:
            closed_data = f.read()
            closed_data = int(closed_data)
    else:
        judge = 0

    cursor_hpd = db_remote.cursor()

    with open('hpd_result.txt', 'w') as f:
        f.write(str(now_time))
    if not judge:
        hpd_sql = """select
        Incident_Number,--事件编号
        people1.Last_Name,--用户
        people1.cChr_OAUser,--用户OAID
        people1.Organization,--部门
        Phone_Number,--电话
        dateadd(s,cDate_start,'1970-01-01 08:00:00') startdate,--事件发生时间
        dateadd(s,cDat_HappenedDate,'1970-01-01 08:00:00') happeneddate,--用户报障时间
        dateadd(s,Last_Resolved_Date,'1970-01-01 08:00:00') resolveddate,--受理时间
        dateadd(s,cDat_ResumeDate,'1970-01-01 08:00:00') resumedate,--故障恢复时间
        dateadd(s,hpd.Submit_Date,'1970-01-01 08:00:00') createdate,--记录日期
        dateadd(s,hpd.Last_Modified_Date,'1970-01-01 08:00:00') modifydate,--最后修改日期
        cChr_BelongSystemName,--故障系统名称
        cChr_SystemName,--受影响系统名称
        cChr_IncidentType,--事件类型
        Description,--摘要
        Detailed_Decription,--现象
        Categorization_Tier_1,--一级分类
        Categorization_Tier_2,--二级分类
        Categorization_Tier_3,--三级分类
        case Impact --影响度
        when 1000 then '高'
        when 2000 then '中'
        when 3000 then '低'
        when 4000 then '无'
        end Impact,
        case Urgency --紧急度
        when 1000 then '高'
        when 2000 then '中'
        when 3000 then '低'
        end Urgency,
        case Priority --优先级
        when 0 then '5级'
        when 1 then '4级'
        when 2 then '3级'
        when 3 then '2级'
        when 4 then '1级'
        end Priority,
        case Reported_Source --报告来源
        when 1000 then '电话'
        when 1500 then '微信'
        when 2000 then 'QQ群'
        when 6000 then '机房人工巡检'
        when 8000 then '人工监控'
        when 9000 then '程序自动监控'
        when 11000 then '其它'
        end Reported_Source,
        case Status_Reason --状态理由
        when 14000 then '已取消'
        when 81000 then '重复开单'
        when 91000 then '成功处理-转变更'
        when 94000 then '成功处理-转问题'
        when 96000 then '成功处理'
        end Status_Reason,
        Assigned_Group,--处理组
        Assignee, --处理人
        Assignee_Login_ID, --处理人OAID
        cInt_FaultHour,--实际解决用时(小时)
        cInt_FaultMuitm,--实际解决用时(分钟)
        cInt_solutionHour,--故障恢复用时(小时)
        cInt_solutionMinute,--故障恢复用时(分钟)
        cInt_AvailableHour,--可用性影响时间(小时)
        cInt_AvailableMinute,--可用性影响时间(分钟)
        Resolution,--处理方案
        Incident_Reason,--故障原因初步分析
        cChr_IncidentResult,--故障导致影响
        cChr_IncidentEP--应急预案场景类型

        from HPD_Help_Desk hpd
        left join CTM_People people1
        on hpd.Person_ID = people1.Person_ID
        where status = 5 and hpd.Last_Modified_Date < %i
        order by Incident_Number desc
        """ % now_time
    else:
        hpd_sql = """select
                Incident_Number,--事件编号
                people1.Last_Name,--用户
                people1.cChr_OAUser,--用户OAID
                people1.Organization,--部门
                Phone_Number,--电话
                dateadd(s,cDate_start,'1970-01-01 08:00:00') startdate,--事件发生时间
                dateadd(s,cDat_HappenedDate,'1970-01-01 08:00:00') happeneddate,--用户报障时间
                dateadd(s,Last_Resolved_Date,'1970-01-01 08:00:00') resolveddate,--受理时间
                dateadd(s,cDat_ResumeDate,'1970-01-01 08:00:00') resumedate,--故障恢复时间
                dateadd(s,hpd.Submit_Date,'1970-01-01 08:00:00') createdate,--记录日期
                dateadd(s,hpd.Last_Modified_Date,'1970-01-01 08:00:00') modifydate,--最后修改日期
                cChr_BelongSystemName,--故障系统名称
                cChr_SystemName,--受影响系统名称
                cChr_IncidentType,--事件类型
                Description,--摘要
                Detailed_Decription,--现象
                Categorization_Tier_1,--一级分类
                Categorization_Tier_2,--二级分类
                Categorization_Tier_3,--三级分类
                case Impact --影响度
                when 1000 then '高'
                when 2000 then '中'
                when 3000 then '低'
                when 4000 then '无'
                end Impact,
                case Urgency --紧急度
                when 1000 then '高'
                when 2000 then '中'
                when 3000 then '低'
                end Urgency,
                case Priority --优先级
                when 0 then '5级'
                when 1 then '4级'
                when 2 then '3级'
                when 3 then '2级'
                when 4 then '1级'
                end Priority,
                case Reported_Source --报告来源
                when 1000 then '电话'
                when 1500 then '微信'
                when 2000 then 'QQ群'
                when 6000 then '机房人工巡检'
                when 8000 then '人工监控'
                when 9000 then '程序自动监控'
                when 11000 then '其它'
                end Reported_Source,
                case Status_Reason --状态理由
                when 14000 then '已取消'
                when 81000 then '重复开单'
                when 91000 then '成功处理-转变更'
                when 94000 then '成功处理-转问题'
                when 96000 then '成功处理'
                end Status_Reason,
                Assigned_Group,--处理组
                Assignee, --处理人
                Assignee_Login_ID, --处理人OAID
                cInt_FaultHour,--实际解决用时(小时)
                cInt_FaultMuitm,--实际解决用时(分钟)
                cInt_solutionHour,--故障恢复用时(小时)
                cInt_solutionMinute,--故障恢复用时(分钟)
                cInt_AvailableHour,--可用性影响时间(小时)
                cInt_AvailableMinute,--可用性影响时间(分钟)
                Resolution,--处理方案
                Incident_Reason,--故障原因初步分析
                cChr_IncidentResult,--故障导致影响
                cChr_IncidentEP--应急预案场景类型

                from HPD_Help_Desk hpd
                left join CTM_People people1
                on hpd.Person_ID = people1.Person_ID
                where status = 5 and hpd.Last_Modified_Date >= %i
                order by Incident_Number desc
                """ % closed_data
    cursor_hpd.execute(hpd_sql.decode('utf-8'))
    hpd_results = cursor_hpd.fetchall()
    db_remote.close()
    db_connection = connections['default']

    if hpd_results:
        event_ids = EventInfo.objects.values_list('event_number')
        event_idlist = []
        for event_id in event_ids:
            event_idlist.append(event_id[0])
        for result in hpd_results:
            try:
                if result[0] not in event_idlist:
                    event_info = EventInfo.objects.create(
                        event_number=result[0],
                        user_name=result[1],
                        department=result[3],
                        user_phone=result[4],
                        event_happened_time=result[5],
                        user_reporting_time=result[6],
                        reception_time=result[7],
                        failure_recovery_time=result[8],
                        record_time=result[9],
                        event_last_update_time=result[10],
                        failure_sys_name=result[11],
                        influenced_sys_name=result[12],
                        event_type=result[13],
                        event_summary=result[14],
                        event_phenomenon=result[15],
                        event_first_category=result[16],
                        event_second_category=result[17],
                        event_third_category=result[18],
                        event_impact=result[19],
                        event_urgency=result[20],
                        event_priority=result[21],
                        report_src=result[22],
                        event_state_reason=result[23],
                        processing_group=result[24],
                        processing_person=result[25],
                        processing_person_OAID=result[26],
                        actual_solution_hour=result[27],
                        actual_solution_minute=result[28],
                        failure_recovery_hour=result[29],
                        failure_recovery_minute=result[30],
                        usability_impact_hour=result[31],
                        usability_impact_minute=result[32],
                        event_exec_case=result[33],
                        failure_cause_preliminary_analysis=result[34],
                        failure_created_influence=result[35],
                        emergency_plans_type=result[36],
                        data_src=u"同步",
                        event_analysis_state=u"未分析",
                    )
                    event_info.save()
                else:
                    event = EventInfo.objects.get(event_number=result[0])
                    event.user_name = result[1],
                    event.department = result[3],
                    event.user_phone = result[4],
                    event.event_happened_time = result[5],
                    event.user_reporting_time = result[6],
                    event.reception_time = result[7],
                    event.failure_recovery_time = result[8],
                    event.record_time = result[9],
                    event.event_last_update_time = result[10],
                    event.failure_sys_name = result[11],
                    event.influenced_sys_name = result[12],
                    event.event_type = result[13],
                    event.event_summary = result[14],
                    event.event_phenomenon = result[15],
                    event.event_first_category = result[16],
                    event.event_second_category = result[17],
                    event.event_third_category = result[18],
                    event.event_impact = result[19],
                    event.event_urgency = result[20],
                    event.event_priority = result[21],
                    event.report_src = result[22],
                    event.event_state_reason = result[23],
                    event.processing_group = result[24],
                    event.processing_person = result[25],
                    event.processing_person_OAID = result[26],
                    event.actual_solution_hour = result[27],
                    event.actual_solution_minute = result[28],
                    event.failure_recovery_hour = result[29],
                    event.failure_recovery_minute = result[30],
                    event.usability_impact_hour = result[31],
                    event.usability_impact_minute = result[32],
                    event.event_exec_case = result[33],
                    event.failure_cause_preliminary_analysis = result[34],
                    event.failure_created_influence = result[35],
                    event.emergency_plans_type = result[36],
                    event.data_src = u"同步",
                    event.event_analysis_state = u"未分析",
                    event.save()
            except:
                db_connection.rollback()
    return HttpResponseRedirect('/')