import concurrent.futures
import datetime
import os
import random
import socket
import time
import traceback
from datetime import timedelta

import requests
from flask import Flask , render_template
from flask import request , jsonify
from flask_jwt_extended import JWTManager , create_refresh_token
from flask_jwt_extended import jwt_required , get_jwt_identity , create_access_token
from waitress import serve

from Functions import utils , DataComputer as DataComputer , ipcall , flaskDBUtils4PG as flaskDBUtils
from Functions.DButilsFunction import flightDB , judge_bc as Judge_bc , initFlightDatabase as InitFlightDatabase , \
    insertTaskDataToTable , sortFlighttime , sortFlighttime2 , checkTFUairplane , \
    createWorkloadtablesFromPg as CreateWorkloadtablesFromPg , \
    checkFlightAlert , dingdingDelete_flight , dingdingFlightsts , dingdinginfoget , calledChecked as CalledChecked , \
    infoConfirm as InfoConfirm , infoConfirm3 as InfoConfirm3 , infoConfirm2 as InfoConfirm2 , \
    maintainAuthCheck as MaintainAuthCheck , \
    checkLoadSingal as CheckLoadSingal , changepassword as Changepassword , postgresql_local , \
    mapDispaly as MapDispaly , \
    checkPglist as CheckPglist , updateEidteItem as UpdateEidteItem , updateDragDropItem as UpdateDragDropItem , \
    qtPeopleLoad as QtPeopleLoad , tableWidgetDispaly as TableWidgetDispaly , \
    tableWidgetDispaly2 as TableWidgetDispaly2 , \
    tableWidgetDispalyRead2 as TableWidgetDispalyRead2 , tableWidgetDispalyRead as TableWidgetDispalyRead , \
    bakupdata as Bakupdata , getphonelist as Getphonelist , MM_GJJH_LIST as mM_GJJH_LIST , \
    checkCalllist as CheckCalllist , \
    tableWidgetLOGDispaly as TableWidgetLOGDispaly , tableWidgetDisplayChange as TableWidgetDisplayChange , \
    manAddFlight as ManAddFlight , get_dic as Get_dic , manChangests as ManChangests , insertLogs as InsertLogs , \
    insertLogs2 as InsertLogs2 , \
    selftaxiLogs as SelftaxiLogs , taskAtuoCheck as TaskAtuoCheck , deleteFlight as DeleteFlight , \
    get_empNos as Get_empNos , updateTaskAuto as UpdateTaskAuto , insertCalllist as InsertCalllist , \
    insertWorkjob as InsertWorkjob , \
    getRiskData as GetRiskData , saveRisktable as SaveRisktable , updateRiskdb as UpdateRiskdb , \
    updateStopFlight as UpdateStopFlight , \
    dealLogs as DealLogs , update_Pglist as Update_Pglist , getWorkjobInfo as GetWorkjobInfo , \
    mandealAllLogs as MandealAllLogs , \
    calltry as Calltry , callon as Callon , get_empNos_phoone as Get_empNos_phoone , FlightSearchInsert , \
    TaskListInsert , checkWorkerlaod_new , \
    GetPglistInDatabase , Getworkload , HandoverStsChange , ManCahangeWorkload , UpdateNoteItem , postgresql_bakup , \
    UpdatePeopleScheduleFromOnline , FlightPlanInsert , checkFlightplan
from unitls.LogerinTxt import app_logger
from unitls.StaticDataclass import initialize_file , write_status_to_file
from unitls.settings import DBServer, flightDB4 , DataTransferMode , Server_Class , Main_Sever , databasefileDB , \
    Oline_flight

#requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

'''
200 OK：请求成功，常用于GET和POST请求。

201 Created：请求成功并创建了新资源。

301 Moved Permanently：资源已永久移动到新位置。

302 Found：资源临时移动。

400 Bad Request：请求语法错误，服务器无法理解。

401 Unauthorized：请求需要身份验证。

403 Forbidden：服务器拒绝执行请求。

404 Not Found：服务器无法找到请求的资源。

500 Internal Server Error：服务器内部错误，无法完成请求。

503 Service Unavailable：服务器因超载或维护暂时无法处理请求。
'''

#初始化Flask应用
app = Flask(__name__)
app.config['initialized'] = False
app.config['JWT_SECRET_KEY'] = 'your-secret-key'  # 设置JWT密钥
# 设置普通JWT过期时间
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=1)
# 设置刷新JWT过期时间
app.config["JWT_REFRESH_TOKEN_EXPIRES"] = timedelta(days=30)
app.config["SECRET_KEY"] = "Can't not guess it ."
jwt = JWTManager(app)
dir = os.getcwd()

dbhost, dbport, dbuser, dbpassword,online_host, online_port, online_user, online_password = DBServer()
mainseverip, maindatabase=Main_Sever()
backupactive = False #备用服务器激活标注
database="flaskDatabase"
databaseDB4 = flightDB4()
databaseWorkLoad = 'workLoad'
databaseLoginDB = 'loginDB'
databasefileDB=databasefileDB()
SameDatabase,HighRefreh,Online_flight_sts=Oline_flight()
flightDataTransfer,displayDataTransfer=DataTransferMode()
ServerClas = Server_Class()
severVersion = "18.0.0"
displayVersion = "18.0.0"
print(f"当前客户端版本：{severVersion}/白板版本：{displayVersion}")
print(f"当前服务器为:【{ServerClas}】")
print(f"当前服务器航班数据传输模式为:【{flightDataTransfer}】")
print(f"当前服务器显示计算请求模式为:【{displayDataTransfer}】")
print(f"在线编辑模式:【{Online_flight_sts}】")
print(f"一期二期服务器是否统一:【{SameDatabase}】")
print(f"在线编辑高刷模式:【{HighRefreh}】")
VinA1="328"
VinA2="328"
VinA3="328"
VinB1="328"
VinB2="328"
VinB3="328"

# 获取本地IP地址
def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))  # 连接到Google DNS服务器
        ip = s.getsockname()[0]
        s.close()
        return ip
    except:
        return socket.gethostbyname(socket.gethostname())

def check_a_availability():
    """检查A服务器的可用性"""
    try:
        ip = "http://" + mainseverip + ":5001/static/health"
        response = requests.get(ip, timeout=5)
        return response.status_code != 200  #看是否连接成功
    except Exception as e:
        return True  #出问题了

# 健康检查接口
@app.route('/static/health')
def health_check():
    try:
        # 检查数据库连接
        db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
        db.close()
        return jsonify({"status": "ok", "msg":{"timestamp": datetime.datetime.now().isoformat()}}), 200
    except Exception as e:
        return jsonify({"status": "error", "msg": str(e)}), 500

#userdatabase
import sqlite3
def create_user_table():
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    cur_str = """
        CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, 
        username TEXT NOT NULL, 
        password TEXT NOT NULL, 
        roles TEXT NOT NULL )
    """
    c.execute(cur_str)
    conn.commit()
    conn.close()
    print("Table created successfully")
def insert_user(username, password, roles):
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    result = query_user(username)
    if not result:
        cur_str="""
        INSERT INTO users (username, password, roles) VALUES ("{}", "{}", "{}")""".format(username, password, roles)
        c.execute(cur_str)
        conn.commit()
        print("User ({}) inserted successfully".format(username))
    else:
        print("User {} already exists".format(username))
    conn.close()

def query_user(username):
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    cur_str="""
    SELECT * FROM users WHERE username = "{}" """.format(username)
    result = c.execute(cur_str).fetchall()
    return result

def verify_user(username, password):
    result = query_user(username)
    if not result:
        print("User ({}) doesn't exist".format(username))
        return False
    else:
        if result[0][2] == password:
            return True
        else:
            return False

def returnTrue(message, data):
    return jsonify(msg=message, data=data)

#用户注册与登录
@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    print(data)
    username = data.get('username')
    password = data.get('password')

    insert_user(username, password, 'general')



    return jsonify({'msg': 'User created successfully'}), 201


@app.route('/getAccessToken', methods=['POST'])
def get_access_token():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')


    if verify_user(username, password):
        access_token = create_access_token(identity=username)
        refresh_token = create_refresh_token(identity=username)
        return jsonify(access_token=access_token, refresh_token=refresh_token, msg="Login {} success".format(username)), 200

    return jsonify({'msg': 'Invalid credentials'}), 401

@app.route('/loginTable', methods=['POST'])
def loginTable():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    remote_addr = request.remote_addr
    res1={"返回值":""}
    #t1 = datetime.datetime.now()
    loginTabledb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseLoginDB)
    #t2 = datetime.datetime.now()
    #print(f'登录时间:{t2 - t1}')
    res=loginTabledb.queryTabel('logintable', '*', "登录名='{}' and 密码='{}'".format(username,password))
    loginTabledb.close()
    if res !=[]:
        access_token = create_access_token(identity=username)
        refresh_token = create_refresh_token(identity=username)
        res1["返回值"]=res[0]
        return jsonify(data=res1, access_token=access_token, refresh_token=refresh_token), 200
    print(datetime.datetime.now(),"[%s]%s尝试登录" %(remote_addr,username))
    #t3 = datetime.datetime.now()
    #print(f'处理时间:{t3-t2}')
    return jsonify(msg=(datetime.datetime.now(),"[%s]%s尝试登录失败" %(remote_addr,username)), data=res1), 401

