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

import psycopg2
import zipfile
import json
import hashlib
import datetime
import requests

class HsData():
    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='30a8ff416da1419cbb7df0146ab485aa'
            self.appsecret= 'ca639cb7b2004f39b077a79e2796fda9'
            self.url = 'https://neican.newxm.kuaidiantong.cn/openApi/Hishop.Open.Api.Scan.PushOrder?'
        else:
            self.appkey = '93f7c0ba7fd94f86bc28ac206bd169af'
            self.appsecret = '0eac1ae5a4bb4e29a8038454474663a1'
            pass

    import hashlib

    def sign_top_request(self,parameters, sign_method, app_secret):
        sorted_params = dict(sorted(parameters.items()))

        query = ''
        for key, value in sorted_params.items():
            if key and value:
                query += key + value

        query += app_secret
        # query = "app_keyhishopyunshangchengbuyer_unamenainiuend_created2016-02-15 23:50:20status1start_created2016-02-15 11:50:20timestamp2015-01-01 12:00:00page_no1page_size40123456789"
        # print(query)
        md5 = hashlib.md5()
        md5.update(query.encode('utf-8'))
        result = md5.hexdigest()

        return result.upper()

    def post_data(self, url, data):
        return requests.post(url, json=data)
    def get_url(self):
        parameter = {
            'timestamp': self.tm,
            'app_key': self.appkey,
        }
        sign_method = ''
        signature = self.sign_top_request(parameter, sign_method, self.appsecret) 
        if signature:
            self.url = self.url + 'app_key=' + self.appkey + '&timestamp=' + self.tm + '&sign=' + signature
        else:
            self.url = ''
        return self.url
    def data_batch(self,batch_id):
        cur = self.cn.cursor()
        data={
              "OrdersId": "",
              "Codes": [],
              "DealerName": "",
              "DealerCode": ""
            }
        url = self.get_url()
        cnt = 0
        msg = ''
        if url :
            s = f'''
                SELECT 
                    A.code,
                    b.label_code,
                    C.NAME,
                    C.external_code,
                    d.NAME,
                    d.external_code 
                FROM
                    ( SELECT code, ID, company_to_id FROM logistics.inventory_batch WHERE ID = {batch_id} )
                    A LEFT OUTER JOIN ( SELECT batch_id, label_code, product_id FROM stkdetails.c1644 ) b ON A.ID = b.batch_id
                    LEFT OUTER JOIN ( SELECT ID, NAME, external_code FROM logistics.company_company ) C ON C.ID = A.company_to_id
                    LEFT OUTER JOIN ( SELECT ID, NAME, external_code FROM logistics.product_product ) d ON d.ID = b.product_id
                '''
            cur.execute(s)
            r = cur.fetchall()
            for index,ele in enumerate(r) :
                if index == 0:
                    data['OrderId']=ele[0]
                    data['DealerName']=ele[4]
                    data['DealerCode']=ele[5]

                data['Codes'].append({
                          "Code": ele[1],
                          "ProductCode": ele[3]
                        })
            cnt = len(data['Codes'])
            res = self.post_data(self.url,data)
            status = res.status_code
            #{"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 " + \
                "(1644,"+str(is_ok)+","+str(status)+",'hishop','" + url + "'," + str(batch_id) + ",2,'" + 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 " + \
            "(1644,'hishop','" + url + "'," + str(batch_id) + ",2,'" + '' + "'," + str(cnt) + ",null,null,'"+msg+"') " + \
            "returning id"
        cur = self.cn.cursor()
        cur.execute(s)
        self.cn.commit()
        cur.close()
        return {'msg':msg}

if __name__ == '__main__':

    isTest = True
    cn = psycopg2.connect(database="datacenter", user="hntj", password="hntj!@)!", host="47.107.230.103", port="5432")

    hs = HsData(isTest,cn)
    hs.data_batch(916142)
