# -*- codeing: utf-8 -*-
# import win32com.client
import os, sys, string
import sys
import time

import psycopg2
import json
import hashlib
import datetime
import requests

class ZxwData():
    def __init__(self,is_test=True,cn=None, log=True):
        self.log = log

        self.tm = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        # 数据库连接，如果为空，使用django默认连接
        if cn:
            cn.autocommit = True
        else:
            cn = connection
        self.cn = cn
        # 海商测试环境
        if is_test:
            self.appkey='42d3eec7ddef476e82e0f83c354846ad'
            self.appsecret= '3b7256ace17449758a3243383c0c548a'   
            self.url='http://zuixian.demo.newxm.kuaidiantong.cn/openApi/Hishop.Open.Api.Scan.PushOrder'
            
        else:
            self.appkey=    '7953a4f75b7a4fb7a7e603a137a9d443'
            self.appsecret= '0ccb16a28eff4d9bbad296e1606b8a73'   
            self.url=       'https://jiuguijiumiaopin.com/openApi/Hishop.Open.Api.Scan.PushOrder'  
    

    def post_data(self, url, data):
        return requests.post(url, json=data)
    
    

    def get_sign(self,parameters):
        sorted_params = dict(sorted(parameters.items()))
        query = ''
        
        #print('==============')
        #print('parameters:',parameters)
        #print('appsecret:',self.appsecret)
        
        #for key, value in sorted_params.items():
        #    if key and value:
        #        query += key + value
        #        print('string:',query)
        # 对方签名接口参数按指定的顺序而非排序字典
        query="app_key"+self.appkey+\
            "OrderId"+parameters['OrderId']+\
            "timestamp"+parameters['timestamp']+\
            self.appsecret        

        m2=hashlib.md5(query.encode('utf8'))           
        result = m2.hexdigest().upper()

        #print('sign:',result)
        #print('==============')

        return result
    
    def process_batch(self,batch_id):
        tm=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        sign=self.get_sign({
            'timestamp': tm,
            'app_key': self.appkey,     
            'OrderId':str(batch_id)
        })
        

        cur = self.cn.cursor()
        data={
              "OrderId": str(batch_id),
              "Cartons": [],

              "app_key":self.appkey,
              "sign":sign,
              "timestamp":tm
              
            }
        #url = self.get_url()
        cnt = 0
        msg = ''

        if sign:        
        
            cur.execute("select left(label_code,4) from stkdetails.c1 "+\
                "where batch_id="+str(batch_id)+" and label_pkg=3 "+\
                "group by left(label_code,4)"
            )
            rs=cur.fetchall()
            for r in rs:
                rg=r[0][:4]
                t='label.t'+rg        
                s="select "+str(batch_id)+",external_code,name,"+\
                    "(select code from "+t+" where id=d.label_pk_id),"+\
                    "coalesce((select code from "+t+" where parent_id=d.label_pk_id and package_id=3 limit 1),''),"+\
                    "array(select label from logistics.z_bottlecap_binding where label_pk_id=d.label_pk_id) "+\
                    "from "+\
                    "(SELECT label_code,label_pk_id,product_id "+\
                        "FROM stkdetails.c1 where batch_id="+str(batch_id)+" and left(label_code,4)='"+rg+"' and label_pkg=3"\
                    ") d "+\
                    "left outer join "+\
                    "(select id,name,external_code from logistics.product_product where company_id=1) p "+\
                    "on d.product_id=p.id"
                cur.execute(s)
                for rr in cur.fetchall():
                    codes=[]
                    for c in rr[5]:
                        codes.append({
                            'Code':c,
                            'ProductCode':rr[1]    
                        })
                    data['Cartons'].append({
                        'Carton':rr[3],
                        'Carton2':rr[4],
                        'Codes':codes                        
                    })            

 
            #f="F:\\hzy\\醉仙网\\"+str(batch_id)+".json"
            #ff=open(f,'w')
            #ff.write(json.dumps(data))
            #ff.close()
                    
            #print("data:", data)

            cnt = len(data['Cartons'])


            
            url=self.url
            url=url+"?app_key="+self.appkey+"&timestamp="+tm+"&sign="+sign+"&OrderId="+str(batch_id)

            res = self.post_data(url,data)

            #print("url:", url)
            #print(res)
            #print(f)

            status = res.status_code

            #print(res.text)

            #{"success":true,"data":"成功"}
            is_ok = False
            if status == 200 or status ==202:
                rt = json.loads(res.text)
                if rt['success'] :
                    is_ok = True
                    msg = rt['data']
                else:
                    pass
                    msg = rt['msg']
            else:
                msg = '请求失败'
            s = "INSERT INTO log.sync_inventory_batch(company_id,is_ok,status,vendor,url,batch_id,vtype_id,batch_code,cnt_total,src,results) values " + \
                "(1,"+str(is_ok)+","+str(status)+",'zxw','" + url + "'," + str(batch_id) + ",1,'" + data['OrderId'] + "'," + str(
                cnt) + ",'" + json.dumps(data, ensure_ascii=False) + "','" + json.dumps(res.text,ensure_ascii=False) + "') "
        else:
            msg = '获取签名失败'
            s = "INSERT INTO log.sync_inventory_batch(company_id,vendor,url,batch_id,vtype_id,batch_code,cnt_total,src,results,err_msg) values " + \
            "(1,'zxw','" + url + "'," + str(batch_id) + ",1,'" + '' + "'," + str(cnt) + ",null,null,'"+msg+"') " + \
            "returning id"
        cur = self.cn.cursor()
        cur.execute(s)
        self.cn.commit()
        cur.close()
        return {'msg':msg}

'''
 
isTest = False
ids=[
        
#1805994,
#1805993,
#1802083,
#1802082,
#1802081,


#1806064,
#1815226,
#1819865,
#1823004,
#1823025,
#1833570,
#1833571,
#1841427,
#1843658,
#1853292,
#1907452,
#1908515,
#1911174,
#1911175,
#1912810,

#2025-02-25
#1980893,
#2016812,
#2017194,
#2072261,
#2076942,
#2076975,  



#2025-02-26
#2065127
2054348

]

cn = psycopg2.connect(database="datacenter", user="tjfw", password="Tj2024)&#!", host="47.107.230.103", port="5432")



zxw = ZxwData(isTest,cn)
for id in ids:
    zxw.process_batch(id)
'''
