import datetime

import requests

from unitls.LogerinTxt import app_logger
from .flightDB import flightDB


def calltry(fdb:flightDB,ip,token):
    try:
        #print("calltry")
        #print(ip,token)
        calllist=fdb.sort_queryTable2("*","Calllist","接通时间 ='' and 拨号次数<4","拨号次数","ASC","创建时间","ASC")
        if len(calllist) != 0:
            phone_num=calllist[0][1]
            calltime=int((fdb.queryTabel("Calllist","拨号次数","航班编号='%s'"%calllist[0][0]))[0][0])+1
            newdic={"拨号次数":"%s"%calltime}
            fdb.upDateItem("Calllist",newdic,"航班编号='%s'"%calllist[0][0])
            try:
                data = {"PHB_AutoDialNumber": phone_num,
                        "ReturnPage": "/contacts.htm",
                        "AutoDialSubmit": "submit",
                        "PHB_AutoDialLine": "1"
                        }
                header = {
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                    "Connection": "keep-alive",
                    "Cookie": token
                }
                requests.post(url="http://%s/contacts.htm" % ip, data=data, headers=header)
                return phone_num
            except Exception as e:
                app_logger.log_error(e)
                print(datetime.datetime.now(),"[数据中心]拨号失败")
                return "fail"
    except Exception as e:
        app_logger.log_error(e)
        return "fail"
