# coding=utf-8
from __future__ import absolute_import
import json
import types
from django.conf import settings
from hashlib import md5
import requests
import json
from random import Random
from rpc.tool.log_tool import yinuo_logger

def random_str(randomlength=32):
    str = ''
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str


def _smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Returns a bytestring version of 's', encoded as specified in 'encoding'.
    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    if not isinstance(s, basestring):
        try:
            return str(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return ' '.join([_smart_str(arg, encoding, strings_only,
                                            errors) for arg in s])
            return unicode(s).encode(encoding, errors)
    elif isinstance(s, unicode):
        return s.encode(encoding, errors)
    elif s and encoding != 'utf-8':
        return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s


def _params_filter(params):
    ks = params.keys()
    ks.sort()
    newparams = {}
    prestr = ''
    for k in ks:
        v = params[k]
        k = _smart_str(k, settings.ALIPAY_INPUT_CHARSET)
        if k not in ('sign') and v != '':
            newparams[k] = _smart_str(v)
            # newparams[k] = v
            if k!='extra':
                prestr += '%s%s' % (k, newparams[k])
            # prestr += u'{key}={value}&'.format(
            #     key=k,
            #     value=newparams[k],
            # )
            else:
                newparams['extra'] = params['extra']
    return newparams, prestr



def _build_mysign(prestr, private_key):
    """
        生成签名结果
    """
    # final_str = prestr + private_key
    return md5(_smart_str(prestr + private_key)).hexdigest()


def create_insurance(product_id, plan, mobile, id_card, id_name, money, hospital_name, operation_name):
    params = {
        "user_id":settings.YINUO_USER_ID,
        "product_id":product_id,
        "plan":plan,
        "policyholder_mobile":mobile,
        "policyholder_id_type":"身份证",
        "policyholder_id_card":id_card,
        "policyholder_name":id_name,
        # "policyholder_sex":"M",
        "insurant_mobile":mobile,
        "insurant_id_type":"身份证",
        "insurant_id_card":id_card,
        "insurant_name":id_name,
        # "insurant_sex":"M", //被保人性别
        "money":money,
        "extra":{
            'yiyuan': hospital_name,
            'xiangmu': operation_name
        },
        "noncestr":random_str(),
    }
    params, prestr = _params_filter(params)
    params['sign'] = _build_mysign(prestr, settings.YINUO_SECRECT)
    url = settings.YINUO_CREATE_URL
    headers = {'content-type': 'application/json'}
    yinuo_logger.info(json.dumps(params))
    rsp = requests.post(url, headers=headers, data=json.dumps(params))
    '''
    <Response [200]> {"guarantee_slip_id":"USF1QVVL","payment_id":"GDP8MLGC"}
    '''
    yinuo_logger.info(rsp.text)
    return json.loads(rsp.text)

def pay_balance(product_id, payment_id):
    params = {
        'user_id': settings.YINUO_USER_ID,
        'payment_id':payment_id,
        "noncestr":random_str(),
    }
    params, prestr = _params_filter(params)
    params['sign'] = _build_mysign(prestr, settings.YINUO_SECRECT)
    url = settings.YINUO_PAY_URL
    headers = {'content-type': 'application/json'}
    yinuo_logger.info(json.dumps(params))
    rsp = requests.post(url, headers=headers, data=json.dumps(params))
    yinuo_logger.info(rsp.text)
    return rsp