import datetime

from unitls.LogerinTxt import app_logger
from .flightDB import flightDB
from .initFlightDatabase import initFlightDatabase


def updateData(database:flightDB, id,taskid,time,flighttype,flight_date_str,classstr,nowDayStr):
    try:
        newdic = {"编号": "'%s'" % id, "航班编号": "'%s'" % taskid, "保障时间": "'%s'" % time, "航班类型": "'%s'"%flighttype,
                  "航班日期": "'%s'" % flight_date_str, "级别": "%s"%classstr}
        database.lazyUpdateItem("sortFlight{}".format(nowDayStr), newdic, "编号='%s'" % id)
    except Exception as e:
        #print(e)
        app_logger.log_error(e)

def insertData(database:flightDB, id,taskid,time,flighttype,flight_date_str,classstr,nowDayStr):
    if id not in lazyinsert:
        try:
            newdic = {"编号": "%s" % id, "航班编号": "%s" % taskid, "保障时间": "%s" % time, "航班类型": "%s"%flighttype,
                      "航班日期": '%s' % flight_date_str, "级别": classstr}
            database.lazyInsertData("sortFlight{}".format(nowDayStr), newdic)
            lazyinsert.append(id)
        except Exception as e:
            #print(e)
            app_logger.log_error(e)
    else:
        updateData(database, id, taskid, time, flighttype, flight_date_str, classstr, nowDayStr)


def checkData(database,taskid,sendtime,flighttype,flight_date_str,sort_flight_ids_arr,nowDayStr,classstr):
    if flighttype == "航前":
        ii = str(taskid) + "-2"  # 送
        iii = str(taskid) + "-1"  # 接
    elif flighttype == "航后":
        ii = str(taskid) + "-1"
        iii = str(taskid) + "-2"
    else:
        ii = str(taskid) + "-1"
        iii = ""
    if ii in str(sort_flight_ids_arr):
        updateData(database, ii, taskid, sendtime, flighttype, flight_date_str, classstr, nowDayStr)
    else:
        insertData(database, ii, taskid, sendtime, flighttype, flight_date_str, classstr, nowDayStr)
    if iii and iii in str(sort_flight_ids_arr):
        database.deleteSingledata('sortFlight{}'.format(nowDayStr), "编号='%s'" % iii)
        sort_flight_ids_arr.remove(iii)

