import datetime

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


def postgresql_bakup(bakcup:flightDB,main:flightDB,type):
    print(datetime.datetime.now(), "[主从同步]开始同步数据库")
    logintoken_dic=['id','username','token']
    loginsts_dic=['id','sts']
    logintable_dic=['id',"登录名","密码","权限","使用人"]
    today = datetime.datetime.now().strftime('%Y%m%d')
    yesterday=(datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%Y%m%d')
    tomorrow=(datetime.datetime.now() + datetime.timedelta(days=1)).strftime('%Y%m%d')
    table_colmuns={"peopleschedule%s"%today:get_dic('peopleScheduleLabel'),"peopleschedule%s"%yesterday:get_dic('peopleScheduleLabel'),"peopleschedule%s"%tomorrow:get_dic('peopleScheduleLabel'),
                   'risktable':get_dic('RiskLabel'),'workerinfo':get_dic('workerinfoLabel'),'pglist%s'%today:get_dic('pglistLabel'),'pglist%s'%yesterday:get_dic('pglistLabel'),
                   'logs':get_dic('logsLabel'),'taskauto':get_dic('taskLabel'),'calllist':get_dic('CalllistLabel'),
                   'flightsts%s'%today:get_dic('flightstsLabel'),'flightsts%s'%yesterday:get_dic('flightstsLabel'),
                   'logintoken':logintoken_dic,'loginsts':loginsts_dic,'logintable':logintable_dic,
                   "TaskFlightinfo%s"%today:get_dic('TaskflightinfoLabel'),"TaskFlightinfo%s"%yesterday:get_dic('TaskflightinfoLabel'),"TaskFlightinfo%s"%tomorrow:get_dic('TaskflightinfoLabel'),
                   "flightsearch%s"%today:get_dic('flightsearchLabel'),"flightsearch%s"%yesterday:get_dic('flightsearchLabel'),"flightsearch%s"%tomorrow:get_dic('flightsearchLabel'),
                   "sortFlight%s"%today:get_dic('sortLabel'),"sortFlight%s"%yesterday:get_dic('sortLabel'),"sortFlight%s"%tomorrow:get_dic('sortLabel'),"display":get_dic('displayLabel'),
                   "sortFlight2%s"%today:get_dic('sortLabel'),"sortFlight2%s"%yesterday:get_dic('sortLabel'),"sortFlight2%s"%tomorrow:get_dic('sortLabel'),
                   }
    if type == 1:
        dbtables=["peopleschedule%s"%today,"peopleschedule%s"%yesterday,"peopleschedule%s"%tomorrow,'risktable',
                  'workerinfo','pglist%s'%today,'pglist%s'%yesterday,'taskauto','calllist',
                  'flightsts%s'%today,'flightsts%s'%yesterday,
                  "TaskFlightinfo%s"%today,"TaskFlightinfo%s"%yesterday,"TaskFlightinfo%s"%tomorrow,
                  "flightsearch%s"%today,"flightsearch%s"%yesterday,"flightsearch%s"%tomorrow,
                  "sortFlight%s"%today,"sortFlight%s"%yesterday,"sortFlight%s"%tomorrow,
                  "sortFlight2%s"%today,"sortFlight2%s"%yesterday,"sortFlight2%s"%tomorrow,
                  "display"]#logs太大无法同步
    elif type == 2:
        dbtables=['logintable']
    elif type == 3:
        dbtables=['logintoken','loginsts']
    try:
        tablesok=""
        tablenum=0
        for dbtable in dbtables:
            try:
                if type == 1:
                    Dic = {}
                    primaryKey2 = 'text'
                    for key in list(table_colmuns[dbtable])[1:]:
                        Dic[key] = 'text'
                    main.initTable(dbtable, table_colmuns[dbtable][0], primaryKey2, Dic)
                all_source_data=bakcup.getAlldata(dbtable)
                if len(all_source_data)!=0:
                    main.lazydeleteTable(dbtable)
                    if dbtable=="display":
                        dispaly_res=main.getSingledata("A", 'display')
                        if dispaly_res == None or len(dispaly_res) == 0:
                            main.insertData('display', {'ID': 1, 'A': '{}', 'B': '{}'})
                            main.insertData('display', {'ID': 2, 'A': '{}', 'B': '{}'})
                            main.insertData('display', {'ID': 3, 'A': '{}', 'B': '{}'})
                        for row in all_source_data:
                            newdic = {"A": '"{}"'.format(row[1]),"B": '"{}"'.format(row[2])}
                            main.lazyUpdateItem(dbtable, newdic, "ID = '%s'"%row[0])
                        #online.FunctionCommit()
                    else:
                        for row in all_source_data:
                            main.lazyInsertData2(dbtable,', '.join(table_colmuns[dbtable]),row)
                    main.FunctionCommit()
                tablesok=tablesok+dbtable+"/"
                tablenum+=1
            except Exception as e:
                app_logger.log_error(e)
                continue
        print(datetime.datetime.now(), "[主从同步]完成数据库同步(%s[%s])"%(tablesok,tablenum))
        return "ok"
    except Exception as e:
        app_logger.log_error(e)
        return "fail"
