# coding:utf-8
#解决广点通回调问题
import json
import hashlib
import requests
import time
import uuid

from gm_types.gaia import PLATFORM_CHANNEL

from rpc.cache import channel_cache
from rpc.tool.log_tool import  channel_logger, logging_exception


client_id=1109734825
account_id=11270422

client_secret="j8qbhUZ3nnC2NCeY"
base_url="https://api.e.qq.com/oauth/token"

request_timeout=6

def md5(string):
    if string:
        md5=hashlib.md5()
        md5.update(string.encode(encoding='utf-8'))
        return md5.hexdigest()
    return string

def get_base_url(method):
    '''获取请求的基础url'''
    access_token=channel_cache.get("access_token")

    channel_logger.info("从缓存中拿到的access_token---")
    channel_logger.info(access_token)

    #刷新access_token
    if not access_token:
        refresh_token=channel_cache.get("refresh_token")
        access_token=refresh_access_token(refresh_token)
    try:
        timestamp= int(time.time())

        #不超过32位
        nonce=str(uuid.uuid4()).replace("-","")

        channel_logger.info("here")

        callback_url="https://api.e.qq.com/v1.1/{0}?access_token={1}&timestamp={2}&nonce={3}".format(method,access_token,timestamp,nonce)
        channel_logger.info("base_url")
        channel_logger.info(callback_url)

        return callback_url
    except Exception as e:
        channel_logger.info(e)

def refresh_access_token(refresh_token):
    '''
        刷新access_token
    '''
    global client_id
    global client_secret
    global base_url

    data={
        "client_id":client_id,
        "client_secret":client_secret,
        "grant_type":"refresh_token",
        "refresh_token":refresh_token
    }

    try:
        headers={'Content-Type': 'application/json'}
        response=requests.get(base_url,headers=headers, params=data,timeout=request_timeout).json()

        data=response.get("data")

        access_token=data.get("access_token")
        refresh_token=data.get("refresh_token")
        access_token_expires_in=int(data.get("access_token_expires_in"))-3600

        channel_cache.set("access_token",access_token)
        channel_cache.expire("access_token",access_token_expires_in)

        #23小时时就过去取重新刷数据
        channel_cache.set("refresh_token",refresh_token)

        return access_token

    except Exception as e:
        channel_logger.info(e)


def get_user_action_set_id(action_type="IOS"):
    '''
        获取user_action_set_id
        action_type:WEB, ANDROID, IOS, OFFLINE
    '''

    if action_type=="IOS":
        #有用户行为(创建账户时创建???)
        return 1109728494
    else:
        return 1109817959

    #应用id
    mobile_app_id="639234809"
    if action_type.lower()=="android":
        mobile_app_id="1101126509"

    callback_url=get_base_url("user_action_sets/add")
    data={
        "account_id":account_id,
        "type":action_type,
        "mobile_app_id":mobile_app_id,
        "name": "action_set",
        "description": ""
    }

    channel_logger.info("获取user_action_set_id")
    channel_logger.info(data)

    try:
        response=requests.post(callback_url, data=data,timeout=request_timeout)
        data=response.json()
        channel_logger.info(data)
        return data.get("data").get("user_action_set_id")
    except Exception as e:
        channel_logger.info(e)

def guangdiantong_active(record):
    """
        广点通数据上报
    """
    report_data = json.loads(record.click_request)
    if int(record.platform_type) == PLATFORM_CHANNEL.IOS:
        user_action_set_id = get_user_action_set_id(action_type="IOS")
        user_info = {"hash_idfa": report_data.get('muid', '')}
    else:
        user_action_set_id = get_user_action_set_id(action_type="ANDROID")
        user_info = {
            "hash_imei": report_data.get('muid', ''),
            'oaid': report_data.get('oaid', ''),
        }

    # 操作时间
    timestamp = int(time.time())

    data = {
        "account_id": account_id,
        "user_action_set_id": user_action_set_id,
        "actions": [{
            "action_time": timestamp, "user_id": user_info, "action_type": "ACTIVATE_APP",
            'trace': {'click_id': report_data.get('click_id', '')},
        }],
    }

    channel_logger.info("上报数据---")
    channel_logger.info(data)

    # {'account_id': 11270422, 'actions': [{'action_time': 1567048947, 'user_id': {'hash_idfa': u'9F81AB87-791D-4541-B8F8-8C6AF55C8E98'}, 'action_type': 'ACTIVATE_APP'}], 'user_action_set_id': 1109728494}
    # {u'message': u'JSON string is malformed.', u'code': 51002}
    callback_url = get_base_url("user_actions/add")

    try:
        headers={'Content-Type': 'application/json'}
    	response=requests.post(callback_url,headers=headers,data=json.dumps(data),timeout=request_timeout)
    	data=response.json()
        record.callback_response = response.text or ''

        #code不为0,提交失败
        if data.get("code"):
    	   channel_logger.info(data)
        else:
            channel_logger.info("上报成功---")
    except Exception as e:
    	channel_logger.info(e)

#获取access_token并更新到缓存
def get_token(authorization_code):
    '''请求access_token和refresh_token'''
    global client_id
    global client_secret
    global base_url

    data={
        "client_id":client_id,
        "client_secret":client_secret,
        "authorization_code":authorization_code,
        "grant_type":"authorization_code",
        "redirect_uri":"http://hermes.igengmei.com/integralwall/callback",
    }

    channel_logger.info("收到的数据---")
    channel_logger.info(data)

    try:
        response=requests.get(base_url, params=data,timeout=request_timeout)

        channel_logger.info(response.text)
        data=response.json().get("data")

        #data=json.loads('{"authorizer_info":{"account_uin":2409388915,"account_id":11270422,"scope_list":["user_actions"],"wechat_account_id":""},"access_token":"360994df1652cea7b9c97308f4529cf5","refresh_token":"8ed65a1ea6890ca9dc19fef3bf76a4e2","access_token_expires_in":86400,"refresh_token_expires_in":2592000}')

        access_token=data.get("access_token")
        refresh_token=data.get("refresh_token")

        channel_logger.info("获得的access_token--")
        channel_logger.info(access_token)

        access_token_expires_in=int(data.get("access_token_expires_in"))
        #减少1小时
        access_token_expires_in-=3600

        result=channel_cache.set("access_token",access_token)
        time_result=channel_cache.expire("access_token",access_token_expires_in)

        channel_logger.info("缓存结果---")
        channel_logger.info(result)
        channel_logger.info(time_result)

        #23小时时就过去取重新刷数据
        channel_cache.set("refresh_token",refresh_token)
    except Exception as e:
        channel_logger.info(e)