import datetime

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

newWorkloadLabel=get_dic("newWorkloadLabel")
startimeReDic={"WXJJ":25,"WXAP":100,"WXAF":0,"WXTAF":0,"FXAP":100,"FXAF":0,"FXTAF":0,"FXTR":0,"WXES":35}
endtimeReDic={"WXJJ":10,"WXAP":10,"WXAF":120,"WXTAF":60,"FXAP":10,"FXAF":120,"FXTAF":60,"FXTR":30,"WXES":10}
standvalueReDic={"WXJJ":0.3,"WXES":0.4,"WXAP":0.6,"WXAF":1,"WXTAF":0.8,"FXAP":0.9,"FXAF":1.2,"FXTAF":1,"FXTR":0.3}

#注意，在航后接机，特后前接机需要移除放行，否则会平摊过多分值


def Computer(workload,ids ,start ,end ,bay ,peoples,flightdate,taskid,flighttype,day,workloadinfos,time1,time2,standtime,type,jbry,fx=None):#TIME1 到位时间  TIME2 离开时间 standtime 标准工时，type保障类型
    fxpeople=fx.replace("√","") if fx else ""
    typedic={"接机勤务":"-1-","送机勤务":"-2-","航前放行":"-3-","航后放行":"-3-","特后前放行":"-3-","短停放行":"-3-","航前维修":"-4-","航后维修":"-5-","特后前维修":"-6-"}
    startime = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S")-datetime.timedelta(minutes=time1+1)
    if end != "":
        endtime = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")+datetime.timedelta(minutes=time2)
        if endtime < datetime.datetime.now():
            flightsts = "完工"
            endtime_str = '[实]' + endtime.strftime("%Y-%m-%d %H:%M:%S")
        elif startime > datetime.datetime.now():
            flightsts = "未开始"
            endtime_str = '[预]' + endtime.strftime("%Y-%m-%d %H:%M:%S")
        else:
            flightsts = "进行中"
            endtime_str = '[预]' + endtime.strftime("%Y-%m-%d %H:%M:%S")
    else:
        endtime =datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S")+datetime.timedelta(minutes=time2)
        endtime_str='[预]'+endtime.strftime("%Y-%m-%d %H:%M:%S")
        if startime < datetime.datetime.now():
            flightsts = "进行中"
        else:
            flightsts = "未开始"

    costtime = (endtime - startime).total_seconds() / 60
    standardcost = (costtime / (time1+time2)) * standtime
    peopleslist=peoples.replace("√","").replace(fxpeople,"").split(",")
    for people in peopleslist:
        single_standardcost = round(standardcost/len(peopleslist),2)
        jb = ""
        if jbry != "":
            if people in jbry:
                jb1 = datetime.datetime.strptime(day+" 09:10:00","%Y%m%d %H:%M:%S")
                limit = datetime.datetime.strptime(day+" 11:10:00","%Y%m%d %H:%M:%S")
                jb2 = datetime.datetime.strptime(day+" 20:40:00","%Y%m%d %H:%M:%S")
                if startime < jb1:
                    endtime = jb1 + datetime.timedelta(minutes=25)
                    endtime_str = '[实]' + endtime.strftime("%Y-%m-%d %H:%M:%S")
                    flightsts = "完工"
                    jb = "交班"
                elif limit < startime < jb2:
                    endtime = jb2+datetime.timedelta(minutes=25)
                    endtime_str = '[实]' + endtime.strftime("%Y-%m-%d %H:%M:%S")
                    flightsts = "完工"
                    jb = "交班"
            else:
                jb1 = datetime.datetime.strptime(day + " 09:10:00", "%Y%m%d %H:%M:%S")
                limit = datetime.datetime.strptime(day+" 11:10:00","%Y%m%d %H:%M:%S")
                jb2 = datetime.datetime.strptime(day + " 20:40:00", "%Y%m%d %H:%M:%S")
                if startime < jb1:
                    startime = jb1
                    jb = "接班"
                elif limit < startime < jb2:
                    startime = jb2
                    jb = "接班"
                if endtime <= startime:
                    endtime = startime+datetime.timedelta(minutes=30)
                    if datetime.datetime.now() >= endtime:
                        flightsts = "完工"
                    else:
                        flightsts = "进行中"


        id = taskid+typedic[type]+people
        if id not in ids and id not in nowids:
            nowids.append(id)
            #print(nowids)
            newdic = {"编号":id,"任务编号":taskid,"航班日期":flightdate,"首次时间":startime,"开始时间":startime,"结束时间":endtime_str,
                    "机位":bay,"类型":type,"总用时":costtime,"标准工时":single_standardcost,"人员":people,"航班状态":flightsts,'备1':flighttype,"备3": jb}
            for i in newWorkloadLabel:
                if i not in newdic.keys():
                    newdic[i] = ""
            workload.lazyInsertData('workload%s'%day, newdic)
        else:
            oldflightsts= baseFunction.TuplefindInList3(workloadinfos , id , 0 , 12)
            if oldflightsts != "完工":
                newdic = {"开始时间":"'%s'"%startime,"结束时间":"'%s'"%endtime_str,"总用时":"'%s'"%costtime,
                        "标准工时":"'%s'"%single_standardcost,"航班状态":"'%s'"%flightsts,"备3":"'%s'"%jb}
                workload.lazyUpdateItem('workload%s'%day, newdic, "编号='{}'".format(id))