@app.route('/static/remoteCheck', methods=['POST']) #操作系统版本验证
def remoteCheck():
    data = request.get_json()
    checknumber = data.get('checknumber')
    if checknumber ==severVersion:
        res={"返回值":"ok"}
    else:
        res={"返回值":severVersion}
    res['msg']="check server version"
    return jsonify(res)
@app.route('/static/remoteCheck2', methods=['POST']) #电子白板系统版本验证
def remoteCheck2():
    data = request.get_json()
    checknumber = data.get('checknumber')
    if checknumber ==displayVersion:
        res={"返回值": "ok"}
    else:
        res={"返回值": displayVersion}
    res['msg']="check display version"
    return jsonify(res)

@app.route('/bakupdata')
def bakupdata():
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    Bakupdata(fdb)
    fdb.close()
    print(datetime.datetime.now(), "[%s]5分钟间隔自动备份"%remote_addr)
    return jsonify(status="ok")

@app.route('/postgresql')
def postgresql():
    try:
        if flightDataTransfer == 1:
            local = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
            try:
                postgresql_local(local,online_host,online_port,online_user,online_password,databaseDB4)
            except:
                local.close()
                print(datetime.datetime.now(), "[远端链接失败]云端数据库服务器")
                return jsonify(status="fail")
            local.close()
        if displayDataTransfer == 1:
            res= DataComputer.mytask()
            if res == "ok":
                url = "https://"+online_host+":7162/computerDispalydata"
                #url = "https://192.168.2.87:5070/computerDispalydata"
                try:
                    ress=requests.get(url, verify=False)
                    ress.raise_for_status()  # 检查HTTP状态码是否为成功
                    data = ress.json()
                    #ress=requests.post(url, cert=('D:\\flightinfo\\DATABASE\\sichuanair.com.pem','D:\\flightinfo\\DATABASE\\sichuanair.com.key')).json()
                    if data == "ok":
                    #if data.get("result") == "ok":
                        print(datetime.datetime.now(), "远端显示中心计算请求成功")
                    else:
                        print(datetime.datetime.now(), "[返回为fail]远端显示中心计算请求失败")
                except Exception as e:
                    print(e)
                    print(datetime.datetime.now(), "[请求被拒绝]远端显示中心计算请求失败")
        return jsonify(status="ok", msg=("远端显示中心计算请求成功"))
    except:
        print(traceback.format_exc())
        return jsonify(status="fail", msg=("[返回为fail]远端显示中心计算请求失败"))

def tableWidgetDispalyN(selectedtime,date):
    #t1 = datetime.datetime.now()
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    #t2 = datetime.datetime.now()
    #print(f'航班刷新登录时间:{t2 - t1}')
    res=TableWidgetDispaly(fdb,selectedtime,date)
    fdb.close()
    #print(datetime.datetime.now(),res)
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]A模式航班信息刷新请求[%s]"%(remote_addr,date))
    #t3 = datetime.datetime.now()
    #print(f'航班刷新处理时间:{t3 - t2}')
    return res
def tableWidgetDispaly2N(selectedtime,date):
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=TableWidgetDispaly2(fdb,selectedtime,date)
    fdb.close()
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]B模式航班信息刷新请求[%s]"%(remote_addr,date))
    return res
def updatetimer():

    db = flaskDBUtils.flaskDB(host = dbhost , port = dbport , user = dbuser , password = dbpassword ,database = database)
    try:
        today = datetime.datetime.now().strftime("%Y%m%d")
        tomorrow = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y%m%d")
        yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d")
        dict={"1":yesterday,"2":today, "3":tomorrow}
        for key,value in dict.items():
            tableWidgetDispalyN(value,key)
            tableWidgetDispaly2N(value,key)
        flaskDBUtils.updateALlVin(db)
        #print(VinA1 , VinA2 , VinA3 , VinB1 , VinB2 , VinB3)
    except Exception as e:
        print(traceback.format_exc())
        db.close()


def task_function(taskname, paramaDict):
    #ts = time.time()
    #print('开始请求：{}'.format(taskname))
    time.sleep(random.randint(10,100)/100)
    if taskname == "taskflightdata":
        result = fl.request_task_filght_list(paramaDict['nowDayStr'], paramaDict['token'])
    elif taskname == "Thirdtaskflightdata":
        result = fl.request_task_filght_third_list(paramaDict['nowDayStr'], paramaDict['token'])
    elif taskname == "flightsearch":
        result = fl.request_LM_FLIGHT_SEARCH_LIST(paramaDict['nowDayStr'], paramaDict['token'])
    elif taskname == "flightsearch_1":
        result = fl.request_LM_FLIGHT_SEARCH_LIST(paramaDict['nowDay_1'], paramaDict['token'])
    elif taskname == "TaskList":
        result = fl.request_LM_TASK_ARCHIVE_LIST(paramaDict['nowDayStr'], paramaDict['token'])
    elif taskname == "TaskList_1":
        result = fl.request_LM_TASK_ARCHIVE_LIST(paramaDict['nowDay_1'], paramaDict['token'])
    elif taskname == "FlightplanInfo":
        result = fl.request_flight_from_flightplan(paramaDict['nowDay_1'],paramaDict['nowDayStr'], paramaDict['token'])
    else:
        result = {'code': 404}
    #print("{} 请求耗时：{}".format(taskname, time.time()-ts))
    return result

