#coding:utf-8
import psycopg2
import hashlib
import requests
import datetime
import json 
import time

import hmac
import random
import base64 

# 蒙古王 215340
aid='215340'

class MgwData():
    #初始化
    def __init__(self,is_test=False,cn=None,log=True):
        self.log=log   
        #数据库连接，如果为空，使用django默认连接
        if cn:
            cn.autocommit = True
        else:
            cn=connection
        self.cn=cn        
        if is_test:
            # 博智测试环境
            self.url="http://81.70.247.13/crm-octm/v1/logistics/codeInfo/receiveCodeFromTianJan"
            self.secretId="ww0f67973f04f31ab6"
            self.secretKey="Uw3AwpEIrqKnMLKigVqvhHXm0EoLotSYSoUBt6OuL-9"           
        else:
            # 博智正式环境
            self.url="https://mgwwl.cn/crm-octm/v1/logistics/codeInfo/receiveCodeFromTianJan"  
            self.secretId="ww63508cc6d13e6e48"
            self.secretKey="22MHD7wqjDHHQiqNpIZs0AGZ8HBs3nVu"
        cur=self.cn.cursor()
        #发货标签号码临时表
        s="CREATE TEMP TABLE batch_codes("+\
            "label_code character varying(20),"+\
            "label_pkg integer,"+\
            "label_pk_id bigint,"+\
            "bottle_tb character varying(20),"+\
            "label_pk_code character varying(20)"+\
        ")"
        cur.execute(s)       
        cur.close()
        

    def get_headers(self):
        nonce=str(random.randint(0, 4294967296))       
        tm=str(int(time.time()*1000))  
        str_to_sign="nonce="+nonce+"&secretId="+self.secretId+"&secretKey="+self.secretKey+"&timestamp="+tm   
        hexStr=hmac.new(        
            self.secretKey.encode('utf8'),            
            str_to_sign.encode('utf8'),    
            hashlib.sha256
        ).hexdigest()     
        sign=str(base64.b64encode(hexStr.encode('utf8')),'utf8')  
        headers={
            'nonce':nonce,
            'secretId':self.secretId,
            'timestamp':tm,
            'sign':sign
        }    
        return headers

 
    def process_batch(self,batch_id):
        cur=self.cn.cursor()
        s="select company_id,b.id,code,coalesce(dn_number,''),tm,p.external_code,p.name,"+\
            "c.external_code,c.name,n.id,coalesce(n.salesorder_code,''),coalesce(order_type,''),"+\
            "v.external_code,v.name,(select sn from logistics.company_level where id=v.level_id),"+\
            "(select count(*) from stkdetails.c"+aid+" where batch_id="+str(batch_id)+") "+\
            "from "+\
            "(select id,code,tm,product_id,company_id,company_to_id,salesorder_code,dn_number "+\
                "from logistics.inventory_batch where id="+str(batch_id)+\
            ") b "+\
            "left outer join "+\
            "(select id,salesorder_code,order_type from logistics.inventory_deliverynote where company_id="+aid+") n "+\
            "on b.salesorder_code=n.salesorder_code "+\
            "left outer join "+\
            "(select id,name,level_id,external_code from logistics.company_company where ancestor_id="+aid+") v "+\
            "on b.company_id=v.id "+\
            "left outer join "+\
            "(select id,name,level_id,external_code from logistics.company_company where ancestor_id="+aid+") c "+\
            "on b.company_to_id=c.id "+\
            "left outer join "+\
            "(select id,external_code,name from logistics.product_product where company_id="+aid+") p "+\
            "on b.product_id=p.id"
        cur.execute(s)
        r=cur.fetchone()
        e=''
        if not r:
            e='batch not exists'
        elif r[15]==0:
            e='no details in this batch'

        if e:
            return e

        data={
            "batch_id":r[1],
            "batch_no":r[2],
            "dn_number":r[3],
            "time":r[4].strftime("%Y-%m-%d %H:%M:%S"),
            "product":{
                "code":r[5],"name":r[6]
            },
            "customer":{
                "code":r[7],"name":r[8]
            },
            "openingData":False,
            "orderNo":r[10],
            "orderType":r[11]
        }
        if str(r[0])==aid:
            # 工厂发货
            data['vendor']={}
        else:
            # 发货经销商
            data['vendor']={'code':r[12],'name':r[13],'level':r[14]}         
        # 发货扫码标签数组
        data['labels']=[]
        data['barcodes']=[]        

        #有可能stkdetials明细尚没有完全生成
        time.sleep(3)

        # 发货码明细写入码明细临时表
        s="select label_code,label_pk_id,label_pkg,"+\
            "case when label_pkg=3 "+\
                "then (select bottle_tb from carton.t1355 where code=label_code) "+\
                "else left(label_code,4) "+\
            "end,"+\
            "case when label_pkg=3 "+\
                "then label_code "+\
                "else (select code from label.t1355 where id=label_pk_id) "+\
            "end "+\
            "from stkdetails.c"+aid+" where batch_id="+str(batch_id)
        a=[]
        cur.execute(s)
        for r in cur.fetchall():
            a.append("('"+r[0]+"',"+str(r[1])+","+str(r[2])+",'"+r[3]+"','"+r[4]+"')")
            data['labels'].append({"code":r[0],"pkg":r[2]})
        # 扫码明细写入临时表
        s="insert into batch_codes(label_code,label_pk_id,label_pkg,bottle_tb,label_pk_code) values "+",".join(a)
        cur.execute(s)
        
        cur.execute("select label_code,label_pkg,label_pk_id,label_pk_code,bottle_tb from batch_codes")
        rs=cur.fetchall()
        # 2024-07-26 生成码数据明细，目前只有盖内外码，没有瓶盖上贴刮刮银标签的场景
        for r in rs:
            tb=r[4].lower()
            if r[1]==3:                
                cts=[{"logistics_code": r[0]}] 
                s="select code,"+\
                    "coalesce((select cap    from logistics.mes_bottlcap where label_code=code order by id+0 desc limit 1),''),"+\
                    "coalesce((select outter from logistics.mes_bottlcap where label_code=code order by id+0 desc limit 1),'') "+\
                    "from label.t"+tb+" where parent_id="+str(r[2])
            else:
                cts=[]
                lb=r[0]
                s="select '"+lb+"',"+\
                    "coalesce((select cap    from logistics.mes_bottlcap where label_code='"+lb+"' order by id+0 desc limit 1),''),"+\
                    "coalesce((select outter from logistics.mes_bottlcap where label_code='"+lb+"' order by id+0 desc limit 1),'') "
            bts=[]
            cur.execute(s)
            for rr in cur.fetchall():
                bts.append({
                    "laser_code":rr[0],         #瓶/盒 激光码 以字母JD(酒店)或LT(流通)开头跟13个数字     
                    "bottlecap_inner":rr[1],    #瓶盖内码 h开头 长度为12的数字与小写字母
                    "bottlecap_outter":rr[2],   #瓶盖外码 长度为10的数字与大写字母
                    "bottlecap_label":"",       #刮刮银标签 瓶盖标签码	12 个数字
                    "bottlecap_vcode":"",       #刮刮银标签 标签验证码  6 个数字                
                    "logistics_code":""         #瓶标物流码,长度为12的数字 备用，目前不贴物流标
                })   
            data['barcodes'].append({
                'cartons':cts,
                'boxes':[],
                'bottles':bts,    
            })  

        cur.close()
        cn.close()
        
        # 保存json数据到文件
        #f=open('F:\\hzy\\蒙古王\\batch_'+str(batch_id)+".json",'w')	
        #f.write(json.dumps(data))
        #f.close()         
         
        # 数据推送汉得        
        rt=requests.post( url=self.url, headers=self.get_headers(), json=[data] )
        return (rt.text)         
    
   
'''        
is_test=True
cn=psycopg2.connect(database="datacenter", user="tjfw",password="Tj2024)&#!",host="47.107.230.103", port="5432")
bz=MgwData(is_test=is_test, cn=cn)
#for id in [1489740]:
#    print(id)
id=1489740
id=1489758
bz.process_batch(batch_id=id)
'''
