import datetime
import re

import unitls.baseFunction as baseFunction
from unitls.LogerinTxt import app_logger
from unitls.StaticDataclass import get_dic
from unitls.settings import NO_TPIS
from .flightDB import flightDB

no_tips_acno=NO_TPIS()


def waringinsert(database,text,taskid,col):
    try:
        newDic = {"警告信息": text,"航班编号":taskid, "信息状态": "", "提示信息": "", "产生时间": "%s" % datetime.datetime.now(),
               "处理人": "", "处理时间": "","变更字段": col, "显示对象": "", "提示内容": ""}
        database.lazyInsertData('logs', newDic)
    except Exception as e:
        app_logger.log_error(f"警告信息插入错误，插入信息{text}，{taskid}，{col}，错误信息见下一条")
        app_logger.log_error(e)
def noteinsert(database,text,taskid,col):
    try:
        newDic = {"警告信息": '',"航班编号":taskid, "信息状态": "", "提示信息": text, "产生时间": "%s" % datetime.datetime.now(),
               "处理人": "", "处理时间": "","变更字段": col, "显示对象": "", "提示内容": ""}
        database.lazyInsertData('logs', newDic)
    except Exception as e:
        app_logger.log_error(f"提示信息插入错误，插入信息{text}，{taskid}，{col}，错误信息见下一条")
        app_logger.log_error(e)
def checkTASKTYPE(row,en2zh,database,flightdate,LOGsdeactive,headerLabelKey,headerLabel,nowDayStr):
    try:
        newDic = {}
        for col in row:
            if col in headerLabelKey:
                if col != "FJ_TASKIDS" and col != "LAST_AF_ATA" and col != "LAST_TAF_ATA" and col != 'FNO':
                    newDic[en2zh[col]] = row[col]
                elif col == "FJ_TASKIDS" :
                    newDic[en2zh[col]] = ",".join(row[col])
                elif col == 'FNO':
                    newDic[en2zh[col]] = row[col].replace("|","-").replace("---","")
                else:
                    if row["CARRIER"] == '3U':
                        newDic[en2zh[col]] = row[col][0]['ATA']
                    else:
                        newDic[en2zh[col]] = ''
        if row["TASKTYPE"] == "" and LOGsdeactive != 0:
            waringinsert(database,"[%s]机号%s航班号%s,航班类型显示为空白,请查看派工模块并及时调整任务类型!!" %(flightdate, row["ACNO"], row["FNO"]),row["TASKID"], en2zh["TASKTYPE"])


        newDic['航班编号'] = str(row['TASKID'])
        newDic['取消标志'] = "0"
        newDic['航班来源'] = "AMRO"
        for key in headerLabel:
            if key not in newDic.keys():
                newDic[key] = ''

        database.lazyInsertData('TaskFlightinfo{}'.format(nowDayStr), newDic)
    except Exception as e:
        app_logger.log_error(f"航班类型监测并写入数据错误，详细错误信息见下条")
        app_logger.log_error(e)

def judgeWaringsts(bztime,oldbztime): #只抑制警告，不抑制note
    now = datetime.datetime.now()
    starttime = now-datetime.timedelta(hours=12)
    endtime = now+datetime.timedelta(hours=4)   #最多4+2小时的
    if (starttime < datetime.datetime.strptime(bztime, "%Y-%m-%d %H:%M:%S") < endtime) or (starttime < datetime.datetime.strptime(oldbztime, "%Y-%m-%d %H:%M:%S") < endtime ):  #当现在距离这个航班的预计保障时间相差5h或者过了一1h之内就不抑制
        return 0
    else:
        return 1