@app.route('/getFlightData2', methods=['POST'])
async def getFlightData2():
    data = request.get_json()
    type = data.get('type')
    global singlePeopleNotice,loaclseverip
    db = flaskDBUtils.flaskDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=database)
    fdb = flightDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=databaseDB4)
    workLoad = flightDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=databaseWorkLoad)
    if Online_flight_sts == "1":
        onlinefileDB = flightDB(host=online_host, port=dbport, user=dbuser, password=dbpassword, database=databasefileDB)
    if (mainseverip and mainseverip == loaclseverip) or mainseverip == "" or (mainseverip and mainseverip != loaclseverip and check_a_availability()):
        try:
            #print(type)
            ts = time.time()
            taskname_queue = ["taskflightdata","Thirdtaskflightdata","flightsearch","TaskList","FlightplanInfo","flightsearch_1","TaskList_1"] #FlightplanInfo 飞机排班系统的航班嘻嘻你
            taskparama_queue = []
            date_time = Judge_bc()["date"]
            nowDay = datetime.datetime.now()
            nowDayStr = nowDay.strftime("%Y%m%d")
            now_130 = (datetime.datetime.now() + datetime.timedelta(minutes=300)).strftime("%Y%m%d")
            nowStr = nowDay.strftime("%Y%m%d %H:%M:%S")
            print(datetime.datetime.now(), "[判断：%s,当前：%s,+130：%s]" % (date_time, nowDayStr, now_130))
            if date_time == nowDayStr and now_130 == nowDayStr:  # 当班次判断为09：00-1900时，只查当日   1900取决于300min不取决于班次判断
                nowDay_1 =nowDayStr
                nowday_11=nowDayStr
                searchDay=f"{nowDayStr[:4]}-{nowDayStr[4:6]}-{nowDayStr[6:]}"
                start=nowDay.strftime('%Y-%m-%d 00:00:00')
                end= nowDay.strftime('%Y-%m-%d 00:00:00')

            elif date_time == nowDayStr and now_130 != nowDayStr:  # 当班次判断为1900-2400时，今日和明日
                nowDay_1 = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%Y%m%d")
                nowday_11=nowDayStr
                searchDay=f"{nowDayStr[:4]}-{nowDayStr[4:6]}-{nowDayStr[6:]}"
                start=nowDay.strftime('%Y-%m-%d 00:00:00')
                end= (datetime.date.today() + datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00')
            else:                                             #当班次判断为000-0900时，查昨日和今日
                nowDay_1 = date_time
                nowday_11= nowDayStr
                searchDay=f"{date_time[:4]}-{date_time[4:6]}-{date_time[6:]}"
                start=f"{date_time[:4]}-{date_time[4:6]}-{date_time[6:]} 00:00:00"
                end=nowDay.strftime('%Y-%m-%d 00:00:00')
            print('nowDay_1:{},nowday_11:{},searchDay:{}'.format(nowDay_1,nowday_11,searchDay))
            if type == "A":
                if str(flaskDBUtils.checkLogin(db)) == '1':
                    token,x_access_token = flaskDBUtils.getToken(db)
                    #print('db-token:{}'.format(token))
                    print(datetime.datetime.now(), "A动态获取获取[%s/%s]" % (nowDayStr, nowDay_1))
                    taskparama_queue.append({'nowDayStr':searchDay, 'token': token})
                    taskparama_queue.append({'nowDayStr':searchDay, 'token': token})
                    taskparama_queue.append({'nowDayStr':nowday_11, 'token': token})
                    taskparama_queue.append({'nowDayStr':nowday_11, 'token': token})
                    taskparama_queue.append({'nowDayStr':end,'nowDay_1': start, 'token': x_access_token})
                    taskparama_queue.append({'nowDay_1': nowDay_1, 'token': token})
                    taskparama_queue.append({'nowDay_1': nowDay_1, 'token': token})
                    flaskDBUtils.clearinfolog(db)
                    with concurrent.futures.ThreadPoolExecutor() as executor:
                        if nowday_11 == nowDay_1: #如果两个日期相同，只查一次避免相同
                            results = executor.map(task_function, taskname_queue[:5], taskparama_queue[:5])
                        else:
                            results = executor.map(task_function, taskname_queue, taskparama_queue)
                    resultsList = []
                    for result in results:
                        resultsList.append(result)
                    taskflightdata= resultsList[0]
                    Thirdtaskflightdata= resultsList[1]
                    flightsearchdata= resultsList[2]
                    tasklistdata= resultsList[3]
                    infoFromflightplan= resultsList[4] #飞机排班数据
                    #print(infoFromflightplan)
                    if nowday_11 != nowDay_1:  ##如果两个日期相同，就没有另外一天的数据
                        flightsearchdata_1= resultsList[5]
                        tasklistdata_1= resultsList[6]

                    if taskflightdata['code'] and taskflightdata['code'] != 200:
                        flaskDBUtils.logout(db)
                        flaskDBUtils.insertinfolog(db, nowStr, str(taskflightdata['code']))
                        InitFlightDatabase(fdb,workLoad, nowDayStr)
                        InitFlightDatabase(fdb,workLoad, nowDay_1)
                        sortFlighttime(fdb,workLoad)
                        sortFlighttime2(fdb,workLoad)
                        checkTFUairplane(fdb)
                        checkWorkerlaod_new(fdb,workLoad,nowDayStr,nowDay_1)
                        checkFlightAlert(fdb, singlePeopleNotice)
                        dingdingDelete_flight(fdb)
                        dingdingFlightsts(fdb)
                        dingdinginfoget(fdb)
                        CalledChecked(fdb)
                        if Online_flight_sts == "1" and  SameDatabase == "0":
                            res = UpdatePeopleScheduleFromOnline(fdb, onlinefileDB)
                            if res:
                                updatetimer()
                        else:
                            updatetimer()
                        print(datetime.datetime.now(), "A静态刷新")
                        code=str(taskflightdata['code'])
                    else:
                        #ts2 = time.time()
                        InitFlightDatabase(fdb,workLoad, nowDayStr)
                        InitFlightDatabase(fdb,workLoad, nowDay_1)
                        insertTaskDataToTable(fdb, nowDayStr, taskflightdata['data'], Thirdtaskflightdata['data'])
                        FlightSearchInsert(fdb, nowDayStr, flightsearchdata['data'])
                        TaskListInsert(fdb, nowDayStr, tasklistdata['data'])
                        if infoFromflightplan['code'] and infoFromflightplan['code'] == 200:
                            FlightPlanInsert(fdb, nowDayStr, infoFromflightplan['result'])
                        if nowday_11 != nowDay_1:  ##如果两个日期相同，就没有另外一天的数据，无需写入
                            insertTaskDataToTable(fdb, nowDay_1, taskflightdata['data'], Thirdtaskflightdata['data'])
                            FlightSearchInsert(fdb, nowDay_1, flightsearchdata_1['data'])
                            TaskListInsert(fdb, nowDay_1, tasklistdata_1['data'])
                            if infoFromflightplan['code'] and infoFromflightplan['code'] == 200:
                                FlightPlanInsert(fdb, nowDay_1, infoFromflightplan['result'])
                        checkFlightplan(fdb,workLoad)
                        sortFlighttime(fdb,workLoad)
                        sortFlighttime2(fdb,workLoad)
                        checkTFUairplane(fdb)
                        checkWorkerlaod_new(fdb,workLoad,nowDayStr,nowDay_1)
                        checkFlightAlert(fdb, singlePeopleNotice)
                        dingdingDelete_flight(fdb)
                        dingdingFlightsts(fdb)
                        dingdinginfoget(fdb)
                        CalledChecked(fdb)
                        flaskDBUtils.insertinfolog(db,nowStr,str(taskflightdata['code']))
                        if Online_flight_sts == "1":
                            if SameDatabase == "0":
                                UpdatePeopleScheduleFromOnline(fdb , onlinefileDB)
                        updatetimer()
                        print(datetime.datetime.now(), "A动态刷新")
                        #print('数据库耗时：{}'.format(time.time()-ts2))
                        code = str(taskflightdata['code'])+";刷新用时:"+str(time.time()-ts)
                else:
                    code = '未登录'
            else: #type==B
                InitFlightDatabase(fdb,workLoad, nowDayStr)
                InitFlightDatabase(fdb,workLoad, nowDay_1)
                sortFlighttime(fdb,workLoad)
                sortFlighttime2(fdb,workLoad)
                checkTFUairplane(fdb)
                checkWorkerlaod_new(fdb,workLoad,nowDayStr,nowDay_1)
                checkFlightAlert(fdb, singlePeopleNotice)
                dingdingDelete_flight(fdb)
                dingdingFlightsts(fdb)
                dingdinginfoget(fdb)
                CalledChecked(fdb)
                if Online_flight_sts == "1" and SameDatabase == "0":
                    res=UpdatePeopleScheduleFromOnline(fdb, onlinefileDB)
                    if res:
                        updatetimer()
                else:
                    updatetimer()
                print(datetime.datetime.now(),"B静态刷新")
                code = "200"
            if mainseverip and mainseverip != loaclseverip and type == "B":
                print(datetime.datetime.now(), '[系统警告]主服务器通讯失败，备份服务器工作中')
                main_fdb=flightDB(host=maindatabase, port=dbport, user=dbuser, password=dbpassword, database=databaseDB4)
                main_db = flaskDBUtils.flaskDB(host=maindatabase, port=dbport, user=dbuser, password=dbpassword, database=database)
                main_loginTabledb = flightDB(host=maindatabase, port=dbport, user=dbuser, password=dbpassword, database=databaseLoginDB)
                loginTabledb = flightDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=databaseLoginDB)
                try:
                    postgresql_bakup(fdb, main_fdb,1)
                    postgresql_bakup(db, main_db,3)
                    postgresql_bakup(loginTabledb, main_loginTabledb,2)
                    main_fdb.close()
                    main_db.close()
                    main_loginTabledb.close()
                except Exception as e:
                    main_fdb.close()
                    main_db.close()
                    main_loginTabledb.close()
                    print(datetime.datetime.now(), '[系统警告]向主数据传输失败')
            fdb.close()
            workLoad.close()
            db.close()
            if Online_flight_sts == "1":
                onlinefileDB.close()
            return jsonify(code=code, msg='正常刷新')
        except Exception as e:
            fdb.close()
            workLoad.close()
            db.close()
            if Online_flight_sts == "1":
                onlinefileDB.close()
            app_logger.log_error(e)
            return jsonify(code='未登录', msg=str(e))

    else:
        #需要加入数据库同步
        if type == "B":
            print(datetime.datetime.now(), '[主从备份]非主服务器,该服务器仅同步')
            main_fdb=flightDB(host=maindatabase, port=dbport, user=dbuser, password=dbpassword, database=databaseDB4)
            main_db = flaskDBUtils.flaskDB(host=maindatabase, port=dbport, user=dbuser, password=dbpassword, database=database)
            main_loginTabledb = flightDB(host=maindatabase, port=dbport, user=dbuser, password=dbpassword, database=databaseLoginDB)
            loginTabledb = flightDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=databaseLoginDB)
            try:
                postgresql_bakup(main_fdb,fdb,1)
                postgresql_bakup(main_db, db, 3)
                postgresql_bakup(main_loginTabledb, loginTabledb, 2)
                db.close()
                fdb.close()
                workLoad.close()
                main_fdb.close()
                main_db.close()
                main_loginTabledb.close()
                return '200'
            except Exception as e:
                print(e)
                db.close()
                fdb.close()
                workLoad.close()
                main_fdb.close()
                main_db.close()
                main_loginTabledb.close()
                print(datetime.datetime.now(), '[系统警告]从主数据备份失败')
                return '200'
        else:
            return "200"


@app.route('/static/linktest')
def linktest():

   return jsonify(status="ok", msg="linktest")
@app.route('/checkLogin')
def checkLogin():
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    cookie,x_access_token = flaskDBUtils.getToken(db)
    if str(flaskDBUtils.checkLogin(db)) == '1':
        logincode = fl.checkCookieSts(cookie)
        if logincode and logincode != 200:
            flaskDBUtils.logout(db)
            time.sleep(0.1)
    if str(flaskDBUtils.checkLoginflightplan(db)) == '1':
        flightplanlogincode = fl.checkCookieStsFLIGHTplan(x_access_token)
        if flightplanlogincode and flightplanlogincode != 200:
            flaskDBUtils.logoutflightplan(db)

            time.sleep(0.1)
    #db.close()

    return jsonify(code=str(flaskDBUtils.checkLogin(db)), msg=str("飞机排班为:"+flaskDBUtils.checkLoginflightplan(db)))
@app.route('/table')
def table():
    flaskDB = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    result = flaskDBUtils.getinfolog(flaskDB)
    flaskDB.close()
    dl = []
    if result !=None:
        for i in result:
            dl.append([i[0], i[1], i[2]])
        data = {
            "data":dl,
            'msg':"get table data"
        }
        #print(data)
        #print('get table data')
        return jsonify(data)

@app.route("/map/<selectedtime>")
def index(selectedtime):
    return render_template("map.html", selectedtime=selectedtime)
