# coding: utf-8

import json
import re
import requests
import time
from hashlib import md5

from django.conf import settings

from api.tool.log_tool import logging_exception
from rpc.tool.random_tool import random_str


class QQConnect(object):
    """
    QQ互联验证功能
    """
    # Authorization Code -> Access Token
    access_token_url = 'https://graph.qq.com/oauth2.0/token'

    # Access Token -> Openid
    open_id_url = 'https://graph.qq.com/oauth2.0/me'

    # Consume Card
    consume_url = 'https://api.qcoupon.qq.com/card/user/usecard'

    def __init__(self, code, redirect_uri, card_id=None,
                 signature=None, attach=None):
        self.appid = settings.QQ_CONNECT_APPID
        self.appkey = settings.QQ_CONNECT_APPKEY
        self.code = code
        self.card_id = card_id
        self.signature = signature
        self.attach = attach
        self.redirect_uri = redirect_uri

    def get_openid_access_token(self):
        """
        获取openid和access_token
        """
        request_params = {
            'grant_type': 'authorization_code',
            'client_id': self.appid,
            'client_secret': self.appkey,
            'code': self.code,
            'redirect_uri': self.redirect_uri,
        }

        try:
            access_token_result = requests.get(self.access_token_url,
                                               params=request_params,
                                               timeout=3)
        except:
            logging_exception()
            return None, None

        access_token_text = access_token_result.text
        # access_token_text: u'access_token=99CC7830D42F****80A49E3A952CA002&expires_in=7776000&refresh_token=3769ECD2F3AC****53FED4F4632D06CD'

        access_token_text_list = access_token_text.split('&')
        access_dict = {}

        try:
            for _text in access_token_text_list:
                key, value = _text.split('=')
                access_dict[key] = value
        except:
            logging_exception()
            return None, None

        access_token = access_dict.get('access_token')

        if not access_token:
            return None, None

        request_params = {'access_token': access_token}
        try:
            openid_result = requests.get(self.open_id_url,
                                         params=request_params,
                                         timeout=3)
        except:
            logging_exception()
            return None, None

        openid_text = openid_result.text
        # openid_text: u'callback( {"client_id":"101365749","openid":"190B6C68EE40D6FBC975F72ECD2C821D"} );\n'

        openid_json_re = re.search(r'\{(.*)\}', openid_text)
        if not openid_json_re:
            return None, None

        openid_dict = json.loads(openid_json_re.group())

        return openid_dict.get('openid'), access_token

    def notify_gained(self):
        pass

    def notify_consumed(self, open_id, attach, access_token, card_code):
        """
        QQ卡券使用通知接口
        :param open_id:              获取卡券时的用户openid
        :param attach:               获取卡券时跳转参数
        :param access_token:         获取卡券时换取的用户access_token
        :return:
        """
        request_body_dict = {
            'appid': int(settings.QQ_CONNECT_APPID),
            'timestamp': int(time.time()),
            'rand_str': random_str(),
            'req': {
                'card_id': self.card_id,
                'code': card_code,
                'openid': open_id,
                'access_token': access_token,
                'attach': attach,
            },
        }
        request_body = json.dumps(request_body_dict, separators=(',', ':'))
        original_str = 'key={}&post_body={}'.format(settings.QQ_CONNECT_MD5KEY, request_body)
        signature = md5(original_str).hexdigest().lower()
        url = self.consume_url + '?signature=' + signature
        try:
            result_json = requests.post(url, request_body, timeout=3)
        except:
            logging_exception()
            return False

        # result example:
        # '{"result":"{\\"card\\":{\\"card_id\\":\\"CH-aPoMSJ9IsnvLA8TbW8KqnmX5rBW0N\\"},
        # \\"errcode\\":0,\\"openid\\":\\"\\",\\"errmsg\\":\\"success\\"}",
        # "signature":"02dd1f519be3729586565f8afb646105"}'
        result = json.loads(result_json.content)
        result_data = json.loads(result['result'])
        if result_data['errcode']:
            return False
        return True
