import datetime
from celery import shared_task
from django.conf import settings
from gm_protocol import GmProtocol
from gm_types.push.enum import PUSH_INFO_TYPE, AUTOMATED_PUSH
from gm_types.gaia import USER_RIGHTS_LEVEL, POINTS_TYPE
from utils.rpc import get_rpc_invoker
from utils.rpc import logging_exception
from user_hierarchy.models import UserEventLog, UserGrowthValue
from user_hierarchy.score import get_level_by_value
from user_hierarchy.libs.user import rpc_update_user_level


gm_protocol = GmProtocol(api_host=settings.BACKEND_API_HOST+'/')


@shared_task
def process_notify_message(user_id, title='升级提醒', message=None, url=''):
    # TODO : 处理通知
    if settings.INIT_DATA:
        return

    try:
        r = get_rpc_invoker()
        r['api/notification/create'](uid=user_id, title=title, content=message, url=url).unwrap()
    except:
        logging_exception()
    return


@shared_task
def process_push_message(user_id, message, extra=None, push_type=None):
    # TODO: 处理推送  除了更美等级提升，其他场景目前不会触发推送
    if settings.INIT_DATA:
        return

    try:
        rpc_client = get_rpc_invoker()
        rpc_client['push2/push/user/automated_push/uids'](
            push_type=push_type,
            user_ids=[user_id],
            alert=message,
            extra=extra,
        ).unwrap()
    except Exception as e:
        logging_exception()
        print(e)
    return 'ok'


@shared_task
def process_user_add_value(user_id, version='7.6.19'):
    # process  event that user add value triggered
    # tips: level may upper or lower
    user_value = UserEventLog.get_user_value(user_id)
    try:
        user_growth = UserGrowthValue.objects.get(user_id=user_id)
        user_value = user_value if user_value > 0 else 0  # 负值时统一显示为0，同时记录其负值@PM －－ eventlog表有负值记录
        pre_level = user_growth.level
        now_level = get_level_by_value(user_value)
        if pre_level != now_level:
            user_growth.value = user_value
            user_growth.level = now_level
            user_growth.save()
            if int(now_level) > int(pre_level):
                _build_level_upper_message(user_id, pre_level, now_level, version)
                add_user_point(user_id, POINTS_TYPE.LEVEL_UPPER, settings.LEVEL_UPPER_GAIN_POINTS)
            return _callback_update_user_level(user_id, now_level)

        user_growth.value = user_value
        user_growth.save()

    except UserGrowthValue.DoesNotExist:
        now_level = get_level_by_value(user_value)
        UserGrowthValue.objects.create(user_id=user_id, value=user_value, level=now_level)
        if not now_level == USER_RIGHTS_LEVEL.V1:
            add_user_point(user_id, POINTS_TYPE.LEVEL_UPPER, settings.LEVEL_UPPER_GAIN_POINTS)


def _callback_update_user_level(user_id, level):
    # call gaia to update user level
    if settings.INIT_DATA:
        return

    user = {'user_id': user_id, 'level': level}
    rpc_update_user_level([user, ])


def _build_level_upper_message(user_id, pre_level, now_level, version='7.6.19'):
    title = '升级提醒'
    message = '快来看！你的更美等级由等级{}升级到了等级{}，多了哪些特权呀？——'.format(pre_level, now_level)
    if version == '7.6.20':
        from six.moves import urllib_parse as urlparse
        url_new = urlparse.urljoin(
            gm_protocol.api_host,
            'hybrid/user/rights_v1?user_id={}'.format(user_id)
        )
        url = gm_protocol.get_webview(url_new)
    elif version >= '7.6.25':
        url = gm_protocol.get_user_task_center()
    else:
        url = gm_protocol.get_user_rights(user_id)
    extra = {
        'type': PUSH_INFO_TYPE.GM_PROTOCOL,
        'msgType': 4,
        'pushUrl': url,
        'push_url': url,
    }
    process_notify_message.delay(user_id, title=title, message=message, url=url)
    process_push_message.delay(user_id, message=message, extra=extra, push_type=AUTOMATED_PUSH.USER_LEVEL_UP)
    return


@shared_task
def add_user_point(user_id, point_type, point_v=0):
    try:
        r = get_rpc_invoker()
        r['api/point/add'](user_id=user_id, point_type=point_type, point_v=point_v).unwrap()
    except:
        logging_exception()


@shared_task
def add_user_growth(user_id, event_type, item_id, value, version='7.6.19'):
    UserEventLog.objects.create(
        event_type=event_type,
        related_item_id=item_id,
        trigger_time=datetime.datetime.now(),
        value=value,
        user_id=user_id,
    )
    process_user_add_value(user_id, version)