@app.route("/map/getSelectInf/<selectedtime>", methods=['POST','GET'])
def getSelectInf(selectedtime):
    if request.method == 'POST':
        result = request.form
        fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
        res = MapDispaly(fdb, selectedtime)
        data = res[result['bay']]
        fdb.close()
        return render_template('table.html', data=data)
    return 'err'
#------------------------------------------------------------------------------------------------


@app.route('/changeSinglepoepleNotice', methods=['POST'])
@jwt_required()
def changeSinglepoepleNotice():
    global singlePeopleNotice
    data = request.get_json()
    boolsts = data.get('boolsts')
    singlePeopleNotice = str(boolsts) == "1"
    write_status_to_file(singlePeopleNotice,'D:\\flightinfo\\DATABASE\\singlepoeple_notice.txt')
    return jsonify({"status": "success", "new_value": singlePeopleNotice, "msg":"changeSinglepoepleNotice"})

@app.route('/getSinglepoepleNotice')
@jwt_required()
def getSinglepoepleNotice():
    global singlePeopleNotice
    return jsonify({"singlepoepleNotice": singlePeopleNotice, "msg":"getSinglepoepleNotice"})

#受保护的路由
@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
    current_user_id = get_jwt_identity()
    return jsonify({'msg': f'Hello user {current_user_id}'}), 200

@app.route('/findserver')
def findserver():
    return jsonify(msg=ServerClas)



@app.route('/static/remoteCookielogin',methods=["POST"])
@jwt_required()
def remoteCookielogin():
    remote_addr = request.remote_addr
    data = request.get_json()
    username = data.get('username')
    cookie = data.get('cookie')
    cookie2 = data.get('cookie2')
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    user = username
    token = "{}".format(cookie)
    token2 = "{}".format(cookie2)

    flaskDBUtils.login(db, user, token, token2)
    db.close()
    if token != None:
        print(datetime.datetime.now(),"[%s]远程登录已获取Token"%remote_addr)
        return jsonify(msg=(datetime.datetime.now(),"[%s]远程登录已获取Token"%remote_addr), status = "ok")
    else:
        return jsonify(status="fail", msg=(datetime.datetime.now(),"[%s]远程登录获取Token失败！"%remote_addr))

@app.route('/static/remotelogin',methods=["POST"])
@jwt_required()
def remotelogin():
    remote_addr = request.remote_addr
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    user = username
    pwd =password
    #print(user, pwd)
    token,x_access_token = fl.start(user, pwd)
    flaskDBUtils.login(db, user, token,x_access_token)
    if token != None:
        print(datetime.datetime.now(),"[%s]远程登录已获取Token"%remote_addr)
        return jsonify(msg=(datetime.datetime.now(),"[%s]远程登录已获取Token"%remote_addr), status = "ok")
    else:
        return jsonify(status="fail", msg=(datetime.datetime.now(),"[%s]远程登录获取Token失败！"%remote_addr))

@app.route('/static/remotelogout')
@jwt_required()
def remotelogout():
    remote_addr = request.remote_addr
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    flaskDBUtils.logout(db)
    db.close()
    print(datetime.datetime.now(), "[%s]远程注销服务器AMRO账号"%remote_addr)
    return jsonify(stauts="ok", msg=("[%s]远程注销服务器AMRO账号"%remote_addr))

@app.route('/static/checkjobcard', methods=['GET', 'POST'])
@jwt_required()
def checkjobcard():
    remote_addr = request.remote_addr
    if request.method == 'GET':
        file_path = request.args.get('path')
    else:
        file_path = request.form.get('path')
    try:
        res= fl.request_jobcard("_udid=80c6089a041646db9c1d9f1a2bc1381a", file_path)
        print(datetime.datetime.now(), "[%s]调取电签工卡查询" % remote_addr)
    except Exception as e:
        app_logger.log_error(e)
        res = ""
    return jsonify(msg=res)

@app.route('/static/VinCheck', methods=['POST'])
@jwt_required()
def VinCheck():
    data = request.get_json()
    vinLcoal = data.get('vinLcoal')
    mode = data.get('mode')
    num = data.get('num')
    if int(num) !=4:
        db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
        vinOnline = flaskDBUtils.getVin(db,mode,int(num))
        db.close()
        if vinLcoal == vinOnline:
            a = "检验一致"
            res = {"返回值":"ok"}
        else:
            a = "服务器有更新"
            res = {"返回值": "update"}
    else:
        a = "非昨天、今天、明天无需获取"
        res = {"返回值": "ok"}
    remote_addr = request.remote_addr
    res['msg'] = ("[%s]刷新识别码监测:%s" % (remote_addr,a))
    print(datetime.datetime.now(), "[%s]刷新识别码监测:%s" % (remote_addr,a))
    return jsonify(res)



@app.route('/static/setIpPhone', methods=['POST'])
@jwt_required()
def setIpPhone():
    data = request.get_json()
    ip = data.get('ip')
    remote_addr = request.remote_addr
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    token=si.start(ip)
    if token != "fail":
        res={"返回值":"ok"}
        flaskDBUtils.setIpPhone(db, ip, token)
        print(datetime.datetime.now(), "[%s]自动网页电话登录成功[%s,%s]" % (remote_addr,ip, token))
        res['msg'] = ("[%s]自动网页电话登录成功[%s,%s]" % (remote_addr,ip, token))
    else:
        res={"返回值":"fail"}
        flaskDBUtils.setIpPhone(db, ip, None)
        print(datetime.datetime.now(), "[%s]自动网页电话登录失败[%s]" % (remote_addr,ip))
        res['msg']=("[%s]自动网页电话登录失败[%s]" % (remote_addr,ip))
    db.close()
    return jsonify(res)


@app.route('/static/maintainAuthCheck', methods=['POST'])
@jwt_required()
def maintainAuthCheck():
    data = request.get_json()
    name = data.get('name')
    flighttype = data.get('flighttype')
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=MaintainAuthCheck(fdb,name,flighttype)
    fdb.close()
    print(datetime.datetime.now(), "[%s]维修权限验证"%remote_addr)
    res['msg'] = ("[%s]维修权限验证"%remote_addr)
    return jsonify(res)


@app.route('/static/getPglist', methods=['POST'])
@jwt_required()
def getPglist():
    data = request.get_json()
    bcstr = data.get('bcstr')
    try:
        remote_addr = request.remote_addr
        #print('获取派工数据')
        bc=bcstr
        #bc = "B"  #需要获取
        db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
        token,x_access_token  = flaskDBUtils.getToken(db)
        db.close()
        #token = utils.flight_list.get_cookie()
        nowDay = datetime.datetime.now()
        nowDayStr = nowDay.strftime("%Y%m%d")
        nowDayStr2 = nowDay.strftime("%Y-%m-%d")
        # (self, taskid:str, shiftDate:str, shift:str, cookie):
        fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
        taskids=fdb.queryTabel("TaskFlightinfo{}".format(nowDayStr),"航班编号","进出港航班号 like '%3U%'")
        if taskids[0][0] != "":
            Pglistdata=fl.request_LM_TSK_EMP_PGLIST(taskids[0][0],nowDayStr2,bc,token)
            Update_Pglist(fdb,nowDayStr,bc,Pglistdata['data'])
            fdb.close()
            print(datetime.datetime.now(),"[%s]获取派工人员清单请求"%remote_addr)
            return jsonify(code=Pglistdata['code'], msg=(datetime.datetime.now(),"[%s]获取派工人员清单请求"%remote_addr))
        else:
            return jsonify(code='404', msg="获取派工失败"), 404
    except Exception as e:
        app_logger.log_error("获取派工失败")
        app_logger.log_error(e)
        return jsonify(code='404', msg="获取派工失败"), 500
@app.route('/static/getPglistInDatabase')
@jwt_required()
def getPglistInDatabase():
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    try:
        res = Judge_bc()
        ress = GetPglistInDatabase(fdb,res)
        fdb.close()
        return jsonify({"返回值":ress, "msg":"get PglistInDatabase success"})
    except Exception as e:
        fdb.close()
        app_logger.log_error(e)
        return jsonify({"返回值":[], "msg":"get PglistInDatabase fail"})

@app.route('/static/getworkload',methods=["POST"])
@jwt_required()
def getworkload():
    data = request.get_json()
    names = data.get('names')
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    workLoad = flightDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=databaseWorkLoad)
    try:
        res=Getworkload(fdb,workLoad,names)
        return jsonify(data=res, msg="get workload success")
    except Exception as e:
        fdb.close()
        workLoad.close()
        app_logger.log_error(e)
        return jsonify(data={}, msg="get workload fail")
@app.route('/static/manchangecosttime',methods=["POST"])
@jwt_required()
def manchangecosttime():
    remote_addr = request.remote_addr
    data = request.get_json()["data"]
    workLoad = flightDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=databaseWorkLoad)
    res=ManCahangeWorkload(workLoad,data)
    workLoad.close()
    return jsonify({"返回值":res, "msg":"manchangecosttime workload success"})

@app.route('/static/handoverflight',methods=["POST"])
@jwt_required()
def handoverflight():
    remote_addr = request.remote_addr
    data = request.get_json()["data"]
    workLoad = flightDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=databaseWorkLoad)
    res=HandoverStsChange(workLoad,data)
    workLoad.close()
    return jsonify({"返回值":res, "msg":"handoverflight workload success"})
