import datetime

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


def postgresql_local(local:flightDB,host_online, port_online, user_online, password_online, database_online):
    print(datetime.datetime.now(), "[同步中心]开始同步数据库")

    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')
    online=flightDB(host_online, port_online, user_online, password_online, database_online)
    '''
    table_colmuns={"flightinfo%s"%today:flightinfoLabel,"flightinfo%s"%yesterday:flightinfoLabel,"flightinfo%s"%tomorrow:flightinfoLabel,
                   "peopleschedule%s"%today:peopleScheduleLabel,"peopleschedule%s"%yesterday:peopleScheduleLabel,"peopleschedule%s"%tomorrow:peopleScheduleLabel,
                   "sortFlight%s"%today:sortLabel,"sortFlight%s"%yesterday:sortLabel,"sortFlight%s"%tomorrow:sortLabel,
                   "display":displayLabel}
    '''
    table_colmuns={"TaskFlightinfo%s"%today:get_dic("TaskflightinfoLabel"),"TaskFlightinfo%s"%yesterday:get_dic("TaskflightinfoLabel"),"TaskFlightinfo%s"%tomorrow:get_dic("TaskflightinfoLabel"),
                   "peopleschedule%s"%today:get_dic('peopleScheduleLabel'),"peopleschedule%s"%yesterday:get_dic('peopleScheduleLabel'),"peopleschedule%s"%tomorrow:get_dic('peopleScheduleLabel'),
                   "sortFlight%s"%today:get_dic('sortLabel'),"sortFlight%s"%yesterday:get_dic("sortLabel"),"sortFlight%s"%tomorrow:get_dic("sortLabel"),
                   "display":get_dic("displayLabel"),"flightsearch%s"%today:get_dic("flightsearchLabel"),"flightsearch%s"%yesterday:get_dic("flightsearchLabel"),"flightsearch%s"%tomorrow:get_dic("flightsearchLabel"),}
    dbtables=["TaskFlightinfo%s"%today,"TaskFlightinfo%s"%yesterday,"TaskFlightinfo%s"%tomorrow,
              "peopleschedule%s"%today,"peopleschedule%s"%yesterday,"peopleschedule%s"%tomorrow,
              "flightsearch%s"%today,"flightsearch%s"%yesterday,"flightsearch%s"%tomorrow,
              "sortFlight%s"%today,"sortFlight%s"%yesterday,"sortFlight%s"%tomorrow,"display"]
    try:
        tablesok=""
        tablenum=0
        for dbtable in dbtables:
            try:
                Dic = {}
                primaryKey2 = 'text'
                for key in list(table_colmuns[dbtable])[1:]:
                    Dic[key] = 'text'
                online.initTable(dbtable, table_colmuns[dbtable][0], primaryKey2, Dic)
                all_source_data=local.getAlldata(dbtable)
                if len(all_source_data)!=0:

                    online.lazydeleteTable(dbtable)
                    if dbtable=="display":
                        dispaly_res=online.getSingledata("A", 'display')
                        if dispaly_res == None or len(dispaly_res) == 0:
                            online.insertData('display', {'ID': 1, 'A': '{}', 'B': '{}'})
                            online.insertData('display', {'ID': 2, 'A': '{}', 'B': '{}'})
                            online.insertData('display', {'ID': 3, 'A': '{}', 'B': '{}'})
                        for row in all_source_data:
                            newdic = {"A": '"{}"'.format(row[1]),"B": '"{}"'.format(row[2])}
                            online.lazyUpdateItem(dbtable, newdic, "ID = '%s'"%row[0])
                        #online.FunctionCommit()
                    else:
                        for row in all_source_data:
                            online.lazyInsertData2(dbtable,', '.join(table_colmuns[dbtable]),row)
                    online.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"
