import datetime

from unitls.LogerinTxt import app_logger
from .flightDB import flightDB
from unitls import baseFunction


def sort_and_renumber_dict(nested_dict, sort_key, secondary_key=None, reverse=False,secondary_reverse=False):
    # 1. 将原始字典的值转换为列表
    items_list = list(nested_dict.values())

    # 2. 按双条件排序
    if secondary_key:
        sorted_list = sorted(
            items_list,
            key=lambda x: (x[sort_key], x[secondary_key]),
            reverse=secondary_reverse
        )
    else:
        sorted_list = sorted(items_list, key=lambda x: x[sort_key], reverse=reverse)

    # 3. 创建新字典，使用连续整数作为键
    new_dict = {}
    for new_key, item in enumerate(sorted_list):
        new_dict[new_key] = item
    return new_dict



def Getworkload(fdb:flightDB,workload: flightDB,names):
    res={}
    flighttypedic={"TR":"短停","AF":"航后","AP":"航前","TAF":"特后前","":"未显示"}
    dic={"FX":"放行","WX":"维修员","":"未分配"}
    nowDay = datetime.date.today().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")
    a_str = nowDay + " 09:00:00"
    b_str = nowDay + " 20:30:00"
    a = datetime.datetime.strptime(a_str, "%Y%m%d %H:%M:%S")
    b = datetime.datetime.strptime(b_str, "%Y%m%d %H:%M:%S")
    nowtime = datetime.datetime.now()
    if a < nowtime < b:
        date = [nowDay]
        bcdate = nowDay
        bc="A"
    elif b <= nowtime:
        date = [nowDay, nowDay_2]
        bcdate = nowDay
        bc = "B"
    else:
        date = [nowDay_1, nowDay]
        bcdate = nowDay_1
        bc = "B"
    allworkloaddatas=[]
    allpeopleschedule=[]
    allflightinfo=[]
    try:
        if names:
            lastBchandoverinfos=[]
            if len(date) == 1:
                daytime=(datetime.datetime.strptime(date[0],'%Y%m%d')-datetime.timedelta(days=4)).strftime('%Y%m%d')
                lastBchandoverinfos = workload.queryTabel("workload%s"%daytime,"*","(备3 ='交班' and 备4 !='N') or 备4 ='Y'") #上个班的交接情况
            for day in date:
                daily_data = workload.sort_queryTable("*","workload%s"%day,  "备2 != '1'",'结束时间','ASC')
                if daily_data:  # 确保有数据返回
                    allworkloaddatas.extend(daily_data)
                peopleschedule= fdb.queryTabel("peopleschedule%s"%day,"*","显示模式='A' and ('放行' !='' or '勤务1' !='' or '勤务2' !='' or '工1' !='' or '工2' !='' or '工3' !='')")
                if peopleschedule:  # 确保有数据返回
                    allpeopleschedule.extend(peopleschedule)
                flightinfo=  fdb.queryTabel("taskflightinfo%s"%day,"*","航班编号 !=''")
                if flightinfo:  # 确保有数据返回
                    allflightinfo.extend(flightinfo)
            if allworkloaddatas !=[]:
                allpeopleionfos=fdb.queryTabel("pglist%s"%bcdate,"*","班次='%s'"%bc)
                sqinfos=fdb.queryTabel('workerinfo',"*","姓名!=''")
                num = 0
                for name in names:
                    signalpeopleinfo= baseFunction.TuplefindInList1(allpeopleionfos , name , 0)
                    singlepeopledata= baseFunction.TuplefindInList11(allworkloaddatas , name , 11)#所有工时内容
                    hbsinglepeopledata= baseFunction.TuplefindInList8(singlepeopledata , 'Y' , 17)#非人工的工作内容
                    rgsinglepeopledata= baseFunction.TuplefindInList11(singlepeopledata , 'Y' , 17)#人工修正工作内容
                    notfinshsinglepeopledata= baseFunction.TuplefindInList8(hbsinglepeopledata , '完工' , 12) #未完工的内容
                    singlesqinfo= baseFunction.TuplefindInList1(sqinfos , name , 1)
                    preinfos= baseFunction.TuplefindInList111(allpeopleschedule , name)
                    workrole=dic[signalpeopleinfo[0][2]]
                    noteinfo=signalpeopleinfo[0][4]
                    handoverSts=""
                    handoverids=""
                    if len(date) == 1:
                        handoverinfos= baseFunction.TuplefindInList33(lastBchandoverinfos , name , 11 , 0)
                        if handoverinfos:
                            handoverSts="Y"
                            handoverids=",".join(handoverinfos)
                    sq = singlesqinfo[0][8].replace("*","") if singlesqinfo else ""
                    zgzl=len(hbsinglepeopledata)#总工作量
                    wwcgz=len(notfinshsinglepeopledata) #当前未完成工作量
                    zys = baseFunction.TuplefindInList9(singlepeopledata , 9) #总用时
                    zgs = baseFunction.TuplefindInList9(singlepeopledata , 10) #总的标准工时
                    rggs = baseFunction.TuplefindInList9(rgsinglepeopledata , 10) #人工标准工时
                    xzgs = baseFunction.TuplefindInList9(rgsinglepeopledata , 10) #修正工作时间的总长
                    dqgz = "无"
                    if notfinshsinglepeopledata:
                        for i in notfinshsinglepeopledata:
                          dqgz = i[4][-8:-3]+"-"+i[5][-8:-3]+"/"+i[6]+i[8][:2] if dqgz == "无" else dqgz+"\n"+ i[4][-8:-3]+"-"+i[5][-8:-3]+"/"+i[6]+i[8][:2]

                    xzxq = "无"
                    if rgsinglepeopledata:
                        for i in rgsinglepeopledata:
                            xzxq ="修正详情:"+"\n"+ i[18]+"/"+i[10] if xzxq == "无" else xzxq+"\n"+i[18]+"/"+i[10]
                    res[num]={
                        '0':num+1,
                        '1':handoverSts,
                        '2':name,
                        '3':handoverids,
                        '4':workrole,
                        '5':'',
                        '6':sq,
                        '7':'',
                        '8':f'{zgzl}({wwcgz})',
                        '9':'',
                        '10':wwcgz,
                        '11':'',
                        '12':zgzl,
                        '13':'',
                        '14':f'{zgs}({rggs})',
                        '15':'',
                        '16':dqgz,
                        '17':'',
                        '18':xzgs,
                        '19':'',
                        '20':xzxq,
                        '21':noteinfo,
                        '22':'',
                        '23':'',
                        '24':'',
                        '25':'',
                        '26':'',
                        '27':'',
                        '28':'',
                        '29':'',
                        '30':'',
                        '31':'',
                        '32':'',
                        '33':'',
                        '34':'',
                        '35':'',
                        '36':'',
                        '37':'',
                        '38':'',
                        '39':'',
                        '40':'',
                        '41':'',
                        '42':'',
                        '43':'',
                        '44':'',
                        '45':'',
                        '46':'',
                        '47':'',
                    }
                    num1 = 28
                    if hbsinglepeopledata:
                        for i in singlepeopledata:
                            res[num][str(num1)] = i[5][-8:-3]+"\n"+i[8][:2]+"/"+i[6]
                            num1 += 1
                    if preinfos:
                        for i in preinfos:
                            isok=False
                            preflightinfos= baseFunction.TuplefindInList1(allflightinfo , i[1 ] , 0)[0 ]
                            if i[0][-3] == "1" and preflightinfos[3] == "TR" and preflightinfos[8] != "":
                                endtime=(datetime.datetime.strptime(preflightinfos[8], "%Y-%m-%d %H:%M:%S")+ datetime.timedelta(minutes=10)).strftime("%H:%M")
                                flighttyep="短停接"
                                bay=preflightinfos[10]
                                isok = True
                            elif i[0][-3] == "1" and preflightinfos[3] == "AF" and preflightinfos[8] != "":
                                endtime=(datetime.datetime.strptime(preflightinfos[8], "%Y-%m-%d %H:%M:%S")+ datetime.timedelta(minutes=120)).strftime("%H:%M")
                                flighttyep="航后"
                                bay=preflightinfos[10]
                                isok = True
                            elif i[0][-3] == "1" and preflightinfos[3] == "TAF" and preflightinfos[8] != "":
                                endtime=(datetime.datetime.strptime(preflightinfos[8], "%Y-%m-%d %H:%M:%S")+ datetime.timedelta(minutes=60)).strftime("%H:%M")
                                flighttyep="特后前"
                                bay=preflightinfos[10]
                                isok = True
                            elif i[0][-3] == "2" and preflightinfos[3] != "AF" and preflightinfos[5] != "":
                                endtime=(datetime.datetime.strptime(preflightinfos[5], "%Y-%m-%d %H:%M:%S")+ datetime.timedelta(minutes=60)).strftime("%H:%M")
                                flighttyep="%s送"%flighttypedic[preflightinfos[3]]
                                if preflightinfos[3] !="AP":
                                    bay=preflightinfos[10]
                                else:
                                    bay=preflightinfos[11]
                                isok = True
                            if isok:
                                res[num][str(num1)] = endtime+"\n"+"预排"+flighttyep+"/"+bay
                                num1 += 1
                    num += 1
        res = sort_and_renumber_dict(
            res,
            sort_key="4",  # 第一排序条件：
            secondary_key="1",  # 第二排序条件：
            reverse=False,  # 第一升序
            secondary_reverse=True  # 第二降序
        )
        return res
    except Exception as e:
        app_logger.log_error(e)
        return res