@app.route('/static/handoverflightAMRO',methods=["POST"])
@jwt_required()
def handoverflightAMRO():
    remote_addr = request.remote_addr
    data = request.get_json()["data"]
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    token,x_access_token = flaskDBUtils.getToken(db)
    #token = utils.flight_list.get_cookie()

    Pglistdata=fl.request_LM_TSK_HANDOVER(data,token)
    if Pglistdata['code'] == 200:
        res = {"返回值": "ok"}
    else:
        res = {"返回值": "fail"}
    print(datetime.datetime.now(),"[%s]使用AMRO工作交接功能"%remote_addr)
    res['msg'] = (datetime.datetime.now(),"[%s]使用AMRO工作交接功能"%remote_addr)
    return jsonify(res)

@app.route('/static/MM_GJJH_LIST', methods=["POST"])
@jwt_required()
def MM_GJJH_LIST():
    remote_addr = request.remote_addr
    data = request.get_json()
    team = data.get('team')
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    token,x_access_token  = flaskDBUtils.getToken(db)
    db.close()
    Pglistdata=fl.request_MM_GJJH_LIST(token)
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    mM_GJJH_LIST(fdb,team,Pglistdata['data'])
    fdb.close()
    print(datetime.datetime.now(),"[%s]%s工具接还查询"%(remote_addr,team))
    return jsonify(code=str(Pglistdata['code']), msg=(datetime.datetime.now(),"[%s]%s工具接还查询"%(remote_addr,team)))

@app.route('/static/checkWorkjob', methods=["POST"])
@jwt_required()
def checkWorkjob():
    remote_addr = request.remote_addr
    data = request.get_json()
    taskid = data.get('taskid')
    res = {"返回值": "fail"}
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    token,x_access_token  = flaskDBUtils.getToken(db)
    db.close()
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    getinfos=GetWorkjobInfo(fdb,taskid)
    if getinfos !={}:
        getworkjob = fl.checkWorkjob(getinfos["taskids"], getinfos["acno"], getinfos["taskType"], getinfos["actype"], getinfos["startDate"], getinfos["endDate"], token)
        res=InsertWorkjob(fdb,getworkjob["data"],taskid)
        print(datetime.datetime.now(), "[%s]获取%s工作包请求"%(remote_addr,getinfos["acno"]))
    fdb.close()
    res['msg'] = ("[%s]获取%s工作包请求"%(remote_addr,getinfos["acno"]))
    return jsonify(res)

@app.route('/static/mandealAllLogs', methods=["POST"])
@jwt_required()
def mandealAllLogs():
    remote_addr = request.remote_addr
    data = request.get_json()
    mode = data.get('mode')
    user = data.get('user')
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    MandealAllLogs(fdb, user,mode)
    fdb.close()
    print(datetime.datetime.now(),"[%s]%s人工处理所有待办"%(remote_addr,user))
    return jsonify(status="ok", msg=(datetime.datetime.now(),"[%s]%s人工处理所有待办"%(remote_addr,user)))

@app.route('/static/calltry')
@jwt_required()
def calltry():
    remote_addr = request.remote_addr
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    phoneip=flaskDBUtils.getIpPhoneip(db)
    db.close()
    ip=phoneip["ip"]
    token = phoneip["token"]
    db.close()
    #print("客户端点击尝试拨打请求获取的IP：%s"%phoneip)
    if ip !="" and token!="":
        fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
        A=Calltry(fdb, ip,token)
        fdb.close()
        if A != "fail":
            res = {"返回值": "ok"}
            print(datetime.datetime.now(),"[%s]尝试自动拨打请求%s"%(remote_addr,A))
            res['msg'] = (datetime.datetime.now(),"[%s]尝试自动拨打请求%s"%(remote_addr,A))
        else:
            res = { "返回值" : "fail" , "msg":"auto call fail"}
    else:
        res = {"返回值": "fail", "msg":"auto call fail"}
    return jsonify(res)

@app.route('/static/manAddFlight', methods=["POST"])
@jwt_required()
def manAddFlight():
    data = request.get_json()
    flighttype = data.get('flighttype')
    acno = data.get('acno')
    eng = data.get('eng')
    actype = data.get('actype')
    flightno = data.get('flightno')
    flightdate = data.get('flightdate')
    bay = data.get('bay')
    eta = data.get('eta')
    etd = data.get('etd')
    user = data.get('user')
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=ManAddFlight(fdb,flighttype,acno,eng,actype,flightno,flightdate,bay,eta,etd,user)
    print(datetime.datetime.now(),"%s人工添加航班%s"%(user,flightno))
    fdb.close()
    res['msg'] = (datetime.datetime.now(),"%s人工添加航班%s"%(user,flightno))
    return jsonify(res)

@app.route('/static/getphonelist')
@jwt_required()
def getphonelist():
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=Getphonelist(fdb)
    remote_addr = request.remote_addr
    fdb.close()
    print(datetime.datetime.now(),"[%s]客户端获取通讯录名单"%remote_addr)
    return jsonify(data=res, msg=(datetime.datetime.now(),"[%s]客户端获取通讯录名单"%remote_addr))

@app.route('/static/deleteFlight', methods=['POST'])
@jwt_required()
def deleteFlight():
    remote_addr = request.remote_addr
    data = request.get_json()
    flightid = data.get('flightid')
    user = data.get('user')
    time = data.get('time')
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=DeleteFlight(fdb,flightid,time)
    fdb.close()
    print(datetime.datetime.now(),"[%s]%s删除航班操作(%s)"%(remote_addr,user,flightid))
    res['msg'] = (datetime.datetime.now(),"[%s]%s删除航班操作(%s)"%(remote_addr,user,flightid))
    return jsonify(res)

@app.route('/static/called/')
@jwt_required()
def calledChecked():
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    CalledChecked(fdb)
    fdb.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s]通话建立情况检查请求"%remote_addr)
    res['msg']=(datetime.datetime.now(),"[%s]通话建立情况检查请求"%remote_addr)
    return res

@app.route('/static/dingdong',methods=["POST"])
@jwt_required()
def dingdong():
    remote_addr = request.remote_addr
    data = request.get_json()["data"]
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    token,x_access_token =flaskDBUtils.getToken(db)
    db.close()
    LM_TSK_DINGDONG=fl.request_LM_TSK_DINGDONG(data,token)
    #print(data)
    if LM_TSK_DINGDONG['code'] and LM_TSK_DINGDONG['code'] == 200:
        res = {"返回值": "ok", "msg": (datetime.datetime.now(),"[%s]使用叮咚消息success"%remote_addr)}
    else:
        res = {"返回值": "fail", "msg": (datetime.datetime.now(),"[%s]使用叮咚消息fail"%remote_addr)}
    print(datetime.datetime.now(),"[%s]使用叮咚消息"%remote_addr)
    return jsonify(res)

@app.route('/static/LM_TSK_SURE_PG',methods=["POST"])
@jwt_required()
def LM_TSK_SURE_PG():
    remote_addr = request.remote_addr
    data = request.get_json()["data"]
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    token,x_access_token = flaskDBUtils.getToken(db)
    db.close()
    LM_TSK_SURE_PG=fl.request_LM_TSK_SURE_PG(data,token)
    #print(data)
    if LM_TSK_SURE_PG['code'] and LM_TSK_SURE_PG['code'] == 200:
        res = {"返回值": "ok", "msg":(datetime.datetime.now(),"[%s]使用派工success"%remote_addr)}
    else:
        res = {"返回值": "fail", "msg":(datetime.datetime.now(),"[%s]使用派工fail"%remote_addr)}
    print(datetime.datetime.now(),"[%s]使用派工"%remote_addr)
    return jsonify(res)

@app.route('/static/insertCalllist',methods=["POST"])
@jwt_required()
def insertCalllist():
    remote_addr = request.remote_addr
    data = request.get_json()["data"]
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=InsertCalllist(fdb, data)
    fdb.close()
    print(datetime.datetime.now(),"[%s]录入拨号数据库"%remote_addr)
    #print(datetime.datetime.now(),data)
    res['msg']=(datetime.datetime.now(),"[%s]录入拨号数据库"%remote_addr)
    return jsonify(res)

@app.route('/static/get_empNos_phoone', methods=['POST'])
@jwt_required()
def get_empNos_phoone():
    remote_addr = request.remote_addr
    data = request.get_json()
    name = data.get("name")
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=Get_empNos_phoone(fdb, name)
    fdb.close()
    print(datetime.datetime.now(),"[%s]获取员工号和电话号码"%remote_addr)
    #print(datetime.datetime.now(),data)
    return res

@app.route('/static/get_empNos',methods=["POST"])
@jwt_required()
def get_empNos():
    remote_addr = request.remote_addr
    data = request.get_json()["data"]
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=Get_empNos(fdb, data)
    fdb.close()
    print(datetime.datetime.now(),"[%s]获取员工号"%remote_addr)
    #print(datetime.datetime.now(),data)
    res['msg'] = (datetime.datetime.now(),"[%s]获取员工号"%remote_addr)
    return res

@app.route('/static/updatecheck')
@jwt_required()
def updatecheck():
    try:
        remote_addr = request.remote_addr
        flaskDB =flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
        updatests=flaskDBUtils.updatecheck(flaskDB)
        res = {"返回值":updatests}
        flaskDB.close()
        #print(res)
        print(datetime.datetime.now(),"[%s]客户端自动检查更新请求"%remote_addr)
        res['msg'] = (datetime.datetime.now(),"[%s]客户端自动检查更新请求"%remote_addr)
        return jsonify(res)
    except:
        return jsonify({"返回值": "0", 'msg':(datetime.datetime.now(),"[%s]客户端自动检查更新请求fail"%remote_addr)})

