import requests,json,time,random,hashlib

def api_request01(url,passid,serviceid,passtoken,jsons1,query,decoder='utf8'):
    signTime = str(GetTime()//1000)
    nonce = GetNonce()
    sign = GetSign(signTime,nonce,passtoken)
    headers = {
        'Content-Type':'application/json',
        'x-tif-signature':sign,
        'x-tif-timestamp':signTime,
        'x-tif-nonce':nonce,
        'x-tif-paasid':passid,
        'x-tif-serviceId':serviceid
    }
    query_timestamp = str(GetTime())
    jsons = {
        "system_id": GetKwargs(jsons1, 'system_id'),
        "vender_id": GetKwargs(jsons1, 'vender_id'),
        "department_id": GetKwargs(jsons1, 'department_id'),
        "query_timestamp": query_timestamp,
        "UID": GetNonce(),
        "query": query,
        "audit_info": {
            "operator_id": GetKwargs(jsons1, 'operator_id'),
            "operator_name": GetKwargs(jsons1, 'operator_name'),
            "query_object_id": GetKwargs(query, 'SFZH'),
            "query_object_id_type": '01',
            "item_id": GetKwargs(jsons1, 'item_id'),
            "item_code": GetKwargs(jsons1, 'item_code'),
            "item_sequence": GetKwargs(jsons1, 'item_sequence'),
            "terminal_info": GetKwargs(jsons1, 'terminal_info'),
            "query_timestamp": query_timestamp
        }
    }
    # print(url,headers,jsons)
    request = requests.post(url=url,headers=headers,json=jsons)
    result = request.text.encode(decoder)
    return result
def GetSign(signTime,nonce,passtoken):
    data = signTime+passtoken+nonce+signTime
    return hashlib.sha256(data.encode('utf-8')).hexdigest()
def GetNonce():
    reu = ''
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    for i in range(20):reu+=random.choice(base_str)
    return reu
def GetTime():
    return int(time.time()*1000)
def GetKwargs(dic,key):
    resu = 'xxx'
    if dic.__contains__(key):
        resu = dic[key]
    return resu
