import datetime

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


def FlightPlanInsert(database: flightDB, datatime: str, jsonData):
    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"
    c_str = nowDay_str2 + " 09:00:00"
    time1 = datetime.datetime.strptime(a_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]
    if nowDayStr in days:
        keys=get_dic('flightplanflightinfoLabel')
        flightinfo_flight_ids_arr = []
        flightinfo_flight_ids = database.queryTabel('flightplaninfo{}'.format(nowDayStr), '*', "flightId !=''")#确认一下要不要取整张表
        if len(flightinfo_flight_ids) != 0:
            for i in flightinfo_flight_ids:
                flightinfo_flight_ids_arr.append(i[0])
        flight_id_now = []
        if jsonData !="" and  jsonData !=None and jsonData != {} and len(jsonData)!=0 :
            try:
                for row in jsonData:
                    targets = ["321","320","319","737","C919","C909","ARJ21"]
                    ac_type = row.get("acType" , "")
                    if (row.get("arrAirportAbbr","") == "天府" or row.get("depAirportAbbr","") == "天府") and any(target in ac_type for target in targets) and not ("备降" == str(row.get("flgVr", "")) and bool(row.get("fplAirport1Abbr", ""))):
                        flight_id_now.append(row["flightId"])
                        if str(row["flightId"]) not in str(flightinfo_flight_ids_arr) and str(insertdate) == row["flightDate"]:
                            newDic={}
                            for key in keys:

                                if key in row.keys() and row[key]:
                                    if key == "acReg" :
                                        newDic[key] = str(row[key].replace("B", ""))
                                    else:
                                        newDic[key] = str(row[key])
                                else:
                                    newDic[key] = ""
                            if (row["arrAirportAbbr"] == "天府" and datetime.datetime.strptime(row["sta"], "%Y-%m-%d %H:%M:%S") <= (datetime.datetime.now() + datetime.timedelta(hours=11))) or \
                                    (row["depAirportAbbr"] == "天府" and datetime.datetime.strptime(row["std"], "%Y-%m-%d %H:%M:%S") <= (datetime.datetime.now() + datetime.timedelta(hours=12))):
                                newDic["备1"] = "1"
                            database.lazyInsertData('flightplaninfo{}'.format(nowDayStr), newDic)
                        elif str(row["flightId"]) in str(flightinfo_flight_ids_arr):
                            for key in keys:
                                if key in row.keys():
                                    b = baseFunction.TuplefindInList3(flightinfo_flight_ids, row["flightId"], 0, keys.index(key))
                                    if key == "acReg" :
                                        row[key]= str(row[ key ].replace("B" , ""))
                                    if b != row[key] and row[key]:
                                        newdic = {"%s"%key: "'%s'" % row[key]}
                                        database.lazyUpdateItem('flightplaninfo{}'.format(nowDayStr), newdic,"flightId='%s'" % row["flightId"])
                                elif key != "备1":
                                    newdic = {"%s"%key: "''"}
                                    database.lazyUpdateItem('flightplaninfo{}'.format(nowDayStr), newdic,"flightId='%s'" % row["flightId"])
                            if (row["arrAirportAbbr"] == "天府" and datetime.datetime.strptime(row["sta"], "%Y-%m-%d %H:%M:%S") <= (datetime.datetime.now() + datetime.timedelta(hours=11))) or \
                                    (row["depAirportAbbr"] == "天府" and datetime.datetime.strptime(row["std"], "%Y-%m-%d %H:%M:%S") <= (datetime.datetime.now() + datetime.timedelta(hours=12))):
                                newdic = {"备1": "'1'"}
                                #database.lazyUpdateItem('flightplaninfo{}'.format(nowDayStr), newdic,"flightId='%s'" % row["flightId"])

                            else:
                                newdic = {"备1": "''"}
                            database.lazyUpdateItem('flightplaninfo{}'.format(nowDayStr), newdic,"flightId='%s'" % row[ "flightId" ])

                database.FunctionCommit()
            except Exception as e:
                database.FunctionCommit()
                app_logger.log_error(e)
                app_logger.log_error(row)
                pass
        else:
            print(datetime.datetime.now(), "[数据库操作]flightplaninfo航班数据为空")
            app_logger.log_error("[数据库操作]flightplaninfo航班数据为空")
            pass
        if jsonData !="" and jsonData !=None and jsonData != {} and len(flight_id_now) != 0 and len(jsonData)!=0:
            flightinfo_flight_ids = database.queryTabel('flightplaninfo{}'.format(nowDayStr),'*',"flightId !=''")
            if len(flightinfo_flight_ids) != 0:
                for iii in flightinfo_flight_ids:
                    if str(iii[0]) not in flight_id_now:
                        database.deleteSingledata("flightplaninfo{}".format(nowDayStr), "flightId='%s'" % str(iii[0]) )
            database.FunctionCommit()
        '''
        flightinfo_flight_ids = database.sort_queryTable2("*",'flightplaninfo{}'.format(nowDayStr), "flightId !=''","ACNO","ASC","STD","ASC")
        flightinfo_flight_ids2 = database.queryTabel('TaskFlightinfo{}'.format(nowDayStr),"*", "备5 !='' and 备4 =''")
        flightinfo_flight_ids_check = flightinfo_flight_ids2 if flightinfo_flight_ids2 != None else ""
        if len(flightinfo_flight_ids) != 0:
            last_acno = ""
            for row in flightinfo_flight_ids:
                if row[0] in str(flightinfo_flight_ids_check) or  (last_acno != row[2] and row[4] == "天府"):
                    newDic2 = {"backup3": "'AP'", "backup4": "'航前'"}
                    database.lazyUpdateItem('flightplaninfo{}'.format(nowDayStr), newDic2, "flightId='%s'" % row[0])
                else:
                    newDic2 = {"backup3": "'%s'" % row[12], "backup4": "'%s'" % tasktype[row[12]]}
                    database.lazyUpdateItem('flightplaninfo{}'.format(nowDayStr), newDic2, "flightId='%s'" % row[0])

                last_acno = row[2]
            database.FunctionCommit()
        #'''