@app.route('/static/calling', methods=['POST'])  #呼出通话建立
@jwt_required()
def calling():
    remote_addr = request.remote_addr
    data = request.get_json()
    phonenum0 = data.get("phonenum0")
    #print(phonenum0)
    flaskDB = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    now=datetime.datetime.now()
    a=flaskDBUtils.callingphoneUpdate(flaskDB,phonenum0,now)
    res = {"返回值":"ok"}
    flaskDB.close()
    #print(res)
    print(datetime.datetime.now(),"[%s]%s自动电话通话正在呼出"%(remote_addr,phonenum0))
    res['msg'] = (datetime.datetime.now(),"[%s]%s自动电话通话正在呼出"%(remote_addr,phonenum0))
    return jsonify(res)

@app.route('/static/calldown')  #通话结束
@jwt_required()
def calldown():
    remote_addr = request.remote_addr
    flaskDB = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    now=datetime.datetime.now()
    a=flaskDBUtils.callingphoneUpdate(flaskDB,None,now)
    res = {"返回值":"ok"}
    flaskDB.close()
    #print(res)
    print(datetime.datetime.now(),"[%s]自动电话缓存恢复初始值"%remote_addr)
    res['msg'] =(datetime.datetime.now(),"[%s]自动电话缓存恢复初始值"%remote_addr)
    return jsonify(res)

@app.route('/static/callon')  #呼出通话建立
@jwt_required()
def callon():
    remote_addr = request.remote_addr
    flaskDB = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    phonenum=flaskDBUtils.getPhoneNum(flaskDB)
    flaskDB.close()
    if phonenum != None:
        fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
        Callon(fdb,phonenum)
        fdb.close()
        #print(res)
        print(datetime.datetime.now(),"[%s]%s自动电话通话建立写入"%(remote_addr,phonenum))
        return jsonify({"返回值": "ok", "msg":(datetime.datetime.now(),"[%s]%s自动电话通话建立写入"%(remote_addr,phonenum))})
    res = {"返回值": "ok", "msg":"phonenum=None"}
    return jsonify(res)

@app.route('/static/initFlightDatabase', methods=["POST"])
@jwt_required()
def initFlightDatabase():
    data = request.get_json()
    selectedtime = data.get("selectedtime")
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    workLoad = flightDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=databaseWorkLoad)
    InitFlightDatabase(fdb,workLoad,selectedtime)
    fdb.close()
    workLoad.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s]初始化航班信息数据库"%remote_addr)
    res['msg'] = (datetime.datetime.now(),"[%s]初始化航班信息数据库"%remote_addr)
    return jsonify(res)

@app.route('/static/selftaxiLogs', methods=["POST"])
@jwt_required()
def selftaxiLogs():
    data = request.get_json()
    text = data.get("text")
    flightid = data.get("flightid")
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    SelftaxiLogs(fdb,text,flightid)
    fdb.close()
    res = {"返回值": "ok"}
    res['msg'] = "selftaxiLogs"
    return jsonify(res)

@app.route('/static/checkCalllist', methods=["POST"])
@jwt_required()
def checkCalllist():
    data = request.get_json()
    time = data.get("time")
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=CheckCalllist(fdb,time)
    fdb.close()

    return jsonify(data=res, msg="checkCalllist")

@app.route('/static/insertLogs', methods=["POST"])
@jwt_required()
def insertLogs():
    data = request.get_json()
    time = data.get("time")
    text = data.get("text")
    name = data.get("name")
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    InsertLogs(fdb,text,name,time)
    fdb.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s]%s插入日志信息"%(remote_addr,name))
    res['msg'] = (datetime.datetime.now(),"[%s]%s插入日志信息"%(remote_addr,name))
    return jsonify(res)
@app.route('/static/insertLogs2', methods=["POST"])
@jwt_required()
def insertLogs2():
    data = request.get_json()
    time = data.get("time")
    name = data.get("name")
    text = data.get("text")
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    InsertLogs2(fdb,text,name,time)
    fdb.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s]%s插入日志信息"%(remote_addr,name))
    res['msg'] = (datetime.datetime.now(),"[%s]%s插入日志信息"%(remote_addr,name))
    return jsonify(res)

@app.route('/static/checkLoadSingal', methods=["POST"])
@jwt_required()
def checkLoadSingal():
    data = request.get_json()
    time1 = data.get("time1")
    time2 = data.get("time2")
    worknum = data.get("worknum")
    remote_addr = request.remote_addr
    wdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseWorkLoad)
    res=CheckLoadSingal(wdb,worknum,time1,time2)
    wdb.close()
    print(datetime.datetime.now(),"[%s]查询个人工作量请求"%remote_addr)
    res['msg'] = (datetime.datetime.now(),"[%s]查询个人工作量请求"%remote_addr)
    return jsonify(res)

@app.route('/static/authorityCheck', methods=["POST"])
@jwt_required()
def authorityCheck():
    remote_addr = request.remote_addr
    data = request.get_json()
    username = data.get("username")
    res1={"返回值":""}
    loginTabledb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseLoginDB)
    res=loginTabledb.queryTabel('logintable', '*', "登录名='{}'".format(username))
    loginTabledb.close()
    if res !=[]:
        res1["返回值"]=res[0]
    print(datetime.datetime.now(),"[%s]%s验证权限请求" %(remote_addr,username))
    res1['msg']=(datetime.datetime.now(),"[%s]%s验证权限请求" %(remote_addr,username))
    return jsonify(res1)


@app.route('/static/loginDbget', methods=["POST"])
@jwt_required()
def loginDbget():
    data = request.get_json()
    username = data.get("username")
    remote_addr = request.remote_addr
    res1= {}
    loginTabledb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseLoginDB)
    res=loginTabledb.getAlldata('logintable')
    loginTabledb.close()
    if res !=[] and username in str(res):
        for i in res:
            res2={}
            res2["登录名"] = i[1]
            res2["权限"] = i[3]
            res2["使用人"] = i[4]
            res1[i[1]] = res2
    print(datetime.datetime.now(),"[%s]%s权限修改信息获取" % (remote_addr,username))

    return jsonify(data=res1, msg=(datetime.datetime.now(),"[%s]%s权限修改信息获取" % (remote_addr,username)))

@app.route('/static/changePassword',methods=["POST"])
@jwt_required()
def changePassword():
    remote_addr = request.remote_addr
    data = request.get_json()["data"]
    loginTabledb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseLoginDB)
    Changepassword(loginTabledb,data["登录名"], data["旧密码"], data["新密码"])
    loginTabledb.close()
    res1 = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s]%s更改密码请求" % (remote_addr,data["登录名"]))
    res1['msg'] = (datetime.datetime.now(),"[%s]%s更改密码请求" % (remote_addr,data["登录名"]))
    return jsonify(res1)

@app.route('/static/addUserWidget',methods=["POST"])
@jwt_required()
def addUserWidget():
    remote_addr = request.remote_addr
    res1={"返回值":""}
    data = request.get_json()["data"]
    loginTabledb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseLoginDB)
    res=loginTabledb.queryTabel('logintable', '*', "登录名='%s'"%data["登录名"])
    if res:
        res=loginTabledb.insertData('logintable', data)
        if res == "ok":
            res1["返回值"] = "1"
        else:
            res1["返回值"] = "0"
    else:
        res1["返回值"] = "2"
    loginTabledb.close()
    print(datetime.datetime.now(),"[%s]创建新用户：%s请求" % (remote_addr,data["登录名"]))
    res1['msg'] = (datetime.datetime.now(),"[%s]创建新用户：%s请求" % (remote_addr,data["登录名"]))
    return jsonify(res1)

@app.route('/static/changeAuth',methods=["POST"])
@jwt_required()
def changeAuth():
    remote_addr = request.remote_addr
    res1={"返回值":""}
    data = request.get_json()["data"]
    loginTabledb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseLoginDB)
    res=loginTabledb.queryTabel('logintable', '*', "登录名='%s'"%str(data["登录名"]).replace("'",""))
    if res != []:
        loginTabledb.upDateItem('logintable',data,"登录名='%s'"%str(data["登录名"]).replace("'",""))
        res1["返回值"]="1"
    else:
        res1["返回值"] = "2"
    loginTabledb.close()
    print(datetime.datetime.now(),"[%s]权限变更写入：%s请求" % (remote_addr,data["登录名"]))
    res1['msg'] = (datetime.datetime.now(),"[%s]权限变更写入：%s请求" % (remote_addr,data["登录名"]))
    return jsonify(res1)

@app.route('/static/infoConfirm',methods=["POST"])
@jwt_required()
def infoConfirm():
    remote_addr = request.remote_addr
    data = request.get_json()
    type, flightid, displaymode, selectedtime = data['type'], data['flightid'], data['displaymode'], data['selectedtime']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    InfoConfirm(fdb,type,flightid,displaymode,selectedtime)
    fdb.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(), "[%s]确认通知操作"%remote_addr)
    res['msg'] = ("[%s]确认通知操作"%remote_addr)
    return jsonify(res)

