import datetime
import unitls.baseFunction as baseFunction
from unitls.LogerinTxt import app_logger
from unitls.StaticDataclass import get_dic
from .flightDB import flightDB
from .initFlightDatabase import initFlightDatabase


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 checkFlightplan(database:flightDB,wokload:flightDB):
    updatedic = {2: 11, 4: 13,5:14,6: 16,7: 17, 8: 9,10: 7, 11: 8, 15: 18, 16: 18,21: 12, 25: 3, 26: 2, 33 : 20} #taskinfo :flightplan
    try:
        print(datetime.datetime.now(),'[数据库操作]开始校验航班')
        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")
        now_20 = (datetime.datetime.now() + datetime.timedelta(hours=5)).strftime("%Y%m%d")
        initFlightDatabase(database, wokload, now_20)
        initFlightDatabase(database, wokload, nowDay_1)
        initFlightDatabase(database, wokload, nowDay_2)
        initFlightDatabase(database, wokload, nowDay)

        if now_20 == nowDay:
            day = [nowDay, nowDay_1]
        else:
            day = [nowDay, nowDay_1, nowDay_2]
        for nowDayStr in day:
            flightplan_flight_ids = database.queryTabel('flightplaninfo{}'.format(nowDayStr),"*","备1 ='1' and flgCs =''")
            TaskFlightinfo_flight_ids = database.queryTabel('TaskFlightinfo{}'.format(nowDayStr), '备4,备5', "航班编号!=''")
            TaskFlightinfo_ids = database.queryTabel('TaskFlightinfo{}'.format(nowDayStr), '航班编号', "航班编号!=''")

            flight_id_now = []
            if flightplan_flight_ids and len(flightplan_flight_ids) != 0:
                for sortkey in flightplan_flight_ids:
                    if str(sortkey[0]) not in str(TaskFlightinfo_flight_ids):
                        flight_id_now.append(f"System{sortkey[0]}")
                        TaskflightinfoLabel=get_dic("TaskflightinfoLabel")
                        if f"System{sortkey[0]}" not in str(TaskFlightinfo_ids):
                            peopleSchedule_ids = database.queryTabel('peopleSchedule{}'.format(nowDayStr) , '编号,附加消息', "航班编号 ='%s'"%f"System{sortkey[0]}")
                            newdic={"航班编号":f"System{sortkey[0]}","进出港城市":sortkey[5]+"-"+sortkey[6],"航班来源":"飞机排班","机号":sortkey[1].replace("B",""),"取消标志":0}
                            if sortkey[6] == "天府":
                                newdic["航班类型"] = "AF"
                            else:
                                newdic["航班类型"] = "AP"

                            for key,value in updatedic.items():
                                newdic[TaskflightinfoLabel[key]]= sortkey[value]
                            for key in TaskflightinfoLabel:
                                if key not in newdic.keys():
                                    newdic[key]=""
                            database.lazyInsertData('TaskFlightinfo{}'.format(nowDayStr), newdic)
                            if sortkey[6] == "天府":
                                if  f"System{sortkey[0]}-1-A" not in str(peopleSchedule_ids):
                                    newdic={"编号":f"System{sortkey[0]}-1-A","航班编号":f"System{sortkey[0]}","显示模式":"A","放行":"","勤务1":"","勤务2":"","工1":"","工2":"","工3":"","附加消息":"AMRO航班缺失,无法派工，航班信息来源于飞机排班，请核实航班类型和保障时间"}
                                    database.lazyInsertData('peopleSchedule{}'.format(nowDayStr), newdic)
                                else:
                                    fj = peopleSchedule_ids[0][1]
                                    if "AMRO航班缺失,无法派工，航班信息来源于飞机排班，请核实航班类型和保障时间" not in fj:
                                        newdic={"附加消息":"'%s'"%(fj+";AMRO航班缺失,无法派工，航班信息来源于飞机排班，请核实航班类型和保障时间")}
                                    else:
                                        newdic={"附加消息":"'AMRO航班缺失,无法派工，航班信息来源于飞机排班，请核实航班类型和保障时间'"}
                                    database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newdic,"编号='%s'"%f"System{sortkey[0]}-1-A")
                            elif sortkey[5] == "天府":
                                if  f"System{sortkey[0]}-2-A" not in str(peopleSchedule_ids):
                                    newdic={"编号":f"System{sortkey[0]}-2-A","航班编号":f"System{sortkey[0]}","显示模式":"A","放行":"","勤务1":"","勤务2":"","工1":"","工2":"","工3":"","附加消息":"AMRO航班缺失,无法派工，航班信息来源于飞机排班，请核实航班类型和保障时间"}
                                    database.lazyInsertData('peopleSchedule{}'.format(nowDayStr), newdic)
                                else:
                                    fj = peopleSchedule_ids[0][1]
                                    if "AMRO航班缺失,无法派工，航班信息来源于飞机排班，请核实航班类型和保障时间" not in fj:
                                        newdic={"附加消息":"'%s'"%(fj+";AMRO航班缺失,无法派工，航班信息来源于飞机排班，请核实航班类型和保障时间")}
                                    else:
                                        newdic={"附加消息":"'AMRO航班缺失,无法派工，航班信息来源于飞机排班，请核实航班类型和保障时间'"}
                                    database.lazyUpdateItem('peopleSchedule{}'.format(nowDayStr), newdic,"编号='%s'"%f"System{sortkey[0]}-2-A")

                            waringinsert(database,f"{sortkey[1]}/{sortkey[12]}在Amro任务派工模块无显示，已读取飞机排班系统信息显示，航班将无法派工，请核对航班、随机等信息并加强监控！",f"System{sortkey[0]}","航班缺失警告")
                        else:
                            TaskFlightinfos = database.queryTabel('TaskFlightinfo{}'.format(nowDayStr), '*' ,"航班编号='%s'"%f"System{sortkey[0]}")[0]
                            for key,value in updatedic.items():
                                if TaskFlightinfos[key] != sortkey[value]:
                                    newdic={TaskflightinfoLabel[key]:"'%s'"%sortkey[value]}
                                    database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr),newdic,"航班编号='%s'"%f"System{sortkey[0]}")
                                if (sortkey[5]+sortkey[6]) !=TaskFlightinfos[23]:
                                    newdic={TaskflightinfoLabel[23]:"'%s'"%(sortkey[5]+"-"+sortkey[6])}
                                    database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr),newdic,"航班编号='%s'"%f"System{sortkey[0]}")
                                if sortkey[1].replace("B","") != TaskFlightinfos[1]:
                                    newdic={"机号":"'%s'"%sortkey[1].replace("B","")}
                                    database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr),newdic,"航班编号='%s'"%f"System{sortkey[0]}")
                                if sortkey[6] == "天府" and TaskFlightinfos[3] != "AF":
                                    newdic={"航班类型":"'AF'"}
                                    database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic,"航班编号='%s'" % f"System{sortkey[ 0 ]}")
                                elif sortkey[5] == "天府" and TaskFlightinfos[3] != "AP":
                                    newdic={"航班类型":"'AP'"}
                                    database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr), newdic,"航班编号='%s'" % f"System{sortkey[ 0 ]}")
                    elif str(sortkey[0]) in str(TaskFlightinfo_flight_ids) and f"System{sortkey[0]}" in str(TaskFlightinfo_ids):
                        database.deleteSingledata('TaskFlightinfo{}'.format(nowDayStr),"航班编号='%s'"%f"System{sortkey[0]}")
                        waringinsert(database,f"{sortkey[1]}/{sortkey[12]}在Amro任务派工模块中恢复显示，如未派工请前往派工！飞机排班显示航班将在5min中后自动删除，做好人员安排信息备份！",f"System{sortkey[0]}","航班缺失恢复警告")
            database.FunctionCommit()
            flightinfo_flight_ids = database.queryTabel('TaskFlightinfo{}'.format(nowDayStr), '*',"航班来源 ='飞机排班'")
            if len(flightinfo_flight_ids) != 0 :
                for iii in flightinfo_flight_ids:
                    datas = baseFunction.TuplefindInList1(flightinfo_flight_ids , iii[0], 0)[0]
                    if str(iii[0]) not in flight_id_now:
                        cancelid = datas[35] if datas[35] else 0
                        newcancelid = int(cancelid) + 1
                        if int(newcancelid) < 3:
                            newdic = {"取消标志" : "'%s'" % newcancelid}
                            database.lazyUpdateItem('TaskFlightinfo{}'.format(nowDayStr) , newdic ,"航班编号='%s'" % iii[0])
                        else:
                            database.deleteSingledata("TaskFlightinfo{}".format(nowDayStr),"航班编号='%s'" %f"{iii[0]}")
                            #waringinsert(database,f"{datas[1]}/{datas[12]}Sytem航班删除！",f"System{datas[0]}","Sytem航班自动删除")
                        database.FunctionCommit()
    except Exception as e:
        #print(e)
        database.FunctionCommit()
        app_logger.log_error(e)
        app_logger.log_error("飞机排班系统校验航班失败")

    print(datetime.datetime.now(),'[数据库操作]结束校验航班')