import datetime

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


def FlightSearchInsert(database: flightDB, datatime: str, jsonData):
    tasktype=get_dic('taskType')
    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('flightsearchLabel')
        flightinfo_flight_ids_arr = []
        flightinfo_flight_ids = database.queryTabel('FlightSearch{}'.format(nowDayStr), '*', "FLIGHT_ID !=''")#确认一下要不要取整张表
        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 :
            last_acno=""
            try:
                for row in jsonData:
                    flight_id_now.append(row["FLIGHT_ID"])
                    if str(row["FLIGHT_ID"]) not in str(flightinfo_flight_ids_arr) and str(insertdate) == row["FLIGHT_DATE"]:
                        newDic={}
                        for key in keys:
                            if key in row.keys():
                                newDic[key] = str(row[key])
                            else:
                                newDic[key] = ""
                        database.lazyInsertData('FlightSearch{}'.format(nowDayStr), newDic)
                    elif str(row["FLIGHT_ID"]) in str(flightinfo_flight_ids_arr):
                        for key in keys:
                            if key in row.keys():
                                b = baseFunction.TuplefindInList3(flightinfo_flight_ids , row[ "FLIGHT_ID" ] , 0 , keys.index(key))
                                if b != row[key]:
                                    newdic = {"%s"%key: "'%s'" % row[key]}
                                    database.lazyUpdateItem('FlightSearch{}'.format(nowDayStr), newdic,"FLIGHT_ID='%s'" % row["FLIGHT_ID"])
                            else:
                                newdic = {"%s"%key: "''"}
                                database.lazyUpdateItem('FlightSearch{}'.format(nowDayStr), newdic,"FLIGHT_ID='%s'" % row["FLIGHT_ID"])
                    if last_acno != row["ACNO"] and row["DEP_CH"] == "天府":
                        newDic2 = {"backup1": "'AP'","backup2": "'航前'"}
                        database.lazyUpdateItem('FlightSearch{}'.format(nowDayStr), newDic2, "FLIGHT_ID='%s'" % row["FLIGHT_ID"])
                    else:
                        newDic2 = {"backup1": "'%s'"%row["TASKTYPE"] if "TASKTYPE" in row else "'未显示'","backup2": "'%s'"%tasktype[row["TASKTYPE"]] if "TASKTYPE" in row else "'未显示'"}
                        database.lazyUpdateItem('FlightSearch{}'.format(nowDayStr), newDic2,"FLIGHT_ID='%s'" % row["FLIGHT_ID"])
                    last_acno = row["ACNO"]
                database.FunctionCommit()
            except Exception as e:
                database.FunctionCommit()
                app_logger.log_error(e)
                app_logger.log_error(row)
                pass
        else:
            print(datetime.datetime.now(), "[数据库操作]FlightSearch航班数据为空")
            app_logger.log_error("[数据库操作]FlightSearch航班数据为空")
            pass
        if jsonData !="" and jsonData !=None and jsonData != {} and len(flight_id_now) != 0 and len(jsonData)!=0:
            flightinfo_flight_ids = database.queryTabel('FlightSearch{}'.format(nowDayStr),'*',"FLIGHT_ID !=''")
            if len(flightinfo_flight_ids) != 0:
                for iii in flightinfo_flight_ids:
                    if str(iii[0]) not in flight_id_now :
                        database.deleteSingledata("FlightSearch{}".format(nowDayStr), "FLIGHT_ID='%s'" % str(iii[0]) )
            database.FunctionCommit()
        '''
        flightinfo_flight_ids = database.sort_queryTable2("*",'FlightSearch{}'.format(nowDayStr), "FLIGHT_ID !=''","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('FlightSearch{}'.format(nowDayStr), newDic2, "FLIGHT_ID='%s'" % row[0])
                else:
                    newDic2 = {"backup3": "'%s'" % row[12], "backup4": "'%s'" % tasktype[row[12]]}
                    database.lazyUpdateItem('FlightSearch{}'.format(nowDayStr), newDic2, "FLIGHT_ID='%s'" % row[0])

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