@app.route('/static/infoConfirm3',methods=["POST"])
@jwt_required()
def infoConfirm3():
    remote_addr = request.remote_addr
    data = request.get_json()
    type,flightid,displaymode,selectedtime = data['type'], data['flightid'], data['displaymode'], data['selectedtime']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    InfoConfirm3(fdb,type,flightid,displaymode,selectedtime)
    fdb.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s]确认自滑推送操作"%remote_addr)
    res['msg'] = (datetime.datetime.now(),"[%s]确认自滑推送操作"%remote_addr)
    return jsonify(res)

@app.route('/static/infoConfirm2',methods=["POST"])
@jwt_required()
def infoConfirm2():
    remote_addr = request.remote_addr
    data = request.get_json()
    type, flightid, displaymode, selectedtime = data['type'], data['flightid'], data['displaymode'], data['selectedtime']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    InfoConfirm2(fdb,type,flightid,displaymode,selectedtime)
    fdb.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s]确认推送操作"%remote_addr)
    res['msg'] = (datetime.datetime.now(),"[%s]确认推送操作"%remote_addr)
    return jsonify(res)

@app.route('/static/manChangests',methods=["POST"])
@jwt_required()
def manChangests():
    remote_addr = request.remote_addr
    data = request.get_json()
    text, type, selectedtime, username = data['text'], data['type'], data['selectedtime'], data['username']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    ManChangests(fdb,text,type,selectedtime,username)
    fdb.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s][%s]%s人工改变航班状态"%(remote_addr,username,text))
    res['msg'] = (datetime.datetime.now(),"[%s][%s]%s人工改变航班状态"%(remote_addr,username,text))
    return jsonify(res)

@app.route('/static/updateDragDropItem',methods=["POST"])
@jwt_required()
def updateDragDropItem():
    #t1 = datetime.datetime.now()
    remote_addr = request.remote_addr
    data = request.get_json()
    column, text, flightid, displayMode, flighttype, selectedtime = data['column'], data['text'], data['flightid'], data['displaymode'], data['flighttype'], data['selectedtime']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    #print(fdb,column,text,flightid,displayMode,flighttype,selectedtime)
    #t2 = datetime.datetime.now()
    #print(f'编辑登录时间:{t2 - t1}')
    res = UpdateDragDropItem(fdb,column,text,flightid,displayMode,flighttype,selectedtime)
    fdb.close()
    res1={"返回值":res}
    print(datetime.datetime.now(),"[%s]拖拽更新请求"%remote_addr)
    #t3 = datetime.datetime.now()
    #print(f'编辑处理时间:{t3 - t2}')
    res1['msg'] = (datetime.datetime.now(),"[%s]拖拽更新请求"%remote_addr)
    return jsonify(res1)

@app.route('/static/updateEidteItem',methods=["POST"])
@jwt_required()
def updateEidteItem():
    remote_addr = request.remote_addr
    data = request.get_json()
    text, flightid, displayMode, flighttype, selectedtime = data['text'], data['flightid'], data['displaymode'], data['flighttype'], data['selectedtime']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    #print(fdb,column,text,flightid,displayMode,flighttype,selectedtime)
    UpdateEidteItem(fdb,text,flightid,displayMode,flighttype,selectedtime)
    fdb.close()
    res1={"返回值":"OK"}
    print(datetime.datetime.now(),"[%s]附加消息请求"%remote_addr)
    res1['msg'] = (datetime.datetime.now(),"[%s]附加消息请求"%remote_addr)
    return jsonify(res1)

@app.route('/static/updateNoteItem',methods=["POST"])
@jwt_required()
def updateNoteItem():
    try:
        remote_addr = request.remote_addr
        data = request.get_json()
        text, name = data['text'], data['name']
        fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
        UpdateNoteItem(fdb,text,name)
        fdb.close()
        res1={"返回值":"OK"}
        print(datetime.datetime.now(),"[%s]排班辅助备注修改"%remote_addr)
        return jsonify(res1)
    except Exception as e:
        res1={"返回值":"fail"}
        res1['msg'] = "error:"+str(e)
        print("有bug,请联系管理员")
        app_logger.log_error(e)
        return jsonify(res1)

@app.route('/static/checkPglist',methods=["POST"])
@jwt_required()
def checkPglist():
    remote_addr = request.remote_addr
    data = request.get_json()
    name, selectedtime, bc = data['name'], data['selectedtime'], data['bc']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    #print(fdb,column,text,flightid,displayMode,flighttype,selectedtime)
    res = CheckPglist(fdb,name,selectedtime,bc)
    fdb.close()
    #print(res)
    if res == "YES":
        res1 = {"返回值": "OK"}
        print(datetime.datetime.now(), "[%s]人工录入派工核查成功"%remote_addr)
    else:
        res1 = {"返回值": "fail"}
        print(datetime.datetime.now(), "[%s]人工录入派工核查失败"%remote_addr)
    return jsonify(res1)

@app.route('/static/tableWidgetLOGDispaly', methods=["POST"])
@jwt_required()
def tableWidgetLOGDispaly():
    data = request.get_json()
    selectedtime = data['selectedtime']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=TableWidgetLOGDispaly(fdb,selectedtime)
    fdb.close()
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]日志刷新请求"%remote_addr)
    return jsonify(data=res)

@app.route('/static/qtPeopleLoad',methods=["POST"])
@jwt_required()
def qtPeopleLoad():
    data = request.get_json()
    selectedtime, bc = data['selectedtime'], data['bc']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    workLoad = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseWorkLoad)
    res=QtPeopleLoad(fdb,workLoad,bc,selectedtime)
    workLoad.close()
    fdb.close()
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]人员工作状态刷新请求"%remote_addr)
    return jsonify(data=res)

@app.route('/static/getVin',methods=["POST"])
@jwt_required()
def getVin():
    data = request.get_json()
    mode, num = data['mode'], data['num']
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    vin=flaskDBUtils.getVin(db,mode,int(num)) # 刷新航班
    db.close()
    res = {"返回值": "%s"%vin}
    remote_addr = request.remote_addr
    print(datetime.datetime.now(), "[%s]获取在线Vin码"%remote_addr)
    return jsonify(res)

@app.route('/static/updateVin',methods=["POST"])
@jwt_required()
def updateVin():
    data = request.get_json()
    mode, num = data['mode'], data['num']
    db = flaskDBUtils.flaskDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=database)
    vin=flaskDBUtils.updateVin(db,mode,int(num))  # 刷新航班
    db.close()
    res = {"返回值": "%s"%vin}
    remote_addr = request.remote_addr
    print(datetime.datetime.now(), "[%s]更新在线Vin码"%remote_addr)
    return jsonify(res)

@app.route('/static/tableWidgetDispalyRead',methods=["POST"])
@jwt_required()
def tableWidgetDispalyRead():
    data = request.get_json()
    date = data['date']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=TableWidgetDispalyRead(fdb,date)
    fdb.close()
    #print(datetime.datetime.now(),res)
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]A模式只读航班信息刷新请求"%remote_addr)
    # res['msg'] = (datetime.datetime.now(),"[%s]A模式只读航班信息刷新请求"%remote_addr)
    return jsonify(data=res)

@app.route('/static/tableWidgetDispalyRead2',methods=["POST"])
@jwt_required()
def tableWidgetDispalyRead2():
    data = request.get_json()
    date = data['date']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=TableWidgetDispalyRead2(fdb,date)
    fdb.close()
    #print(datetime.datetime.now(),res)
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]B模式只读航班信息刷新请求"%remote_addr)
    return jsonify(data=res)

@app.route('/static/tableWidgetDispaly',methods=["POST"])
@jwt_required()
def tableWidgetDispaly():
    #t1 = datetime.datetime.now()
    data = request.get_json()
    selectedtime, date = data['selectedtime'], data['date']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    #t2 = datetime.datetime.now()
    #print(f'航班刷新登录时间:{t2 - t1}')
    res=TableWidgetDispaly(fdb,selectedtime,date)
    fdb.close()
    #print(datetime.datetime.now(),res)
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]A模式航班信息刷新请求[%s]"%(remote_addr,date))
    #t3 = datetime.datetime.now()
    #print(f'航班刷新处理时间:{t3 - t2}')
    return jsonify(data=res)

@app.route('/static/tableWidgetDispaly11',methods=["POST"])
@jwt_required()
def tableWidgetDispaly11():
    data = request.get_json()
    selectedtime = data['selectedtime']
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=TableWidgetDispaly(fdb,selectedtime,"4")
    fdb.close()
    #print(datetime.datetime.now(),res)
    print(datetime.datetime.now(),"[%s]文件存储1航班信息刷新请求"%remote_addr)
    return jsonify(data=res)

@app.route('/static/tableWidgetDispaly22',methods=["POST"])
@jwt_required()
def tableWidgetDispaly22():
    data = request.get_json()
    selectedtime = data['selectedtime']
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=TableWidgetDispaly2(fdb,selectedtime,"4")
    fdb.close()
    print(datetime.datetime.now(),"[%s]文件存储2航班信息刷新请求"%remote_addr)
    return jsonify(data=res)

@app.route('/static/tableWidgetDispaly2',methods=["POST"])
@jwt_required()
def tableWidgetDispaly2():
    data = request.get_json()
    selectedtime, date = data['selectedtime'], data['date']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=TableWidgetDispaly2(fdb,selectedtime,date)
    fdb.close()
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]B模式航班信息刷新请求[%s]"%(remote_addr,date))
    return jsonify(data=res)

