#橙券支付

import hashlib
import datetime
import time
import json 
import urllib.request
import urllib.parse
import random
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

domain='https://api.chengquan.cn'

# appid='15020190001'
# k='0BE0C9FEE504983B285B9407CB9C85D9'
# domain='http://test.api.chengquan.cn'

class CQPay:

    def __init__(self, appid, k, aes_key='', aes_iv=''):
        self.appid = appid
        self.k =k
        self.aes_key = aes_key
        self.aes_iv = aes_iv

    def generate_sign(self,data):
        jsonstr = json.dumps(data, sort_keys=True)
        params_json = json.loads(jsonstr)
        items = params_json.items()
        ostr=''
        for key, value in items:
            if value:
                ostr = ostr + str(key) + '=' + str(value) + '&'
        ostr = ostr + 'key='+self.k
        print(ostr)
        m2 = hashlib.md5(ostr.encode(encoding='UTF-8'))
        return m2.hexdigest()

    def http_post(self,data, type, url):
        timestamp = int(round(time.time() * 1000))
        data['timestamp'] = timestamp
        data['app_id'] = self.appid
        if type:
            data['type'] = type
        sign = self.generate_sign(data)
        data['sign'] = sign 
        data = json.dumps(data)
        data = bytes(data,"utf8")
        headers={'Content-Type':'application/json'}   
        request = urllib.request.Request(domain+url, data, headers)   
        res = urllib.request.urlopen(request).read().decode('utf-8')
        return json.loads(res)

    def http_post_form(self, data, type, url):
        timestamp = int(round(time.time() * 1000))
        data['timestamp'] = timestamp
        data['app_id'] = self.appid
        if type:
            data['type'] = type
        sign = self.generate_sign(data)
        data['sign'] = sign 
        data = urllib.parse.urlencode(data).encode('utf-8')
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}   
        request = urllib.request.Request(domain + url, data, headers)   
        res = urllib.request.urlopen(request).read().decode('utf-8')
        return json.loads(res)

    # 解密
    def decrypt_p(self, text):
        cipher = AES.new(self.aes_key.encode('utf-8'), AES.MODE_CBC, self.aes_iv.encode('utf-8'))
        # 将密文进行 base64解码
        ciphertext = base64.b64decode(text)
        # 解密并去除填充
        decrypted_text = unpad(cipher.decrypt(ciphertext), AES.block_size)
        return decrypted_text.decode('utf-8')

    # 微信转账发放下单接口
    def unite_submit(self,project_no, open_id, out_request_no, wechat_app_id, wishing, amount):
        data = {
            'project_no': project_no,
            'open_id': open_id,
            'out_request_no': out_request_no,
            'wechat_app_id': wechat_app_id,
            'wishing': wishing,
            'amount': amount,
            'ip': '116.62.122.204'
        }
        return self.http_post(data, 'WECHAT_TRANSFER', '/voucher_platform/unite/submit')

    def unite_query(self,out_request_no):
        data = {
            'out_request_no': out_request_no
        }
        return self.http_post(data, 'WECHAT_TRANSFER', '/voucher_platform/unite/query')
    
    # 优惠券、打车券等下单接口
    def coupon_order_pay(self, user_order_no, goods_no, count, mobile):
        data = {
            'user_order_no': user_order_no,
            'goods_no': goods_no,
            'count': count,
        }
        if mobile:
            data['mobile'] = mobile
        return self.http_post_form(data, '', '/coupon/order/pay')
    
    def order_direct_charge(self, order_no, recharge_number, product_id, amount=1, ip='', oil_phone_account=''):
        data = {
            'order_no': order_no,
            'recharge_number': recharge_number,
            'product_id': product_id,
            'amount': amount,
            'ip': ip,
            'oil_phone_account': oil_phone_account,
            'notify_url': '',
            'version': '1.0.0'
        }
        return self.http_post_form(data, '', '/order/directCharge')
    
    # 生成订单号
    def generate_order_number():
        timestamp = int(time.time())
        random_number = random.randint(1000, 9999)
        order_number = str(timestamp) + str(random_number)
        return order_number

# cq = CQPay('13292760999','87D4FBD33BAA2DA24E662F3B1DFA7F6D','jRmXqNwpgZu4ajx6','zATElprydEbu2yfx')
# res = cq.coupon_order_pay('test123456789',"17001043",1,"18108807612")
# res = cq.order_direct_charge('test123456789','18108807612',"1088",1,"18108807612")
# res = cq.decrypt_p('FDdIqdik3pghOoLhnueRKE0TGNNT9aLs75rNanFfzgQ=')
# print(res)