def checkWorkerlaod_new(database:flightDB, workload:flightDB,nowDayStr1,nowDay_11):
    global nowids
    nowids = []
    if nowDayStr1 == nowDay_11:
        checkdays = [nowDayStr1]
    else:
        checkdays = [nowDayStr1, nowDay_11]
    try:
        for day in checkdays:
            flightinfos=database.queryTabel('TaskFlightinfo{}'.format(day), '*', "维修人员 !='' or 放行人员 !='' or 二次送机 !=''")
            workloadinfos=workload.queryTabel('workload{}'.format(day), '*', "编号 !=''")
            workload_ids_arr=[]
            if workloadinfos and len(workloadinfos) != 0:
                for workloadinfo in workloadinfos:
                    workload_ids_arr.append(workloadinfo[0])
            workloadAllidsnow=[]
            if flightinfos and len(flightinfos) != 0:
                for flightinfo in flightinfos:
                    if flightinfo[12] and flightinfo[3] == "TR" and flightinfo[8]:  #如果是短停\航后 特后前，且接机人员不是空
                        peopleslist = flightinfo[12].replace("√", "").split(",")
                        for people in peopleslist:
                            workloadAllidsnow.append((flightinfo[0]+"-1-"+people))
                        Computer(workload,workload_ids_arr,flightinfo[8],flightinfo[6],flightinfo[10],flightinfo[12],flightinfo[2],flightinfo[0],
                                 flightinfo[3],day,workloadinfos,startimeReDic['WXJJ'],endtimeReDic['WXJJ'],standvalueReDic['WXJJ'],"接机勤务",flightinfo[37])
                    elif flightinfo[12] and flightinfo[3] == "AP" and flightinfo[5]:
                        peopleslist = flightinfo[12].replace("√", "").split(",")
                        for people in peopleslist:
                            workloadAllidsnow.append((flightinfo[0]+"-4-"+people))
                        Computer(workload,workload_ids_arr,flightinfo[5],flightinfo[7],flightinfo[11],flightinfo[12],flightinfo[2],flightinfo[0],
                                 flightinfo[3],day,workloadinfos,startimeReDic['WXAP'],endtimeReDic['WXAP'],standvalueReDic['WXAP'],"航前维修",flightinfo[37])
                    elif flightinfo[12] and flightinfo[3] == "AF" and flightinfo[8]:
                        peopleslist = flightinfo[12].replace("√", "").split(",")
                        for people in peopleslist:
                            workloadAllidsnow.append((flightinfo[0]+"-5-"+people))
                        Computer(workload,workload_ids_arr,flightinfo[8],flightinfo[6],flightinfo[10],flightinfo[12],flightinfo[2],flightinfo[0],
                                 flightinfo[3],day,workloadinfos,startimeReDic['WXAF'],endtimeReDic['WXAF'],standvalueReDic['WXAF'],"航后维修",flightinfo[37],flightinfo[13])

                    elif flightinfo[12] != "" and flightinfo[3] == "TAF" and flightinfo[8]:
                        peopleslist = flightinfo[12].replace("√", "").split(",")
                        for people in peopleslist:
                            workloadAllidsnow.append((flightinfo[0]+"-6-"+people))
                        Computer(workload,workload_ids_arr,flightinfo[8],flightinfo[6],flightinfo[10],flightinfo[12],flightinfo[2],flightinfo[0],
                                 flightinfo[3],day,workloadinfos,startimeReDic['WXTAF'],endtimeReDic['WXTAF'],standvalueReDic['WXTAF'],"特后前维修",flightinfo[37],flightinfo[13])

                    if flightinfo[13] != "" and flightinfo[3] == "TR" and flightinfo[8]: #放行计算
                        peopleslist = flightinfo[13].replace("√", "").split(",")
                        for people in peopleslist:
                            workloadAllidsnow.append((flightinfo[0]+"-3-"+people))
                        Computer(workload,workload_ids_arr,flightinfo[8],flightinfo[6],flightinfo[10],flightinfo[13],flightinfo[2],flightinfo[0],
                                 flightinfo[3],day,workloadinfos,startimeReDic['FXTR'],endtimeReDic['FXTR'],standvalueReDic['FXTR'],"短停放行",flightinfo[37])
                    elif flightinfo[13] != "" and flightinfo[3] == "AP" and flightinfo[5]:
                        peopleslist = flightinfo[13].replace("√", "").split(",")
                        for people in peopleslist:
                            workloadAllidsnow.append((flightinfo[0]+"-3-"+people))
                        Computer(workload,workload_ids_arr,flightinfo[5],flightinfo[7],flightinfo[11],flightinfo[13],flightinfo[2],flightinfo[0],
                                 flightinfo[3],day,workloadinfos,startimeReDic['FXAP'],endtimeReDic['FXAP'],standvalueReDic['FXAP'],"航前放行",flightinfo[37])
                    elif flightinfo[13] != "" and flightinfo[3] == "TAF" and flightinfo[8]:
                        peopleslist = flightinfo[13].replace("√", "").split(",")
                        for people in peopleslist:
                            workloadAllidsnow.append((flightinfo[0]+"-3-"+people))
                        Computer(workload,workload_ids_arr,flightinfo[8],flightinfo[6],flightinfo[10],flightinfo[13],flightinfo[2],flightinfo[0],
                                 flightinfo[3],day,workloadinfos,startimeReDic['FXTAF'],endtimeReDic['FXTAF'],standvalueReDic['FXTAF'],"特后前放行",flightinfo[37])
                    elif flightinfo[13] != "" and flightinfo[3] == "AF" and flightinfo[8]:
                        peopleslist = flightinfo[13].replace("√", "").split(",")
                        for people in peopleslist:
                            workloadAllidsnow.append((flightinfo[0]+"-3-"+people))
                        Computer(workload,workload_ids_arr,flightinfo[8],flightinfo[6],flightinfo[10],flightinfo[13],flightinfo[2],flightinfo[0],
                                 flightinfo[3],day,workloadinfos,startimeReDic['FXAF'],endtimeReDic['FXAF'],standvalueReDic['FXAF'],"航后放行",flightinfo[37])

                    if flightinfo[19] != "" and flightinfo[3] != "AF" and flightinfo[5]:
                        peopleslist = flightinfo[19].replace("√", "").split(",")
                        for people in peopleslist:
                            workloadAllidsnow.append((flightinfo[0]+"-2-"+people))
                        Computer(workload,workload_ids_arr,flightinfo[5],flightinfo[7],flightinfo[11] if flightinfo[3] == "AP" else flightinfo[10],flightinfo[19],
                                 flightinfo[2],flightinfo[0],flightinfo[3],day,workloadinfos,startimeReDic['WXES'],endtimeReDic['WXES'],standvalueReDic['WXES'],"送机勤务",flightinfo[37])

                workload.FunctionCommit()
            Cancelresult = [x for x in workload_ids_arr if x not in workloadAllidsnow]
            for x in Cancelresult:
                taskid = x.split("-")[0]
                JBRY= baseFunction.TuplefindInList3(flightinfos , taskid , 0 , 37)
                people= baseFunction.TuplefindInList3(workloadinfos , x , 0 , 11)
                if people not in JBRY and "人工" not in x:
                    newdic={"备2":"'1'"}
                    workload.lazyUpdateItem('workload%s' % day,  newdic, "编号='{}'".format(x))
                else:
                    newdic = {"备2": "'0'"}
                    workload.lazyUpdateItem('workload%s' % day, newdic, "编号='{}'".format(x))
            workload.FunctionCommit()
    except Exception as e:
        app_logger.log_error(e)
        app_logger.log_error(flightinfo)