def sortFlighttime(database:flightDB,wokload:flightDB):
    global lazyinsert
    lazyinsert = []
    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 = datetime.datetime.now()
        #now_20 = (datetime.datetime.now() + datetime.timedelta(minutes=200)).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:
            sort_flight_ids_arr = []
            sort_flight_ids = database.queryTabel('sortFlight{}'.format(nowDayStr),"*","编号 !=''")
            flightinfo_flight_ids = database.queryTabel('TaskFlightinfo{}'.format(nowDayStr), '*', "航班编号!=''")

            if sort_flight_ids and len(sort_flight_ids) != 0:
                for sortkey in sort_flight_ids:
                    sort_flight_id=sortkey[1]
                    #sort_flight_id = baseFunction.TuplefindInList3(sort_flight_ids, sortkey[0],0,1)
                    if str(sort_flight_id) in str(flightinfo_flight_ids):
                        sort_flight_ids_arr.append(sortkey[0])
                    else:
                        database.deleteSingledata('sortFlight{}'.format(nowDayStr),"编号='%s'"%sortkey[0])

            for i in flightinfo_flight_ids:
                flight_date_str = i[2]
                if i[3] == "AP" and "MAN" not in str(i[0]):
                    if i[7] == "" and i[5] != "": #flying 空 and std 不空
                        sendtime = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=90)
                        checkData(database,i[0],sendtime,"航前",flight_date_str,sort_flight_ids_arr,nowDayStr,1)
                    elif i[7] != "":
                        sendtime = datetime.datetime.strptime(i[7], "%Y-%m-%d %H:%M:%S")
                        checkData(database,i[0],sendtime,"航前",flight_date_str,sort_flight_ids_arr,nowDayStr,4)
                elif i[3] == "AP" and "MAN" in str(i[0]):
                        sendtime = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=90)
                        sendtime2 = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S")
                        if now < sendtime2:
                            checkData(database,i[0],sendtime,"航前",flight_date_str,sort_flight_ids_arr,nowDayStr,1)
                        else:
                            checkData(database,i[0],sendtime2,"航前",flight_date_str,sort_flight_ids_arr,nowDayStr,4)
                elif i[3] == "停场":
                    receivetime = datetime.datetime.strptime(i[6], "%Y-%m-%d %H:%M:%S")
                    checkData(database, i[0], receivetime, "停场", flight_date_str, sort_flight_ids_arr, nowDayStr, 3)

                elif i[3] == "AF" and "MAN" not in str(i[0]):
                    if i[6]=="" and i[8] !="" and i[30] != "":
                        receivetime = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        checkData(database, i[0], receivetime, "航后", flight_date_str, sort_flight_ids_arr, nowDayStr, 1)
                    elif i[6]=="" and i[8] =="" and i[30] != "":
                        receivetime = datetime.datetime.strptime(i[4], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        checkData(database, i[0], receivetime, "航后", flight_date_str, sort_flight_ids_arr, nowDayStr, 1)

                    elif i[6] == "" and i[30] == "" and i[8] == "" and i[4] != "":
                        receivetime = datetime.datetime.strptime(i[4], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        checkData(database,i[0],receivetime,"航后",flight_date_str,sort_flight_ids_arr,nowDayStr,2)

                    elif i[6] !="":
                        receivetime = datetime.datetime.strptime(i[6], "%Y-%m-%d %H:%M:%S")
                        checkData(database, i[0], receivetime, "航后", flight_date_str, sort_flight_ids_arr, nowDayStr, 3)
                    elif i[6] =="" and i[30] == "" and i[8] != "":
                        receivetime = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        checkData(database, i[0], receivetime, "航后", flight_date_str, sort_flight_ids_arr, nowDayStr, 2)

                elif i[3] == "AF" and "MAN" in str(i[0]):
                        receivetime = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        receivetime2= datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S")
                        if now < receivetime2:
                            checkData(database, i[0], receivetime, "航后", flight_date_str, sort_flight_ids_arr, nowDayStr, 1)
                        else:
                            checkData(database, i[0], receivetime2, "航后", flight_date_str, sort_flight_ids_arr, nowDayStr, 3)

                elif i[3] == "TR" and "MAN" not in str(i[0]):
                    if i[6] == "" and i[8] != "" and i[30] != "":
                        receivetime = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        ii=str(i[0])+ "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database,ii,i[0],receivetime,"短停接",flight_date_str,1,nowDayStr)
                        else:
                            insertData(database,ii,i[0],receivetime,"短停接",flight_date_str,1,nowDayStr)
                    elif i[6] =="" and i[8] == "" and i[30] != "":
                        receivetime = datetime.datetime.strptime(i[4], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        ii=str(i[0])+ "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database,ii,i[0],receivetime,"短停接",flight_date_str,1,nowDayStr)
                        else:
                            insertData(database,ii,i[0],receivetime,"短停接",flight_date_str,1,nowDayStr)
                    elif i[6] =="" and i[30] =="" and i[8] == "" and i[4] !="":
                        receivetime = datetime.datetime.strptime(i[4], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        ii=str(i[0])+ "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database,ii,i[0],receivetime,"短停接",flight_date_str,2,nowDayStr)
                        else:
                            insertData(database,ii,i[0],receivetime,"短停接",flight_date_str,2,nowDayStr)
                    elif i[6] =="" and i[30] =="" and i[8] !="":
                        receivetime = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        ii=str(i[0])+ "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database,ii,i[0],receivetime,"短停接",flight_date_str,2,nowDayStr)
                        else:
                            insertData(database,ii,i[0],receivetime,"短停接",flight_date_str,2,nowDayStr)

                    elif i[6] !="":
                        receivetime = datetime.datetime.strptime(i[6], "%Y-%m-%d %H:%M:%S")
                        ii=str(i[0])+ "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database,ii,i[0],receivetime,"短停接",flight_date_str,4,nowDayStr)
                        else:
                            insertData(database,ii,i[0],receivetime,"短停接",flight_date_str,4,nowDayStr)

                elif i[3] == "TR" and "MAN" in str(i[0]):
                        receivetime = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        receivetime2 = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S")
                        if now < receivetime2:
                            ii=str(i[0])+ "-1"
                            if ii in str(sort_flight_ids_arr):
                                updateData(database,ii,i[0],receivetime,"短停接",flight_date_str,1,nowDayStr)
                            else:
                                insertData(database,ii,i[0],receivetime,"短停接",flight_date_str,1,nowDayStr)
                        else:
                            ii=str(i[0])+ "-1"
                            if ii in str(sort_flight_ids_arr):
                                updateData(database,ii,i[0],receivetime2,"短停接",flight_date_str,4,nowDayStr)
                            else:
                                insertData(database,ii,i[0],receivetime2,"短停接",flight_date_str,4,nowDayStr)

                elif i[3] == "TAF" and "MAN" not in str(i[0]):
                    if i[6] == "" and i[8] != "" and i[30] != "":
                        receivetime = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        ii = str(i[0]) + "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 1, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 1, nowDayStr)
                    elif i[6] == "" and i[8] == "" and i[30] != "":
                        receivetime = datetime.datetime.strptime(i[4], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        ii = str(i[0]) + "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 1, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 1, nowDayStr)
                    elif i[6] == "" and i[30] == "" and i[8] == "" and i[4] != "":
                        receivetime = datetime.datetime.strptime(i[4], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        ii = str(i[0]) + "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 2, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 2, nowDayStr)
                    elif i[6] == "" and i[30] == "" and i[8] != "":
                        receivetime = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                        ii = str(i[0]) + "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 2, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 2, nowDayStr)

                    elif i[6] != "":
                        receivetime = datetime.datetime.strptime(i[6], "%Y-%m-%d %H:%M:%S")
                        ii = str(i[0]) + "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 4, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 4, nowDayStr)

                elif i[3] == "TAF" and "MAN" in str(i[0]):
                    receivetime = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=15)
                    receivetime2 = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S")
                    if now < receivetime2:
                        ii = str(i[0]) + "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 1, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime, "特后前接", flight_date_str, 1, nowDayStr)
                    else:
                        ii = str(i[0]) + "-1"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime2, "特后前接", flight_date_str, 4, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime2, "特后前接", flight_date_str, 4, nowDayStr)


                if i[3] == "TR" and "MAN" not in str(i[0]):
                    if i[7] != "":
                        receivetime = datetime.datetime.strptime(i[7], "%Y-%m-%d %H:%M:%S")- datetime.timedelta(minutes=25)
                        ii=str(i[0])+ "-2"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database,ii,i[0],receivetime,"短停送",flight_date_str,4,nowDayStr)
                        else:
                            insertData(database,ii,i[0],receivetime,"短停送",flight_date_str,4,nowDayStr)
                    elif i[6] != "" and i[5] != "":
                        receivetime = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S")- datetime.timedelta(minutes=25)
                        ii = str(i[0]) + "-2"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "短停送", flight_date_str, 1, nowDayStr)
                        else:
                            insertData(database,  ii, i[0], receivetime, "短停送", flight_date_str, 1, nowDayStr)
                    elif i[5] != "":
                        receivetime = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S")- datetime.timedelta(minutes=25)
                        ii = str(i[0]) + "-2"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "短停送", flight_date_str, 2, nowDayStr)
                        else:
                            insertData(database,  ii, i[0], receivetime, "短停送", flight_date_str, 2, nowDayStr)

                elif i[3] == "TR" and "MAN" in str(i[0]):
                        receivetime1 = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S")
                        receivetime = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=25)
                        receivetime2 = datetime.datetime.strptime(i[5],"%Y-%m-%d %H:%M:%S")  #std
                        if now < receivetime1:
                            ii = str(i[0]) + "-2"
                            if ii in str(sort_flight_ids_arr):
                                updateData(database, ii, i[0], receivetime, "短停送", flight_date_str, 2, nowDayStr)
                            else:
                                insertData(database, ii, i[0], receivetime, "短停送", flight_date_str, 2, nowDayStr)
                        elif receivetime1 < now < receivetime2:
                            ii = str(i[0]) + "-2"
                            if ii in str(sort_flight_ids_arr):
                                updateData(database, ii, i[0], receivetime, "短停送", flight_date_str, 1, nowDayStr)
                            else:
                                insertData(database, ii, i[0], receivetime, "短停送", flight_date_str, 1, nowDayStr)
                        else:
                            ii=str(i[0])+ "-2"
                            if ii in str(sort_flight_ids_arr):
                                updateData(database, ii, i[0], receivetime2, "短停送", flight_date_str, 4, nowDayStr)
                            else:
                                insertData(database, ii, i[0], receivetime2, "短停送", flight_date_str, 4, nowDayStr)

                elif i[3] == "TAF" and "MAN" not in str(i[0]):
                    if i[7] != "":
                        receivetime = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S")- datetime.timedelta(minutes=25)
                        ii=str(i[0])+ "-2"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database,ii,i[0],receivetime,"特后前送",flight_date_str,4,nowDayStr)
                        else:
                            insertData(database,ii,i[0],receivetime,"特后前送",flight_date_str,4,nowDayStr)
                    elif i[7] == "" and i[6] !="" and i[5] !="":
                        receivetime = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S")- datetime.timedelta(minutes=25)
                        ii = str(i[0]) + "-2"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前送", flight_date_str, 1, nowDayStr)
                        else:
                            insertData(database,  ii, i[0], receivetime, "特后前送", flight_date_str, 1, nowDayStr)
                    elif i[7] == "" and i[6] =="" and i[5] !="":
                        receivetime = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S")- datetime.timedelta(minutes=25)
                        ii = str(i[0]) + "-2"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前送", flight_date_str, 2, nowDayStr)
                        else:
                            insertData(database,  ii, i[0], receivetime, "特后前送", flight_date_str, 2, nowDayStr)
                elif i[3] == "TAF" and "MAN" in str(i[0]):
                    receivetime1 = datetime.datetime.strptime(i[8], "%Y-%m-%d %H:%M:%S")
                    receivetime = datetime.datetime.strptime(i[5], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=25)
                    receivetime2 = datetime.datetime.strptime(i[5],"%Y-%m-%d %H:%M:%S")  #std
                    if now < receivetime1:
                        ii = str(i[0]) + "-2"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前送", flight_date_str, 2, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime, "特后前送", flight_date_str, 2, nowDayStr)
                    elif receivetime1 < now < receivetime2:
                        ii = str(i[0]) + "-2"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime, "特后前送", flight_date_str, 1, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime, "特后前送", flight_date_str, 1, nowDayStr)
                    else:
                        ii = str(i[0]) + "-2"
                        if ii in str(sort_flight_ids_arr):
                            updateData(database, ii, i[0], receivetime2, "特后前送", flight_date_str, 4, nowDayStr)
                        else:
                            insertData(database, ii, i[0], receivetime2, "特后前送", flight_date_str, 4, nowDayStr)
        database.FunctionCommit()
    except Exception as e:
        #print(e)
        database.FunctionCommit()
        app_logger.log_error(e)
        app_logger.log_error("排序失败，可能缺失航班")

    print(datetime.datetime.now(),'[数据库操作]结束排序')