# coding=utf-8

import requests
import json
from django.utils import timezone
from django.conf import settings
from hashlib import md5
from utils.exceptions import CustomError
from apps.WechatApplet.models import WechatApplet

def gender_sign(gateway_key):
    ts = timezone.now().strftime('%Y%m%d%H%M%S')
    token = gateway_key + ts

    m = md5()
    m.update(token.encode("utf8"))
    sign = m.hexdigest()
    return ts, sign


def get_xgj_params(appid):
    applet = WechatApplet.getByAppid(appid)
    tenant = applet.tenant
    if not tenant.xgj_address:
        raise CustomError(u'小程序设置错误！')
    if not tenant.xgj_gateway_key:
        raise CustomError(u'小程序设置错误！')

    ts, sign = gender_sign(tenant.xgj_gateway_key)

    return tenant.xgj_address, ts, sign


class XGJ(object):

    @staticmethod
    def get_company(appid):
        xgj_addr, ts, sign = get_xgj_params(appid)
        url = xgj_addr + 'wechat/applet/member/company/?ts=' + ts + '&sign=' + sign
        param = {}
        result = requests.post(url=url, data=json.dumps(param))
        result = result.json()

        if not result['success']:
            if 'errors' in result:
                raise CustomError(u'请求失败--' + str(result['errors']))
            else:
                raise CustomError(u'请求失败')
        return result

    @staticmethod
    def get_member_card(appid, company_id, tel, number):
        xgj_addr, ts, sign = get_xgj_params(appid)
        url = xgj_addr + 'wechat/applet/member/select/?ts=' + ts + '&sign=' + sign
        param = {
            'company_id': company_id,
            'tel': tel,
            'number': number
        }
        result = requests.post(url=url, data=json.dumps(param))
        result = result.json()

        if not result['success']:
            if 'errors' in result:
                raise CustomError(u'请求失败--' + str(result['errors']))
            else:
                raise CustomError(u'请求失败')
        return result

    @staticmethod
    def get_member_info(appid, member_id):
        xgj_addr, ts, sign = get_xgj_params(appid)
        url = xgj_addr + 'wechat/applet/member/seacrh/?ts=' + ts + '&sign=' + sign + '&id=' + member_id

        result = requests.get(url)
        result = result.json()

        if not result['success']:
            if 'errors' in result:
                raise CustomError(u'请求失败--' + str(result['errors']))
            else:
                raise CustomError(u'请求失败')
        return result

    @staticmethod
    def get_member_points(appid, member_id, pageNum, pageSize):
        xgj_addr, ts, sign = get_xgj_params(appid)
        url = xgj_addr + 'wechat/applet/member/points/?ts=' + ts + '&sign=' + sign + '&id=' + member_id + '&page=' + pageNum + '&rows=' + pageSize

        result = requests.get(url)
        result = result.json()

        if not result['success']:
            if 'errors' in result:
                raise CustomError(u'请求失败--' + str(result['errors']))
            else:
                raise CustomError(u'请求失败')
        return result

    @staticmethod
    def get_member_record(appid, member_id, pageNum, pageSize):
        xgj_addr, ts, sign = get_xgj_params(appid)
        url = xgj_addr + 'wechat/applet/member/consume/?ts=' + ts + '&sign=' + sign + '&id=' + member_id + '&page=' + pageNum + '&rows=' + pageSize

        result = requests.get(url)
        result = result.json()

        if not result['success']:
            if 'errors' in result:
                raise CustomError(u'请求失败--' + str(result['errors']))
            else:
                raise CustomError(u'请求失败')
        return result

    @staticmethod
    def get_member_balance(appid, member_id):
        xgj_addr, ts, sign = get_xgj_params(appid)
        url = xgj_addr + 'wechat/applet/member/balance/?ts=' + ts + '&sign=' + sign + '&member_id=' + member_id

        result = requests.get(url)
        result = result.json()

        if not result['success']:
            if 'errors' in result:
                raise CustomError(u'请求失败--' + str(result['errors']))
            else:
                raise CustomError(u'请求失败')
        return result

    @staticmethod
    def refresh_member_card(tenant, member_id, amount, points, discount_amount):
        if not tenant.xgj_gateway_key:
            raise CustomError(u'小程序设置错误')
        if not tenant.xgj_address:
            raise CustomError(u'小程序设置错误')

        ts, sign = gender_sign(tenant.xgj_gateway_key)
        url = tenant.xgj_address + 'wechat/applet/member/use/?ts=' + ts + '&sign=' + sign + '&member_id=' + member_id

        param = {
            'amount': amount,
            'points': points,
            'discount_amount': discount_amount
        }
        result = requests.post(url=url, data=json.dumps(param))
        result = result.json()

        res = ''

        if not result['success']:
            if 'errors' in result:
                res = u'请求失败--' + str(result['errors'])
            else:
                res = u'请求失败'
        return res