@app.route('/static/mapDispaly',methods=["POST"])
@jwt_required()
def mapDispaly():
    data = request.get_json()
    selectedtime = data['selectedtime']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res = MapDispaly(fdb, selectedtime)
    fdb.close()
    #print(datetime.datetime.now(),'获取的机位数据：{}'.format(res))
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]地图显示刷新请求"%remote_addr)
    return jsonify(data=res)

@app.route('/static/judge_bc')
@jwt_required()
def judge_bc():
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    aa=Judge_bc()
    fdb.close()
    print(datetime.datetime.now(),"[%s]判断班次请求"%remote_addr)
    return jsonify(data=aa)

@app.route('/static/dealLogs',methods=["POST"])
@jwt_required()
def dealLogs():
    data = request.get_json()
    user, id = data['user'], data['id']
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    DealLogs(fdb,user,id)
    fdb.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s]%s处理待办信息" % (remote_addr,user))
    return jsonify(res)

@app.route('/static/checkLogs',methods=["POST"])
@jwt_required()
def checkLogs():
    try:
        remote_addr = request.remote_addr
        data = request.get_json()
        start, end = data['start'], data['end']
        fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
        res=fdb.sort_queryTable("*",'logs',"产生时间<'%s' and 产生时间>'%s'"%(end,start),"产生时间","desc")
        fdb.close()
        print(datetime.datetime.now(),"[%s]查询全部日志请求"%remote_addr)
        return jsonify(data=res)
    except:
        return jsonify(data={})

@app.route('/static/tableWidgetDisplayChange',methods=["POST"])
@jwt_required()
def tableWidgetDisplayChange():
    data = request.get_json()
    selectedtime = data['selectedtime']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=TableWidgetDisplayChange(fdb,selectedtime)
    fdb.close()
    remote_addr = request.remote_addr
    print(datetime.datetime.now(),"[%s]待办信息刷新请求"%remote_addr)
    return jsonify(data=res, msg=(datetime.datetime.now(),"[%s]待办信息刷新请求"%remote_addr))

@app.route('/static/get_dic',methods=["POST"])
@jwt_required()
def get_dic():
    try:
        remote_addr = request.remote_addr
        data = request.get_json()['data']

        fdb = flightDB(host = dbhost , port = dbport , user = dbuser , password = dbpassword , database = databaseDB4)
        ress = Get_dic(fdb , data)
        fdb.close()
        res = {"返回值": ress}
        print(datetime.datetime.now(),"[%s]获取人员信息EXCEL表格"%remote_addr)
        res['msg'] = (datetime.datetime.now(),"[%s]获取人员信息EXCEL表格"%remote_addr)
        return jsonify(res)
    except:
        fdb.close()
        print(datetime.datetime.now(), "[%s]获取人员信息EXCEL表格失败" % remote_addr)
        res={ "返回值" : "fail" }
        return jsonify(res)


@app.route('/static/updateStopFlight',methods=["POST"])
@jwt_required()
def updateStopFlight():
    try:
        remote_addr = request.remote_addr
        data = request.get_json()['data']
        fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
        workLoad = flightDB(host=dbhost, port=dbport, user=dbuser, password=dbpassword, database=databaseWorkLoad)
        ress=UpdateStopFlight(fdb,workLoad,data)
        fdb.close()
        workLoad.close()
        res = { "返回值" : ress}
        print(datetime.datetime.now(),"[%s]上传停场航班EXCEL数据"%remote_addr)
        return jsonify(res)
    except:
        fdb.close()
        workLoad.close()
        print(datetime.datetime.now(), "[%s]上传停场航班EXCEL数据失败" % remote_addr)
        return jsonify({"返回值": "fail", "msg":(datetime.datetime.now(), "[%s]上传停场航班EXCEL数据失败" % remote_addr)})

@app.route('/static/updateTaskAuto',methods=["POST"])
@jwt_required()
def updateTaskAuto():
    try:
        remote_addr = request.remote_addr
        data = request.get_json()['data']
        fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
        ress=UpdateTaskAuto(fdb,data)
        fdb.close()
        res = {"返回值":ress}
        print(datetime.datetime.now(),"[%s]获取准备组任务EXCEL表格"%remote_addr)
        res['msg'] = (datetime.datetime.now(),"[%s]获取准备组任务EXCEL表格"%remote_addr)
        return jsonify(res)
    except:
        print(datetime.datetime.now(), "[%s]获取准备组任务EXCEL表格失败" % remote_addr)
        return jsonify({"返回值":"fail","msg":("[%s]获取准备组任务EXCEL表格失败" % remote_addr)})

@app.route('/static/saveRisktable')
@jwt_required()
def saveRisktable():
    remote_addr = request.remote_addr
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=SaveRisktable(fdb)
    fdb.close()
    print(datetime.datetime.now(),"[%s]导出风险数据库"%remote_addr)
    return {"返回值":res, "msg":(datetime.datetime.now(),"[%s]导出风险数据库"%remote_addr)}

@app.route('/static/getRiskData',methods=["POST"])
@jwt_required()
def getRiskData():
    remote_addr = request.remote_addr
    data = request.get_json()
    bay, time, acno, actype = data['bay'], data['time'], data['acno'], data['actype']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    res=GetRiskData(fdb,bay,time,acno,actype)
    fdb.close()
    print(datetime.datetime.now(),"[%s]导出风险数据库"%remote_addr)
    return {"返回值":res, "msg":(datetime.datetime.now(),"[%s]导出风险数据库"%remote_addr)}

@app.route('/static/updateRiskdb',methods=["POST"])
@jwt_required()
def updateRiskdb():
    try:
        remote_addr = request.remote_addr
        data = request.get_json()["data"]
        fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
        ress=UpdateRiskdb(fdb,data)
        fdb.close()
        res = {"返回值": ress}
        print(datetime.datetime.now(),"[%s]获取风险数据库EXCEL表格"%remote_addr)
        res['msg'] = (datetime.datetime.now(),"[%s]获取风险数据库EXCEL表格"%remote_addr)
        return jsonify(res)
    except:
        fdb.close()
        print(datetime.datetime.now(), "[%s]获取风险数据库EXCEL表格失败" % remote_addr)
        return jsonify({"返回值": "fail", "msg":("[%s]获取风险数据库EXCEL表格失败" % remote_addr)})

@app.route('/static/taskAtuoCheck',methods=["POST"])
@jwt_required()
def taskAtuoCheck():
    remote_addr = request.remote_addr
    data = request.get_json()
    time = data['time']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    TaskAtuoCheck(fdb,time)
    fdb.close()
    res = {"返回值": "ok"}
    print(datetime.datetime.now(),"[%s]确认准备组任务待办信息情况"%remote_addr)
    res['msg'] = (datetime.datetime.now(),"[%s]确认准备组任务待办信息情况"%remote_addr)
    return jsonify(res)

@app.route('/static/createWorkloadtablesFromPg',methods=["POST"])
@jwt_required()
def createWorkloadtablesFromPg():
    remote_addr = request.remote_addr
    data = request.get_json()
    selectedtime = data['selectedtime']
    fdb = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseDB4)
    workLoad = flightDB(host=dbhost,port=dbport,user=dbuser,password=dbpassword,database=databaseWorkLoad)
    CreateWorkloadtablesFromPg(fdb,workLoad,selectedtime)
    fdb.close()
    workLoad.close()
    res={"返回值":"ok"}
    print(datetime.datetime.now(),"[%s]通过派工信息创建人员工作统计表"%remote_addr)
    res['msg'] = (datetime.datetime.now(),"[%s]通过派工信息创建人员工作统计表"%remote_addr)
    return jsonify(res)


#--------------------------------------------------------------------------------------------------------

@app.route('/getdict', methods=['GET'])
@jwt_required()
def getdict():
    data = {
        'data':['1','2','3','4','5','6','7','8','9'],
        'data2':'data2_data2'
    }
    return returnTrue('this is message', data), 200




#令牌刷新机制
@app.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    current_user_id = get_jwt_identity()
    new_access_token = create_access_token(identity=current_user_id)
    return jsonify(access_token=new_access_token, msg='Refresh access_token success'), 200



#用户角色与权限管理
@app.route('/admin', methods=['GET'])
@jwt_required()
def admin():
    current_user_id = get_jwt_identity()
    user = query_user(current_user_id)
    if user[0][3] != 'admin':
        return jsonify({'message': 'Access denied'}), 403
    return jsonify({'message': 'Hello admin'}), 200

#'''
@app.before_first_request
def init():
    if not app.config['initialized']:
        print('####  Flask Start... ####')
        global fl,si,singlePeopleNotice,loaclseverip
        fl = utils.flight_list()
        si = ipcall.searchinfo()
        loaclseverip = get_local_ip()
        print(f"当前服务器IP:{loaclseverip}")
        singlePeopleNotice = initialize_file('D:\\flightinfo\\DATABASE\\singlepoeple_notice.txt',False)
        app.config['initialized'] = True

#if __name__ == '__main__':
#    app.run(debug=True, host='0.0.0.0', port=5001)
if __name__ == '__main__':
    serve(app, host='0.0.0.0',port=5001, threads=32)
    #serve(app, host='0.0.0.0',port=5001, threads=64)