# coding=utf-8

import uuid
import requests
import json
import xmltodict
import time
from hashlib import md5
from django.conf import settings

from utils.exceptions import CustomError

# 微信支付sign_type
WEIXIN_SIGN_TYPE = 'MD5'
# 服务器IP地址
WEIXIN_SPBILL_CREATE_IP = '39.106.109.89'
# 微信支付用途
WEIXIN_BODY = u'小程序支付'
# 微信统一下单URL
WEIXIN_UNIFIED_ORDER_URL = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
# 微信查询订单URL
WEIXIN_QUERY_ORDER_URL = 'https://api.mch.weixin.qq.com/pay/orderquery'
# 微信支付回调API
WEIXIN_CALLBACK_API = 'https://print.zzliaoyuan.com/api/wechat_notify/'

class WechatPay():

    def __init__(self, appid, mch_id, merchant_key):
        self.params = {
            'appid': appid,
            'mch_id': mch_id,
            'nonce_str': '',
            'sign_type': WEIXIN_SIGN_TYPE,
            'body': WEIXIN_BODY,
            'out_trade_no': '',
            'total_fee': '',
            'spbill_create_ip': WEIXIN_SPBILL_CREATE_IP,
            'notify_url': WEIXIN_CALLBACK_API + appid + '/',
            'trade_type': 'JSAPI'
        }
        self.prepay_id = None
        self.merchant_key = merchant_key

    def getAppString(self):
        data = {
            'appId': self.params['appid'],
            'signType': WEIXIN_SIGN_TYPE,
            'package': "prepay_id={}".format(self.prepay_id),
            'nonceStr': generate_nonce_str(),
            'timeStamp': str(int(time.time()))
        }
        data['paySign'] = generate_sign(data, self.merchant_key)
        data.pop('appId')
        return data

    def unifiedOrder(self,out_trade_no,total_fee, openid):
        self.params['out_trade_no'] = out_trade_no
        self.params['total_fee'] = int(round(total_fee / 100,0))
        self.params['openid'] = openid
        self.params['nonce_str'] = generate_nonce_str()
        self.params['sign'] = generate_sign(self.params, self.merchant_key)
        data = xmltodict.unparse({'xml': self.params}, pretty=True, full_document=False).encode('utf-8')

        headers = {'Content-Type': 'application/xml'}
        res = requests.post(WEIXIN_UNIFIED_ORDER_URL, data=data, headers=headers)

        if res.status_code != 200:
            raise CustomError(u'微信请求失败！')

        result = json.loads(json.dumps(xmltodict.parse(res.content)))
        if result['xml']['return_code'] != 'SUCCESS':
            raise CustomError(u'微信通信失败！[%s]' % result['xml']['return_msg'])
        if result['xml']['result_code'] != 'SUCCESS':
            raise CustomError(u'微信交易失败！[%s:%s]' % (result['xml']['err_code'],result['xml']['err_code_des']))

        self.prepay_id = result['xml']['prepay_id']

        return result['xml']

class WechatPayNotify():
    def __init__(self,params, merchant_key):
        self.params = params
        self.merchant_key = merchant_key

    def handle(self):
        resp_dict = json.loads(json.dumps(xmltodict.parse(self.params)))['xml']
        return_code = resp_dict['return_code']

        if return_code != 'SUCCESS':
            return None

        if not validate_sign(resp_dict, self.merchant_key):
            return None

        return resp_dict

    @staticmethod
    def response_ok():
        return_info = {
            'return_code': 'SUCCESS',
            'return_msg': 'OK'
        }
        return generate_response_data(return_info)

    @staticmethod
    def response_fail():
        return_info = {
            'return_code': 'FAIL',
            'return_msg': 'FAIL'
        }
        return generate_response_data(return_info)

def generate_nonce_str():
    """
    生成随机字符串
    """
    return str(uuid.uuid4()).replace('-', '')

def generate_sign(params, merchant_key):
    """
    生成md5签名的参数
    """
    if 'sign' in params:
        params.pop('sign')
    src = '&'.join(['%s=%s' % (k, v) for k, v in sorted(params.items())]) + '&key=%s' % merchant_key
    return md5(src.encode('utf-8')).hexdigest().upper()

def validate_sign(resp_dict, merchant_key):
    """
    验证微信返回的签名
    """
    if 'sign' not in resp_dict:
        return False
    wx_sign = resp_dict['sign']
    sign = generate_sign(resp_dict, merchant_key)
    if sign == wx_sign:
        return True
    return False

def generate_response_data(resp_dict):
    """
    字典转xml
    """
    return xmltodict.unparse({'xml': resp_dict}, pretty=True, full_document=False).encode('utf-8')
