from gm_rpcd.all import bind
from talos.rpc import bind_context
from django.conf import settings
from gm_types.gaia import USER_RIGHTS_LEVEL
from gm_types.user_hierarchy import EventType, FEEDBACK
from gm_types.gaia import INDEX_CARD_TYPE

from .models import UserGrowthValue, GrowthTask, UserFeedback
from .manager.event_dispatcher import EventDispatcher
from .tool.user_task_center import TaskCenter
from utils.rpc import gen
from gm_types.error import ERROR as CODES
from talos.services import get_user_from_context


dispatcher = EventDispatcher()


@bind('mimas/user/push_event')
def push_event(event_type, trigger_time, user_id, item_id, pre_payment=None):
    """push event to calc user growth value.

    .. http:POST:: mimas/user/push_event

    :param EventType event_type:
    :param int trigger_time:
    :param user_id:
    :param item_id: diary_id or order id etc
    :param pre_payment: if event type is EventType.BUYSERVICE, this is order's payment value.

    :return: growth value added
    """
    event_handler = dispatcher.dispatch(event_type, trigger_time, user_id, item_id, pre_payment)
    value = event_handler.process()
    return value


@bind('mimas/user/get_growth')
def get_user_growth(user_id):
    """通过user_id获取用户成长值.

    .. http:POST:: /mimas/user/get_growth

    :param user_id:

    **Example response**:

    .. sourcecode:: response

        {
            'value': int,
            'next_level_level': int,
            'level': USER_RIGHTS_LEVEL,
            'tasks': {
                'title':,
                'content':,
                'result':,
                'status':,
            },
        }

    """
    tasks = GrowthTask.get_user_today_status(user_id)
    try:
        growth = UserGrowthValue.objects.get(user_id=user_id)
        value = growth.value
        next_level_value = growth.next_level_value

        return {
            'value': value,
            'next_level_value': next_level_value,
            'level': growth.level,
            'tasks': tasks,
        }
    except UserGrowthValue.DoesNotExist:
        return {
            'value': 0,
            'next_level_value': settings.LEVEL_START_VALUE[USER_RIGHTS_LEVEL.V2],
            'level': USER_RIGHTS_LEVEL.V1,
            'tasks': tasks,
        }


@bind('mimas/user/get_daily_task')
def get_user_task_status(user_id):
    '''获取用户每日任务 7.6.20'''
    task_manager = TaskCenter(user_id)
    daily_data = task_manager.get_daily_task()
    try:
        growth = UserGrowthValue.objects.get(user_id=user_id)
        value = growth.value
        next_level_value = growth.next_level_value

        return {
            'level': growth.level,
            'level_score': value,  # 当前等级分值
            'level_total': settings.LEVEL_START_VALUE[growth.next_level],  # 该等级的总分
            'need_score': next_level_value,  # 到下一级的差值
            'next_level': growth.next_level,  # 到下一级的差值
            'upper_level_point': settings.LEVEL_UPPER_GAIN_POINTS,  # 升下一级所加的美分
            'uni_task': daily_data['uni_task'],  # 每日任务
            'multi_task': daily_data['multi_task'],  # 成长任务
        }

    except UserGrowthValue.DoesNotExist:
        return {
            'level': USER_RIGHTS_LEVEL.V1,
            'level_score': 0,  # 当前等级分值
            'level_total': settings.LEVEL_START_VALUE[USER_RIGHTS_LEVEL.V1],  # 该等级的总分
            'need_score': settings.LEVEL_START_VALUE[USER_RIGHTS_LEVEL.V2] - settings.LEVEL_START_VALUE[USER_RIGHTS_LEVEL.V1],  # 到下一级的差值
            'next_level': USER_RIGHTS_LEVEL.V2,
            'upper_level_point': settings.LEVEL_UPPER_GAIN_POINTS,  # 升下一级所加的美分
            'uni_task': daily_data['uni_task'],  # 每日任务
            'multi_task': daily_data['multi_task'],  # 成长任务
        }

@bind_context('mimas/user/process_event_task')
def process_task(ctx, event_type, user_id, related_item=None, version='7.6.19', only_record_event=False):
    try:
        from gm_rpcd.internals.proxy_object import unproxy
        client_info = unproxy(ctx)._Context__request.client_info  # 慎用
        version = client_info.get('cl_ver')
        session_key = unproxy(ctx)._Context__request.session_id
    except:
        version = version  # 7.6.20 以下皆可
        session_key = ''

    if not user_id or not event_type:
        return gen(CODES.PARAMS_INCOMPLETE)
    task_manager = TaskCenter(user_id, event_type, related_item, session_key)
    re_data = task_manager.get_reveal_data(only_record_event=only_record_event)
    if re_data['growth_value'] or re_data['point_value']:
        task_manager.add_work(version)

    return re_data


@bind_context('mimas/card/feedback')
def user_feedback(ctx, element_type, element_id, device_id, feedback_types):

    defaults = {}
    user = get_user_from_context(ctx)
    if user.id:
        defaults["user_id"] = user.id
    else:
        defaults["user_id"] = 0

    if not device_id and not user:
        return

    for item in feedback_types:
        if item not in FEEDBACK:
            continue

        UserFeedback.objects.get_or_create(
            element_type=element_type,
            element_id=element_id,
            device_id=device_id,
            feedback_type=item,
            defaults=defaults,
        )
