# encoding=utf8
from django.utils.encoding import smart_unicode, DEFAULT_LOCALE_ENCODING
from django.db import connections
from event_analysis.models import *
import pymssql
import os
import random
try:
    line = smart_unicode(DEFAULT_LOCALE_ENCODING)
except UnicodeDecodeError:
    line = ""
import time


    timestamp = int(time.time())
    # sql_connection = connections["sqlserver"]
    sql_connection = pymssql.connect('10.189.63.164', 'InterfaceUser', 'InterfaceUser', 'ARSystem', charset='utf8')
    db_connection = connections["default"]


    ############# 人员信息表的同步
    cursor_userinfo = db_connection.cursor()
    userinfo_sql = "select id from tb_user_info "
    cursor_userinfo.execute(userinfo_sql)
    result_judge = cursor_userinfo.fetchone()

    ctmpeople_sql = "select cChr_OAUser,Remedy_Login_ID,Phone_Number_Mobile,Internet_E_mail,Nick_Name,JobTitle,Last_Name,Organization,Company from CTM_people where cchr_oauser is not null and Last_Modified_Date >=%s-24*60*60 and Last_Modified_Date < %s" % (
        timestamp, timestamp)
    ctmpeople_sql2 = "select cChr_OAUser,Remedy_Login_ID,Phone_Number_Mobile,Internet_E_mail,Nick_Name,JobTitle,Last_Name,Organization,Company from CTM_people where cchr_oauser is not null and Last_Modified_Date <%s;" % timestamp
    cursor_ctm1 = sql_connection.cursor()

    # 如果项目中的数据库表中有数据，表明之前同步过，只需要同步一天数据即可
    if result_judge:
        cursor_ctm1.execute(ctmpeople_sql)
        ctmpeople_results = cursor_ctm1.fetchall()
        if ctmpeople_results:
            for value in ctmpeople_results:
                user_info = UserInfo.objects.create(
                    user_id=value[0],
                    user_department=value[7],
                    remedy_login_id=value[1],
                    phone_number=value[2],
                    user_email=value[3],
                    job_number=value[4],
                    job_position=value[5],
                    user_name=value[6],
                    company=value[8],
                )
                user_info.save()

        else:
            pass
    else:
        cursor_ctm1.execute(ctmpeople_sql2)
        ctmpeople_results2 = cursor_ctm1.fetchall()
        for value in ctmpeople_results2:
            user_info = UserInfo.objects.create(
                user_id=value[0],
                user_department=value[7],
                remedy_login_id=value[1],
                phone_number=value[2],
                user_email=value[3],
                job_number=value[4],
                job_position=value[5],
                user_name=value[6],
                company=value[8],
            )
            user_info.save()

    ########## 事件信息表的同步
    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:
        closed_data = 0
        judge = 0

    cursor_eventinfo = db_connection.cursor()
    # eventinfo_sql = "select id from tb_event_info  "
    # cursor_eventinfo.execute(eventinfo_sql)
    # result_eventinfo_judge = cursor_eventinfo.fetchone()

    hpd1_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 '低'
           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.Closed_Date>=%s and hpd.Closed_Date<%s
           order by Incident_Number desc""" % (closed_data, timestamp)
    hpd2_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 '低'
           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.Closed_Date<=%s
           order by Incident_Number desc
           """ % timestamp
    cursor_hpd1 = sql_connection.cursor()
    hpd_pre_sql = "select Closed_Date from HPD_Help_Desk order by Closed_Date desc"
    cursor_hpd1.execute(hpd_pre_sql)
    pre_touple = cursor_hpd1.fetchone()
    with open('hpd_result.txt', 'w') as f:
        f.write(str(pre_touple[0]))

    # 如果项目中对应的数据库表中有数据
    if judge:
        cursor_hpd1.execute(hpd1_sql)
        hpd1_results = cursor_hpd1.fetchall()
        if hpd1_results:
            for value in hpd1_results:
                try:
                    event_ids = EventInfo.objects.values_list('event_number')
                    event_idlist = []
                    for event_id in event_ids:
                        event_idlist.append(event_id[0])
                    if value[0] not in event_idlist:
                        event_info = EventInfo.objects.create(
                            event_number=value[0],
                            user_name=value[1],
                            department=value[3],
                            user_phone=value[4],
                            event_happened_time=value[5],
                            user_reporting_time=value[6],
                            reception_time=value[7],
                            failure_recovery_time=value[8],
                            record_time=value[9],
                            event_last_update_time=value[10],
                            failure_sys_name=value[11],
                            influenced_sys_name=value[12],
                            event_type=value[13],
                            event_summary=value[14],
                            event_phenomenon=value[15],
                            event_first_category=value[16],
                            event_second_category=value[17],
                            event_third_category=value[18],
                            event_impact=value[19],
                            event_urgency=value[20],
                            event_priority=value[21],
                            report_src=value[22],
                            event_state_reason=value[23],
                            processing_group=value[24],
                            processing_person=value[25],
                            processing_person_OAID=value[26],
                            actual_solution_hour=value[27],
                            actual_solution_minute=value[28],
                            failure_recovery_hour=value[29],
                            failure_recovery_minute=value[30],
                            usability_impact_hour=value[31],
                            usability_impact_minute=value[32],
                            event_exec_case=value[33],
                            failure_cause_preliminary_analysis=value[34],
                            failure_created_influence=value[35],
                            emergency_plans_type=value[36]
                        )
                        event_info.save()
                    else:
                        pass
                except:
                    db_connection.rollback()
        else:
            pass

    else:
        cursor_hpd1.execute(hpd2_sql)
        hpd2_results = cursor_hpd1.fetchall()
        for value in hpd2_results:
            try:
                event_info = EventInfo.objects.create(
                    event_number=value[0],
                    user_name=value[1],
                    department=value[3],
                    user_phone=value[4],
                    event_happened_time=value[5],
                    user_reporting_time=value[6],
                    reception_time=value[7],
                    failure_recovery_time=value[8],
                    record_time=value[9],
                    event_last_update_time=value[10],
                    failure_sys_name=value[11],
                    influenced_sys_name=value[12],
                    event_type=value[13],
                    event_summary=value[14],
                    event_phenomenon=value[15],
                    event_first_category=value[16],
                    event_second_category=value[17],
                    event_third_category=value[18],
                    event_impact=value[19],
                    event_urgency=value[20],
                    event_priority=value[21],
                    report_src=value[22],
                    event_state_reason=value[23],
                    processing_group=value[24],
                    processing_person=value[25],
                    processing_person_OAID=value[26],
                    actual_solution_hour=value[27],
                    actual_solution_minute=value[28],
                    failure_recovery_hour=value[29],
                    failure_recovery_minute=value[30],
                    usability_impact_hour=value[31],
                    usability_impact_minute=value[32],
                    event_exec_case=value[33],
                    failure_cause_preliminary_analysis=value[34],
                    failure_created_influence=value[35],
                    emergency_plans_type=value[36]
                )
                event_info.save()
            except:
                db_connection.rollback()


    ############ 处理人信息表的同步
    cursor_dealerinfo = db_connection.cursor()
    dealerinfo_sql = "select id from tb_dealer_info  "
    cursor_dealerinfo.execute(dealerinfo_sql)
    result_dealerinfo_judge = cursor_dealerinfo.fetchone()

    ctmsupport1_sql = """select
           Company,--公司
           Support_Organization,--组织
           Support_Group_Name,--组
           Full_Name,--姓名
           Login_ID--ID
           from CTM_Support_Group_Assoc_LookUp
           where Status_SGA = 1 AND Status_SGP = 1 and Last_Modified_Date>=%s-24*60*60 and Last_Modified_Date<%s""" % (
        timestamp, timestamp)
    ctmsupport2_sql = """select
           Company,--公司
           Support_Organization,--组织
           Support_Group_Name,--组
           Full_Name,--姓名
           Login_ID--ID
           from CTM_Support_Group_Assoc_LookUp
           where Status_SGA = 1 AND Status_SGP = 1 and Last_Modified_Date<%s""" % timestamp
    cursor_ctmsupport1 = sql_connection.cursor()

    # 如果项目中对应的数据库表中有数据
    if result_dealerinfo_judge:
        cursor_ctmsupport1.execute(ctmsupport1_sql)
        ctmsupport1_results = cursor_ctmsupport1.fetchall()
        if ctmsupport1_results:
            for value in ctmsupport1_results:
                deal_info = DealerInfo.objects.create(
                    dealer_company=value[0],
                    dealer_organization=value[1],
                    dealer_group_name=value[2],
                    dealer_name=value[3],
                    login_id=value[4],

                )
                deal_info.save()
        else:
            pass
    else:
        cursor_ctmsupport1.execute(ctmsupport2_sql)

        ctmsupport2_results = cursor_ctmsupport1.fetchall()
        for value in ctmsupport2_results:
            deal_info = DealerInfo.objects.create(
                dealer_company=value[0],
                dealer_organization=value[1],
                dealer_group_name=value[2],
                dealer_name=value[3],
                login_id=value[4],

            )
            deal_info.save()

    ############### 事件初步原因分析表的同步
    cursor_failurecatereason = db_connection.cursor()
    failurecatereason_sql = "select id from tb_failure_cate_reason  "
    cursor_failurecatereason.execute(failurecatereason_sql)
    result_failurecatereason_judge = cursor_failurecatereason.fetchone()

    incireason1_sql = """select
           cChr_MenuName,
           cChr_MenuName2
           from GTJA_MenuForm
           where cChr_Type = 'IncidentReason' and Modified_Date>=%s-24*60*60 and Modified_Date<%s""" % (
        timestamp, timestamp)
    incireason2_sql = """select
           cChr_MenuName,
           cChr_MenuName2
           from GTJA_MenuForm
           where cChr_Type = 'IncidentReason' and Modified_Date< %s""" % timestamp
    cursor_incident_reason1 = sql_connection.cursor()

    # 如果项目中对应的数据库表中有数据
    if result_failurecatereason_judge:
        cursor_incident_reason1.execute(incireason1_sql)
        incireason1_results = cursor_incident_reason1.fetchall()
        if incireason1_results:
            for value in incireason1_results:
                failure_cate_reason = FailureCateReason.objects.create(
                    first_event_category=value[0],
                    failure_reason_primary_analysis=value[1]
                )
                failure_cate_reason.save()
        else:
            pass
    else:
        cursor_incident_reason1.execute(incireason2_sql)

        incireason2_results = cursor_incident_reason1.fetchall()
        for value in incireason2_results:
            failure_cate_reason = FailureCateReason.objects.create(
                first_event_category=value[0],
                failure_reason_primary_analysis=value[1]
            )
            failure_cate_reason.save()


    ############### 事件一二三级分类信息表的同步
    cursor_classficationlayer = db_connection.cursor()
    classlayer_sql = "select id from tb_event_classify  "
    cursor_classficationlayer.execute(classlayer_sql)
    result_classlayer_judge = cursor_classficationlayer.fetchone()

    catelog1_sql = """select
           Categorization_Tier_1,
           Categorization_Tier_2,
           Categorization_Tier_3
           from CFG_Service_Catalog_LookUp
           where Help_Desk_Selection = 0  and Status_CTA = 1 and Status_CAT = 1 and Submit_Date>=%s-24*60*60 and Submit_Date< %s""" % (
        timestamp, timestamp)
    catelog2_sql = """select
           Categorization_Tier_1,
           Categorization_Tier_2,
           Categorization_Tier_3
           from CFG_Service_Catalog_LookUp
           where Help_Desk_Selection = 0  and Status_CTA = 1 and Status_CAT = 1 and Submit_Date<%s""" % timestamp
    cursor_catelog1 = sql_connection.cursor()

    # 如果项目中对应的数据库表中有数据
    if result_classlayer_judge:
        cursor_catelog1.execute(catelog1_sql)
        catelog1_results = cursor_catelog1.fetchall()
        if catelog1_results:
            for value in catelog1_results:
                category = ClassificationLayer.objects.create(
                    category1=value[0],
                    category2=value[1],
                    category3=value[2]
                )
                category.save()
        else:
            pass
    else:
        cursor_catelog1.execute(catelog2_sql)

        catelog2_results = cursor_catelog1.fetchall()
        for value in catelog2_results:
            category = ClassificationLayer.objects.create(
                category1=value[0],
                category2=value[1],
                category3=value[2]
            )
            category.save()


    ################ 关联度分析信息表的同步（一期没有）
    cursor_relevanceanalysis = db_connection.cursor()
    relevanceanalysis_sql = "select id from tb_association_analysis "
    cursor_relevanceanalysis.execute(relevanceanalysis_sql)
    result_relevanceanalysis_judge = cursor_relevanceanalysis.fetchone()

    hpd_associations1_sql = """
           select Request_ID02,--事件ID
           case Request_Type01 --关系类型
           when 6000 then '配置'
           when 9000 then '事件'
           when 12000 then '变更'
           when 20000 then '问题'
           when 23000 then '服务请求'
           end Request_Type01,
           Request_ID01,--关联ID
           Request_Description01 --关联项描述
           from HPD_Associations where Last_Modified_Date>=%s-24*60*60 and Last_Modified_Date<%s""" % (
        timestamp, timestamp)
    hpd_associations2_sql = """
             select Request_ID02,--事件ID
             case Request_Type01 --关系类型
             when 6000 then '配置'
             when 9000 then '事件'
             when 12000 then '变更'
             when 20000 then '问题'
             when 23000 then '服务请求'
             end Request_Type01,
             Request_ID01,--关联ID
             Request_Description01 --关联项描述
             from HPD_Associations where  Last_Modified_Date<%s""" % timestamp
    cursor_hpd_associations1 = sql_connection.cursor()

    # 如果项目中对应的数据表中有数据
    if result_relevanceanalysis_judge:
        cursor_hpd_associations1.execute(hpd_associations1_sql)
        hpd_associations1_results = cursor_hpd_associations1.fetchall()
        if hpd_associations1_results:
            for value in hpd_associations1_results:

                try:
                    event_ids = RelevanceAnalysis.objects.values_list('event_number')
                    event_idlist = []
                    for event_id in event_ids:
                        event_idlist.append(event_id[0])
                    if value[0] not in event_idlist:

                        relevance = RelevanceAnalysis.objects.create(
                            event_number=value[0],
                            association_type=value[1],
                            request_type=value[2],
                            asso_result_change=value[3]
                        )
                        relevance.save()

                    else:
                        pass
                except:
                    db_connection.rollback()
        else:
            pass
    else:
        cursor_hpd_associations1.execute(hpd_associations2_sql)

        hpd_associations2_results = cursor_hpd_associations1.fetchall()
        for value in hpd_associations2_results:
            relevance = RelevanceAnalysis.objects.create(
                event_number=value[0],
                association_type=value[1],
                request_type=value[2],
                asso_result_change=value[3]
            )
            relevance.save()

    db_connection.close()
    sql_connection.close()


def test():
    event_number = 'INC20100630003'
    event = EventInfo.objects.get(event_number=event_number)
    a = [1, 2, 3, 4, 5, 6]
    b = random.choice(a)
    event.processing_person = str(b)
    event.save()