def insertTaskDataToTable(database: flightDB, datatime: str, jsonData,jsonData2):
    flightst_code = {"4": "接机已到位提示", "7": "已放行提示", "11": "二送已到位提示"}
    bglist = ["ACNO", "FNO", "ETA", "BAY_B", "TASKTYPE", "BL", "SJ_DEP"]  # 需要播报的变更列表,应该与显示的相结合
    AFbglist = ["ACNO", "FNO", "ETA", "BAY_B", "BL"]
    APbglist = ["ACNO", "FNO", "SJ_DEP"]
    TRbglist = ["ACNO", "FNO", "ETA", "BAY_B", "BL", "SJ_DEP"]



    nowDayStr = datatime
    now = datetime.datetime.now()
    insertdatestr = datatime + " 00:00:00"
    insertdate = datetime.datetime.strptime(insertdatestr, "%Y%m%d %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S")
    nowDay = datetime.datetime.now().strftime("%Y%m%d")
    nowDay_1 = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y%m%d")
    nowDay_2 = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%Y%m%d")
    nowDay_str2 = datetime.date.today().strftime("%Y-%m-%d")
    a_str = nowDay_str2 + " 20:30:00"
    b_str = nowDay_str2 + " 22:00:00"
    c_str = nowDay_str2 + " 09:00:00"
    time1 = datetime.datetime.strptime(a_str, "%Y-%m-%d %H:%M:%S")
    time2 = datetime.datetime.strptime(b_str, "%Y-%m-%d %H:%M:%S")
    time3 = datetime.datetime.strptime(c_str, "%Y-%m-%d %H:%M:%S")
    if now < time3:
        days = [nowDay, nowDay_1]
    elif time3 < now < time1:
        days = [nowDay]
    else:
        days = [nowDay, nowDay_2]
    try:
        if nowDayStr in days:
            #获取静态参数
            en2zh=get_dic("TaskflightinfoLabel2en")
            headerLabelKey = get_dic("headerLabelKey")
            headerLabel = get_dic("TaskflightinfoLabel")
            taskType=get_dic("taskType")
            header2num=get_dic("header2num")
            taskSTS=get_dic("taskSTS")
            ecsjtaskSTS=get_dic("ecsjtaskSTS")
            zydy_simple=get_dic("zydy_simple")
            ########################################
            flightinfo_flight_ids_arr = []
            flightinfo_flight_ids = database.queryTabel('TaskFlightinfo{}'.format(nowDayStr), '*', "航班来源='AMRO'")#确认一下要不要取整张表
            if len(flightinfo_flight_ids) != 0:
                for i in flightinfo_flight_ids:
                    flightinfo_flight_ids_arr.append(i[0])

            flight_id_now = []
            for i in [jsonData,jsonData2]:
                if jsonData != "" and jsonData2 !="" and jsonData2 !=None and jsonData !=None and jsonData != {} and  jsonData2 != {} and len(jsonData)!=0 and len(jsonData2)!=0:
                    for row in i:
                        bztime=row["STARTDATE_PL"] if 'STARTDATE_PL' in row and row["STARTDATE_PL"] != "" else datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        flightinfos=baseFunction.TuplefindInList1(flightinfo_flight_ids, row["TASKID"], 0)
                        oldbztime=flightinfos[0][36] if flightinfos else bztime
                        LOGsdeactive = judgeWaringsts(bztime,oldbztime)
                        flight_id_now.append(row["TASKID"])
                        now11=str(now).split(".")[0]
                        flightdate=str(row["FLIGHTDATE"]).split(" ")[0][5:10]
                        if str(row["TASKID"]) not in str(flightinfo_flight_ids_arr) and str(insertdate)==row["FLIGHTDATE"]:
                            checkTASKTYPE(row,en2zh,database,flightdate,LOGsdeactive,headerLabelKey,headerLabel,nowDayStr)
                            ####这里需要一个检查返航的，目前还没有确定返航字段
                            if len(flightinfo_flight_ids_arr) != 0 and LOGsdeactive == 0:
                                #app_logger.log_error("bztime")
                                #app_logger.log_error(bztime)
                                #app_logger.log_error(oldbztime)
                                #app_logger.log_error(f'{flightdate},{row["ACNO"]},{row["TASKID"]}')
                                a = taskType[row["TASKTYPE"]] if row["TASKTYPE"] != "" else "未显示"
                                waringinsert(database, "有新增航班,[%s]机号:%s航班号：%s航班类型:%s,请注意核对FOC!!!" % (flightdate, row["ACNO"], row["TASKID"], a),  row["TASKID"], "全部新增")
                        elif str(row["TASKID"]) in str(flightinfo_flight_ids_arr) and str(row["TASKID"]) != "":
                            #检测到航班信息，清零取消监测
                            newdic = {"取消标志": "'0'"}
                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic,"航班编号='%s'" % row["TASKID"])
                            acno=flightinfos[0][1]
                            if acno == row["ACNO"]:
                                old_tasktype = flightinfos[0][3]
                                sjry = flightinfos[0][15]
                                for col in headerLabelKey:
                                    b = flightinfos[0][header2num[col]]
                                    if col =='TASKTYPE' and 'TASKTYPE' in row and row[col] != b:
                                        if LOGsdeactive == 0:
                                            waringinsert(database, "[%s]机号:%s航班类型由%s变更为%s,请注意核对FOC!!!" % (flightdate,row["ACNO"],taskType[b],taskType[row["TASKTYPE"]] ),row["TASKID"], en2zh[col])
                                            if "BAY_A" in row and "BAY_B" in row and row["BAY_A"] != row["BAY_B"] and (row[col] == "TR" or row[col] == "TAF"):
                                                mesg="[%s]%s %s航班进港机位为%s，出港机位为%s,短停进出港机位不一致，请注意核对AMRO机位信息，按需修改，注意核对工作人员派送机位信息!!!" % (flightdate,row["ACNO"], row["FNO"],row["BAY_A"], row["BAY_B"])
                                                if mesg not in str(database.queryTabel('logs', "警告信息", "航班编号='%s'" % row["TASKID"])):
                                                   waringinsert(database, mesg, row["TASKID"], "机位不一致警告")
                                        else:
                                            noteinsert(database, "[%s]机号:%s航班类型由%s变更为%s,请注意核对FOC!!!" % (flightdate,row["ACNO"],taskType[b],taskType[row["TASKTYPE"]] ),row["TASKID"], en2zh[col])

                                        newdic = {"航班类型": "'%s'" % row["TASKTYPE"]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic,"航班编号='%s'" % row["TASKID"])
                                    elif 'TASKSTS' in row and col == 'TASKSTS' and row[col] != b:
                                        noteinsert(database, "[%s]机号:%s维修状态由%s变更为%s!%s" % (flightdate,row["ACNO"],taskSTS[b], taskSTS[row["TASKSTS"]],now11),row["TASKID"], en2zh[col])
                                        if row[col] in flightst_code.keys():
                                            newdic={"%s"%flightst_code[row[col]]:"1"}
                                            database.lazyUpdateItem('flightsts{}'.format(nowDayStr),newdic,"航班编号='%s'"%row["TASKID"])
                                        if row['TASKTYPE'] != "AP" and row['TASKSTS'] != "" and int(row['TASKSTS']) >= 7 and ("ATA" not in row or row["ATA"] == '' or datetime.datetime.strptime(row['ATA'],"%Y-%m-%d %H:%M:%S")+datetime.timedelta(minutes=15) >= datetime.datetime.now()):
                                            waringinsert(database, "[%s]机号:%s放行节点上报过早，请确认是否误上报并确认放行情况！！" % (flightdate,row["FNO"]), row["TASKID"], "放行节点早报")

                                        newdic = {"维修状态": "'%s'" % row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col == 'TASKSTS_ECSJ' and 'TASKSTS_ECSJ' in row and row[col] != b:
                                        noteinsert(database, "[%s]机号:%s二送状态由%s变更为%s!%s" % (flightdate,row["ACNO"],ecsjtaskSTS[b], ecsjtaskSTS[row["TASKSTS_ECSJ"]],now11),row["TASKID"], en2zh[col])
                                        newdic = {"二送状态": "'%s'" % row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    ####需要判断返航备降的字段，暂缺
                                    elif col == 'ETA' and "ETA" in row and row[col] != b and row["TASKTYPE"] != "AP":
                                        if b == "" and LOGsdeactive == 0 and "FLYING" in row and row["FLYING"] != "" :  #新航班有预计到达，且上段已经实际起飞
                                            waringinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col], b, row[col][-8:-3]),row["TASKID"], en2zh[col])

                                        elif b != "" and LOGsdeactive == 0 and "ATD" in row and row["ATD"] != "" : #预计到达发生变更，且上段已经实际起飞
                                            ETA_P = datetime.datetime.strptime(b, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(minutes=10)
                                            ETA_N = datetime.datetime.strptime(b, "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=5)
                                            ETAnew = datetime.datetime.strptime(str(row[col]), "%Y-%m-%d %H:%M:%S")
                                            if (ETAnew < ETA_N or ETAnew > ETA_P ) and ETAnew > now:
                                                waringinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col], b[-8:-3], row[col][-8:-3]),row["TASKID"], en2zh[col])
                                        else:
                                            noteinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col], b, row[col][-8:-3]),row["TASKID"], en2zh[col])
                                        newdic = {"非航前预计到达": "'%s'" % row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col == "FLYING" and "FLYING" in row and old_tasktype != "AP" and row[col] != b and "新航班播报" not in str(database.queryTabel('logs', "变更字段", "航班编号='%s'" %row["TASKID"])):
                                        FJtask = ",有工作包" if row["FJ_TASKIDS"] != [] else ""
                                        BLstr = ",有保留" if "BL" in row and row["BL"] != "" else ""
                                        bay_str=row["BAY_B"] if "BAY_B" in row else ""
                                        waringinsert(database, "[%s]新航班:%s%s%s %s%s%s!" % (flightdate,row["ACNO"],taskType[old_tasktype],bay_str, row["ETA"][-8:-3],BLstr,FJtask),row["TASKID"], "新航班播报")

                                        newdic = {"上段起飞时间": "'%s'" % row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                        now_1= (datetime.datetime.now() - datetime.timedelta(minutes=0.5)).strftime("%Y-%m-%d %H:%M:%S")
                                        waringsts = database.queryTabel('logs', "编号","航班编号 ='%s' and 变更字段='非航前预计到达' and 产生时间>'%s'" %(row["TASKID"],now_1))
                                        if len(waringsts) != 0:
                                            newdic = {"处理人": "'系统抑制'", "处理时间": "'%s'" % now}
                                            database.lazyUpdateItem('logs', newdic, "编号='%s'" % waringsts[0][0])
                                    elif col == 'STD' and "ETD" not in row and "STD" in row and row[col] != b:
                                        if LOGsdeactive == 0 and "ATD" not in row:
                                            waringinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col], b, row[col]),row["TASKID"], en2zh[col])
                                        else:
                                            noteinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col], b, row[col]),row["TASKID"], en2zh[col])
                                        newdic = {"航前预计起飞": "'%s'" % row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col == 'STD' and "STD" in row and "ETD" in row and "ATD" not in row and row["ETD"] != b :
                                        if LOGsdeactive == 0 and ("CSC" in flightinfos[0][21] or "3U" in flightinfos[0][21] or ("CSC" not in flightinfos[0][21] and "3U" not in flightinfos[0][21] and datetime.datetime.strptime(row["ETD"], "%Y-%m-%d %H:%M:%S") > datetime.datetime.now())):
                                            waringinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col], b, row["ETD"]),row["TASKID"], en2zh[col])
                                        else:
                                            noteinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col], b, row["ETD"]),row["TASKID"], en2zh[col])
                                        newdic = {"航前预计起飞": "'%s'" % row["ETD"]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col == 'FJ_TASKIDS' and "FJ_TASKIDS" in row and ",".join(row[col]) != b:
                                        if row['TASKTYPE'] != "AF" and row['TASKTYPE'] != "AP" and LOGsdeactive == 0:
                                            mesg = "[%s]机号:%s航班号:%s有新增工作包!" % (flightdate,row["ACNO"],row['FNO'])
                                            if mesg not in str(database.queryTabel('logs', "警告信息", "航班编号='%s'" % row["TASKID"])):
                                                waringinsert(database,mesg,row["TASKID"], en2zh[col])
                                        newdic = {"工作包": "'%s'" % ",".join(row[col])}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col == 'BAY_A' and "BAY_A" in row:
                                        if b != row[col]:
                                            if (row["TASKTYPE"] == "TR" or row["TASKTYPE"] == "AF" or row["TASKTYPE"] == "TAF") and LOGsdeactive == 0:
                                                waringinsert(database, "[%s]%s机位由%s变更为%s" % (flightdate, row["ACNO"], b, row[col]),row["TASKID"], "进港机位变更")
                                            else:
                                                noteinsert(database, "[%s]%s机位由%s变更为%s" % (flightdate, row["ACNO"], b, row[col]),row["TASKID"], "进港机位变更")
                                            newDic2={"%s"%en2zh[col]:"'%s'"%row[col]}
                                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newDic2, "航班编号='%s'" %row["TASKID"])
                                        if (row["TASKTYPE"] == "TR" or row["TASKTYPE"] == "TAF") and "BAY_B" not in row:
                                            newDic2 = {"航前离港机位": "'%s'" % row[col]}
                                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newDic2,"航班编号='%s'" % row["TASKID"])
                                    elif col == 'BAY_B' and "BAY_B" in row:
                                        if b != row[col]:
                                            if (row["TASKTYPE"] == "AP" or ((row["TASKTYPE"] == "TR" or row["TASKTYPE"] == "TAF") and("BAY_A" not in row or row["BAY_A"] != row["BAY_B"]))) and LOGsdeactive == 0:
                                                waringinsert(database,  "[%s]%s机位由%s变更为%s" % (flightdate, row["ACNO"], b, row[col]),row["TASKID"], "出港机位变更")
                                            else:
                                                noteinsert(database,  "[%s]%s机位由%s变更为%s" % (flightdate, row["ACNO"], b, row[col]),row["TASKID"], "出港机位变更")
                                            newDic2 = {"%s"%en2zh[col]: "'%s'" % row[col]}
                                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newDic2,"航班编号='%s'" % row["TASKID"])
                                            if (row["TASKTYPE"] == "TR" or row["TASKTYPE"] == "TAF") and "BAY_A" in row and (row["BAY_A"] != row["BAY_B"]):
                                                newDic2 = {"非航前进港机位": "'%s'" % row[col]}
                                                database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newDic2,"航班编号='%s'" %row["TASKID"])
                                        if (row["TASKTYPE"] == "TR" or row["TASKTYPE"] == "TAF") and ("BAY_A" not in row.keys()):
                                            newDic2 = {"非航前进港机位": "'%s'" % row[col]}
                                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newDic2,"航班编号='%s'" % row["TASKID"])
                                    elif col == "SJ_DEP" and "SJ_DEP" in row and "SJ_ARR" not in row:
                                        if row["SJ_DEP"] != "":
                                            SJ = "随机"+row["SJ_DEP"].replace("已安排","").replace("已登机","")+";"
                                        else:
                                            SJ = ""
                                        new_a = row["TASKID"] + "-2" + "-A"
                                        fj = database.queryTabel('peopleSchedule{}'.format(nowDayStr), "附加消息", "编号='%s'" % str(new_a))
                                        if sjry != SJ:
                                            newDic2={"%s"%en2zh[col]:"'%s'" % SJ}
                                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newDic2, "航班编号='%s'" % row["TASKID"])
                                            if fj and len(fj) != 0 and ((sjry != "" and sjry not in str(fj) and SJ not in str(fj) and SJ != "") or sjry == ""):
                                                new_fj=SJ + fj[0][0]
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_a))
                                                waringinsert(database, "[%s]%s随机由%s变更为%s" % (flightdate, row["ACNO"], sjry, SJ),row["TASKID"],"随机人员变更")
                                            elif fj and len(fj)!=0 and sjry in str(fj) and SJ != sjry:
                                                new_fj=fj[0][0].replace("%s"% sjry,"%s"% SJ)
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_a))
                                                waringinsert(database, "[%s]%s随机由%s变更为%s" % (flightdate, row["ACNO"], sjry, SJ),row["TASKID"],"随机人员变更")
                                        else:
                                            if fj == None or len(fj) == 0:
                                                newDic2 = {"编号":new_a,"航班编号":row["TASKID"],"显示模式":"A","放行":"","勤务1":"","勤务2":"","工1":"","工2":"","工3":"","附加消息":"%s" % SJ}
                                                database.lazyInsertData('peopleSchedule{}'.format(nowDayStr), newDic2)
                                            elif SJ not in str(fj):
                                                new_fj = SJ + fj[0][0]
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_a))
                                    elif col == "SJ_ARR" and "SJ_ARR" in row and "SJ_DEP" not in row:
                                        if row["SJ_ARR"] != "":
                                            SJ="随机"+row["SJ_ARR"].replace("已安排","").replace("已登机","")+";"
                                        else:
                                            SJ = ""
                                        new_a = row["TASKID"] + "-1" + "-A"
                                        fj = database.queryTabel('peopleSchedule{}'.format(nowDayStr), "附加消息","编号='%s'" % str(new_a))
                                        if sjry != SJ:
                                            newDic2={"%s"%en2zh[col]:"'%s'" %SJ}
                                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newDic2, "航班编号='%s'" % row["TASKID"])
                                            if fj and len(fj)!=0 and ((sjry!="" and sjry not in str(fj) and SJ not in str(fj) and SJ !="") or sjry == ""):
                                                new_fj=SJ + fj[0][0]
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_a))
                                                waringinsert(database, "[%s]%s随机由%s变更为%s" % (flightdate, row["ACNO"], sjry, SJ),row["TASKID"],"随机人员变更")
                                            elif fj and   len(fj)!=0 and sjry in str(fj) and SJ != sjry:
                                                new_fj=fj[0][0].replace("%s"%sjry,"%s"%SJ)
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_a))
                                                waringinsert(database, "[%s]%s随机由%s变更为%s" % (flightdate, row["ACNO"], sjry, SJ),row["TASKID"],"随机人员变更")
                                        else:
                                            if fj == None or len(fj)==0:
                                                newDic2 = {"编号":new_a,"航班编号":row["TASKID"],"显示模式":"A","放行":"","勤务1":"","勤务2":"","工1":"","工2":"","工3":"","附加消息":"%s" % SJ}
                                                database.lazyInsertData('peopleSchedule{}'.format(nowDayStr), newDic2)
                                            elif SJ not in str(fj):
                                                new_fj=SJ+ fj[0][0]
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_a))

                                    elif (col == "SJ_DEP" and "SJ_ARR" in row and "SJ_DEP" in row) or (col == "SJ_ARR" and "SJ_DEP" in row and "SJ_ARR" in row):
                                        if row["SJ_DEP"] != "" and row["SJ_ARR"] == "":
                                            SJ_DEP="随机"+row["SJ_DEP"].replace("已安排","").replace("已登机","")+";"
                                            SJ_ARR=""
                                            SJ = str(SJ_DEP)
                                        elif row["SJ_DEP"] == "" and row["SJ_ARR"] != "":
                                            SJ_ARR = "随机" + row["SJ_ARR"].replace("已安排","").replace("已登机","")+";"
                                            SJ_DEP = ""
                                            SJ = str(SJ_ARR)
                                        elif row["SJ_DEP"] == "" and row["SJ_ARR"] == "":
                                            SJ_DEP = ""
                                            SJ_ARR = ""
                                            SJ = ""
                                        else:
                                            SJ_ARR = "随机" + row["SJ_ARR"].replace("已安排","").replace("已登机","")+";"
                                            SJ_DEP = "随机" + row["SJ_DEP"].replace("已安排","").replace("已登机","")+";"
                                            SJ=str(SJ_ARR)+"-"+str(SJ_DEP)
                                        new_a = row["TASKID"] + "-1" + "-A"
                                        new_b = row["TASKID"] + "-2" + "-A"
                                        fj = database.queryTabel('peopleSchedule{}'.format(nowDayStr), "附加消息","编号='%s'" % str(new_a))
                                        fj2 = database.queryTabel('peopleSchedule{}'.format(nowDayStr), "附加消息","编号='%s'" % str(new_b))


                                        if "离港" in sjry and "进港" not in sjry:
                                            sjry_ARR = ""
                                            sjry_DEP = sjry
                                        elif "进港" in sjry and "离港" not in sjry:
                                            sjry_ARR = sjry
                                            sjry_DEP = ""
                                        elif "进港" not in sjry and "离港" not in sjry:
                                            sjry_ARR = ""
                                            sjry_DEP = ""
                                        else:
                                            sjry_ARR=sjry.split("-")[0]
                                            sjry_DEP = sjry.split("-")[1]

                                        if sjry != SJ:
                                            newDic2={"随机":"'%s'" %SJ}
                                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newDic2, "航班编号='%s'" % row["TASKID"])
                                            waringinsert(database, "[%s]%s随机由%s变更为%s" % (flightdate, row["ACNO"], sjry, SJ),row["TASKID"],"随机人员变更")
                                            if fj and len(fj)!=0 and ((sjry_ARR !="" and str(sjry_ARR) not in str(fj) and str(SJ_ARR) not in str(fj) and sjry_ARR !=SJ_ARR)or(sjry_ARR =="" and str(SJ_ARR) not in str(fj) and sjry_ARR !=SJ_ARR)):
                                                new_fj=SJ_ARR+fj[0][0]
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_a))
                                            elif fj and  len(fj)!=0 and sjry_ARR !="" and str(sjry_ARR) in str(fj) and sjry_ARR != SJ_ARR:
                                                new_fj=fj[0][0].replace("%s"%(sjry_ARR),"%s"%(SJ_ARR))
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_a))
                                            if fj2 and len(fj2)!=0 and ((sjry_DEP !="" and str(sjry_DEP) not in str(fj2) and str(SJ_DEP) not in str(fj2) and sjry_DEP !=SJ_DEP)or(sjry_DEP =="" and str(SJ_DEP) not in str(fj2) and sjry_DEP !=SJ_DEP)):

                                                new_fj2 = SJ_DEP+fj2[0][0]
                                                newDic2 = {"附加消息": "'%s'" % new_fj2}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_b))
                                            elif fj2 and  len(fj2)!=0 and sjry_DEP !="" and sjry_DEP in str(fj2) and sjry_DEP != SJ_DEP:
                                                new_fj2=fj2[0][0].replace("%s"%(sjry_DEP),"%s"%(SJ_DEP))
                                                newDic2 = {"附加消息": "'%s'" % new_fj2}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_b))
                                        else:
                                            if fj==None or len(fj)==0:
                                                newDic2 = {"编号":new_a,"航班编号":row["TASKID"],"显示模式":"A","放行":"","勤务1":"","勤务2":"","工1":"","工2":"","工3":"","附加消息":"%s" %SJ_ARR}
                                                database.lazyInsertData('peopleSchedule{}'.format(nowDayStr), newDic2)
                                            elif fj2==None or len(fj2)==0:
                                                newDic2 = {"编号":new_b,"航班编号":row["TASKID"],"显示模式":"A","放行":"","勤务1":"","勤务2":"","工1":"","工2":"","工3":"","附加消息":"%s" %SJ_DEP}
                                                database.lazyInsertData('peopleSchedule{}'.format(nowDayStr), newDic2)
                                            elif str(SJ_ARR) not in str(fj) or str(str(SJ_DEP)) not in str(fj2):
                                                new_fj=SJ_ARR+fj[0][0]
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_a))
                                                new_fj2 = SJ_DEP + fj2[0][0]
                                                newDic2 = {"附加消息": "'%s'" % new_fj2}
                                    elif col == 'REMARK_BUSINESS' and "REMARK_BUSINESS" in row and row[col] != b:
                                        if "返航" in row["REMARK_BUSINESS"]:
                                            if row["TASKTYPE"] != "AP":
                                                new_a = row["TASKID"] + "-1" + "-A"
                                            else:
                                                new_a = row["TASKID"] + "-2" + "-A"
                                            fj = database.queryTabel('peopleSchedule{}'.format(nowDayStr), "附加消息","编号='%s'" % str(new_a))
                                            if fj == None or len(fj) == 0:
                                                newDic2 = {"编号": new_a, "航班编号": row["TASKID"], "显示模式": "A", "放行": "","勤务1": "", "勤务2": "", "工1": "", "工2": "", "工3": "","附加消息": "返航航班;"}
                                                database.lazyInsertData('peopleSchedule{}'.format(nowDayStr), newDic2)
                                            elif "返航航班;" not in str(fj):
                                                new_fj=fj[0][0]+"返航航班;"
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2, "编号='%s'" % str(new_a))
                                            waringinsert(database, "%s/%s判断为返航航班，请核对FOC" % (row["ACNO"],row["FNO"]),row["TASKID"],"返航警告")
                                        elif "备降天府" in row["REMARK_BUSINESS"]:
                                            new_a = row["TASKID"] + "-1" + "-A"
                                            fj = database.queryTabel('peopleSchedule{}'.format(nowDayStr), "附加消息","编号='%s'" % str(new_a))
                                            if fj == None or len(fj) == 0:
                                                newDic2 = {"编号": new_a, "航班编号": row["TASKID"], "显示模式": "A", "放行": "","勤务1": "", "勤务2": "", "工1": "", "工2": "", "工3": "","附加消息": "备降航班;"}
                                                database.lazyInsertData('peopleSchedule{}'.format(nowDayStr), newDic2)
                                            elif "备降航班;" not in str(fj):
                                                new_fj=fj[0][0]+"备降航班;"
                                                newDic2 = {"附加消息": "'%s'" % new_fj}
                                                database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2, "编号='%s'" % str(new_a))
                                            waringinsert(database, "%s/%s判断为备降航班，请核对FOC" % (row["ACNO"],row["FNO"]),row["TASKID"],"备降警告")
                                        newdic = {"%s"% en2zh[col]: "'%s'" %row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col == "WX" and "WX" in row and row[col] != "" and row[col] != b:
                                        noteinsert(database, "[%s]机号:%s%s由%s变更为%s!%s" % (flightdate,row["ACNO"], zydy_simple[col],b, row[col],now11),row["TASKID"], en2zh[col])
                                        newdic = {"%s"% en2zh[col]: "'%s'" %row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col == "FX" and "FX" in row and row[col] != "" and row[col] != b:
                                        noteinsert(database, "[%s]机号:%s%s由%s变更为%s!%s" % (flightdate,row["ACNO"], zydy_simple[col],b, row[col],now11),row["TASKID"], en2zh[col])
                                        newdic = {"%s"% en2zh[col]: "'%s'" %row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col == "ECSJ" and "ECSJ" in row and row[col] != "" and row[col] != b:
                                        noteinsert(database, "[%s]机号:%s%s由%s变更为%s!%s" % (flightdate,row["ACNO"], zydy_simple[col],b, row[col],now11),row["TASKID"], en2zh[col])
                                        newdic = {"%s"% en2zh[col]: "'%s'" %row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col== 'HIGHALT' and 'HIGHALT' in row and row[col] != b:
                                        if LOGsdeactive == 0 and row[col] == 'Y' and "A319" in row["ACTYPE"]:
                                            waringinsert(database, "[%s]%s-%s航线变更为高高原航线，注意工作单签署" % (flightdate,row["ACNO"],row["FNO"]),row["TASKID"], en2zh[col])
                                        elif LOGsdeactive == 0 and row[col] != 'Y' and "A319" in row["ACTYPE"]:
                                            waringinsert(database, "[%s]%s-%s航线变更为非高高原航线，注意工作单签署" % (flightdate,row["ACNO"],row["FNO"]),row["TASKID"], en2zh[col])
                                        newdic = {"%s"% en2zh[col]: "'%s'" %row[col]}
                                        database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                    elif col not in ["TASKID","FJ_TASKIDS","SJ_DEP","SJ_ARR","STD","WX","FX","ECSJ","BAY_A","BAY_B"]:
                                        if col not in row:
                                            row[col] = ''
                                        elif col in ["LAST_AF_ATA","LAST_TAF_ATA"] :
                                            if row["CARRIER"] == '3U':
                                                row[col] = row[col][0]["ATA"]
                                            else:
                                                row[col] = ''
                                        elif col == "FNO":
                                            row[col] = row[col].replace("|","-").replace("---","")
                                        if row[col] != b:
                                            if old_tasktype == "AP" and col in APbglist and LOGsdeactive == 0:
                                                waringinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col],b, row[col]),row["TASKID"], en2zh[col])
                                            elif old_tasktype == "AF" and col in AFbglist and LOGsdeactive == 0:
                                                waringinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col],b, row[col]),row["TASKID"], en2zh[col])
                                            elif (old_tasktype =="TR" or old_tasktype=="TAF" ) and col in TRbglist and LOGsdeactive == 0:
                                                waringinsert(database, "[%s]机号:%s%s由%s变更为%s!" % (flightdate,row["ACNO"], zydy_simple[col],b, row[col]),row["TASKID"], en2zh[col])
                                            else:    #限制提示信息输出位置
                                                if col not in ["TASKSTS_TIME",'ISSHIFTEX',"FLIGHTID1","FLIGHTID2",'ACGGY']:
                                                    noteinsert(database, "[%s]机号:%s%s由%s变更为%s!%s" % (flightdate,row["ACNO"], zydy_simple[col],b, row[col],now11),row["TASKID"], en2zh[col])

                                            newdic = {"%s" % en2zh[col]: "'%s'" % row[col]}
                                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                                #database.FunctionCommit()
                                if "SJ_DEP" not in row and "SJ_ARR" not in row and sjry != "":
                                    #if sjry != "":
                                    newDic2 = {"随机": "''"}
                                    database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newDic2,"航班编号='%s'" % row["TASKID"])
                                    waringinsert(database, "[%s]%s %s取消,请核对FOC" % (flightdate, row["ACNO"], sjry),row["TASKID"], "随机人员")
                                    new_a = row["TASKID"] + "-1" + "-A"
                                    new_b = row["TASKID"] + "-2" + "-A"
                                    fj = database.queryTabel('peopleSchedule{}'.format(nowDayStr), "附加消息","编号='%s'" % str(new_a))
                                    fj2 = database.queryTabel('peopleSchedule{}'.format(nowDayStr), "附加消息","编号='%s'" % str(new_b))
                                    if fj and len(fj)!=0 and len(fj[0])!=0:
                                        new_fj=re.sub(r"随机.*港.*?[;]","",fj[0][0])
                                        newDic = {"附加消息": "'%s'" % new_fj}
                                        database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic,"编号='%s'" % str(new_a))
                                    if fj2 and len(fj2)!=0 and len(fj2[0])!=0:
                                        new_fj2=re.sub(r"随机.*港.*?[;]", "",fj2[0][0])
                                        newDic2 = {"附加消息": "'%s'" % new_fj2}
                                        database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_b))

                                if row["ACNO"] in no_tips_acno and row["TASKTYPE"] == "AP":
                                    new_b = row["TASKID"] + "-2" + "-A"
                                    fj2 = database.queryTabel('peopleSchedule{}'.format(nowDayStr), "附加消息","编号='%s'" % str(new_b))
                                    if fj2 == None or len(fj2)==0:
                                        newDic2 = {"编号":new_b,"航班编号":row["TASKID"],"显示模式":"A","放行":"","勤务1":"","勤务2":"","工1":"","工2":"","工3":"","附加消息":"【工具提示】无TPIS,带胎压表;"}
                                        database.lazyInsertData('peopleSchedule{}'.format(nowDayStr), newDic2)
                                    elif "【工具提示】无TPIS,带胎压表" not in str(fj2):
                                        new_fj = "【工具提示】无TPIS,带胎压表;" + fj2[0][0]
                                        newDic2 = {"附加消息": "'%s'" % new_fj}
                                        database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newDic2,"编号='%s'" % str(new_b))


                            else:
                                if LOGsdeactive == 0:
                                    waringinsert(database, "[%s]%s航班机号由%s变更为%s,请注意核对FOC!!!" % (flightdate,row["TASKID"], acno, row["ACNO"]),row["TASKID"], "机号")

                                newdic = {"机号": "'%s'" % row["ACNO"]}
                                database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" % row["TASKID"])
                    database.FunctionCommit()
                else:
                    print(datetime.datetime.now(), "[数据库操作]TaskFlightinfo航班数据为空")
                    app_logger.log_error("[数据库操作]TaskFlightinfo航班数据为空")
                    pass
            if jsonData != "" and jsonData2 !="" and jsonData2 != None and jsonData != None and jsonData != {} and  jsonData2 != {} and len(flight_id_now) != 0 and len(jsonData)!=0 and len(jsonData2)!=0:
                flightinfo_flight_ids = database.queryTabel('TaskFlightinfo{}'.format(nowDayStr),'*',"航班来源='AMRO'")
                if len(flightinfo_flight_ids) != 0:
                    for iii in flightinfo_flight_ids:
                        datas=baseFunction.TuplefindInList1(flightinfo_flight_ids, iii[0], 0)[0]
                        now=datetime.datetime.now()
                        now_15=datetime.datetime.now()-datetime.timedelta(hours=15)
                        if str(iii[0]) not in flight_id_now and datetime.datetime.strptime(datas[36] if datas[36] else now, "%Y-%m-%d %H:%M:%S") >= now_15 :
                            cancelid=datas[35]
                            newcancelid=int(cancelid)+1
                            if int(newcancelid) < 3:
                                newdic={"取消标志":"'%s'"%newcancelid}
                                database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic, "航班编号='%s'" %iii[0])
                            else:
                                c = datas[2][5:10]
                                a = datas[1]
                                bb = datas[21]
                                database.deleteSingledata("TaskFlightinfo{}".format(nowDayStr), "航班编号='%s'" % str(iii[0]) )
                                if nowDayStr == nowDay:
                                    waringinsert(database, "[%s]%s,%s航班已取消,注意核对FOC!!!"% (c,a,bb),iii[0], "全部取消")
            database.FunctionCommit()

            selectdaystr = str(datatime)[0:4] + "-" + str(datatime)[4:6] + "-" + str(datatime)[6:] + " 00:00:00"
            nowDayStr_search = datetime.datetime.strptime(selectdaystr, "%Y-%m-%d %H:%M:%S")
            starttime=(nowDayStr_search - datetime.timedelta(days=7)).strftime("%Y-%m-%d %H:%M:%S")
            endtime = (nowDayStr_search + datetime.timedelta(days=7)).strftime("%Y-%m-%d %H:%M:%S")
            tasknuminworjoblist=database.getSingledata("任务编号",'workjob')
            tasknums=database.queryTabel('TaskFlightinfo{}'.format(nowDayStr),'*', "工作包 !=''")
            if len(tasknums) != 0:
                for i in tasknums:
                    if i[0] not in str(tasknuminworjoblist):
                        workjoblist=i[18]
                        #print(workjoblist)
                        newdic3={"任务编号":"%s"%i[0],"工作包编号":"%s"%workjoblist,"查询开始时间":"%s"%starttime,"查询结束时间":"%s"%endtime,"开始时间":"","基地":"","项目描述":"","工作步骤":"","机号":"%s"%i[1],"机型":"%s"%i[26],"航班类型":"%s"%taskType[i[3]]}
                        database.lazyInsertData('workjob', newdic3)
                        #返回一个数值去查询
                    if i[0] in str(tasknuminworjoblist):
                        if i[18] != database.queryTabel('workjob','工作包编号', "任务编号 ='%s'"%i[0])[0][0]:
                            newdic = {"工作包编号": "'%s'" % i[18],"开始时间":"''","基地":"''","项目描述":"''","工作步骤":"''"}
                            database.lazyUpdateItem('workjob', newdic, "任务编号='%s'" % i[0])
            database.FunctionCommit()
    except Exception as e:
        app_logger.log_error(e)










