import time,random,json,hmac,requests
from hashlib import sha256
from  binascii import a2b_hex 
import psycopg2

from django.conf import settings
import os


def fm_signatrue(str_to_sign,key,signature_method="HMAC_SHA256"):  
    m = sha256(str_to_sign.encode('UTF-8'))       
    authorization = hmac.new(a2b_hex(key), m.digest(), sha256).hexdigest().upper() 
    return authorization


class YgNFC():
    #初始化
    def __init__(self,is_test=True,cn=None,log=True):
        self.log=log 
        #数据库连接，如果为空，使用django默认连接
        if not cn:           
            cn=connection
        self.cn=cn        
        self.sig_method = "FM-HMAC-SHA256"        
        self.uri="/v1/rfid/state/"
        if is_test:            
            self.url="http://rfid-demo.fm-uivs.com:8095"
            self.client_name = "client4test"
            self.secret_id = "58605a5014d9408185708d247ea0186c"            
            self.secret_key = 'C7F4A2568B78DE4225BD3D3CAA826601'            
        else:            
            self.url="https://api.fm-uivs.com:443"            
            self.client_name = "client_ygjy"
            self.secret_id = "3dd117d09df0442ba3e32dbe49f54762"            
            self.secret_key = '9DFCE4FA6D999B55D0E674FD0BC0A32D'

    # 生成指定数据格式
    def get_prepared(self,data,enable=True):
        nonce=str(random.randint(0, 4294967296))
        tm=str(int(time.time()))
        content=json.dumps(data)
        if enable:
            self.uri="/v1/rfid/state/enable"
        else:
            self.uri="/v1/rfid/state/disable"
        str_to_sign=self.uri+"\n" + nonce+"\n"+ tm+"\n"+ self.client_name+"\n" + content+"\n"
        sig = fm_signatrue(str_to_sign,self.secret_key)
        headers={
            "Content-Type": "application/json",    
            "accesskey": self.secret_id,
            "client-name": self.client_name,
            "timestamp": tm,    
            "signmethod": self.sig_method,
            "nonce": nonce,
            "sign": self.sig_method+' SecretID='+self.secret_id+';Signature=' +sig, 
            #"Content-Length": str(len(content)),
        } 
        return {'headers':headers,'data':data}

    def post_data(self, data, enable=True):
        d=self.get_prepared(data,enable)        
        pth=os.path.join(settings.BASE_DIR, "taskman", "cert", "yg_uivs")
        r=requests.post(self.url+self.uri, json=data, headers=d['headers'],
            cert=(os.path.join(pth,'crpa-cert.cer'), os.path.join(pth, 'crpa.key'))) 
        status=r.status_code 
        is_ok=False       
        if status==200:            
            rd=json.loads(r.text)            
            if rd['code']==0:                
                is_ok=True
            rt="'"+json.dumps(r.text)+"'"
        else:
            rt='null'     
        # 写入第三方请求日志 湖北裕贡酒业销售有限公司	16716
        s="INSERT INTO log.post_3rd(company_id,vendor,url,status,data,result,what) VALUES "+\
            "(16716,'UIVS','"+self.url+self.uri+"',"+str(status)+",'"+json.dumps(d)+"',"+rt+",'YG_NFC')"        
        cur=self.cn.cursor()
        cur.execute(s)
        self.cn.commit()
        cur.close()        
        return {'YG_NFC':{'ok':is_ok}}





'''
cn=psycopg2.connect(database="datacenter", user="hntj",password="hntj!@)!",host="47.107.230.103", port="5432")
data={
    "uidList":[
        #"CA345189A2511DE0",
        #"A5A2AAABED511DE0",
        #"B35FAC298B511DE",

        "B40248E112511DE0",
        "B290106483511DE0",
        "4DBA5FF82C511DE0",
    ]        
}


ygnfc=YgNFC(is_test=False,cn=cn,log=True)
d=ygnfc.post_data(data, enable=False)
print(d)
'''
