# coding=utf-8

import json
from datetime import datetime
from django.db.models import Q
from rpc.decorators import bind, bind_context
from gm_types.gaia import SLIDE_USER_TYPE, SLIDE_PAYMENT_TYPE
from api.tool.user_tool import get_user_from_context, is_new_user_local, get_user_and_payment_info
from api.models.slide import ButtonSideslip
from api.models import IndexFunction

@bind('api/index/button_slide')
def get_button_slide():
    """
    首页按钮横滑
    :return:
    """
    buttons = ButtonSideslip.get_buttons(page_type=0, mask_invisible=True)['button_list']
    buttons = sorted(buttons, key=lambda btn: int(btn['rank']) if btn['rank'] else 9999)
    return list(buttons)


@bind_context('api/index/v6/func')
def get_button_func(ctx, platform=None, device_id=None):
    """
    首页功能区入口
    :return:
    """
    user = get_user_from_context(ctx)
    params = {'platform': platform, 'device_id': device_id, 'user': user if user else None}
    user_info = get_user_and_payment_info(**params)
    have_payment = user_info.get('have_payment')
    is_new_user = user_info.get('is_new_user')
    if is_new_user:
        user_type = SLIDE_USER_TYPE.NEW_USER
    else:
        user_type = SLIDE_USER_TYPE.OLD_USER
    if have_payment:
        is_payment = SLIDE_PAYMENT_TYPE.HAVE_PAYMENT
    else:
        is_payment = SLIDE_PAYMENT_TYPE.NO_PAYMENT
    data, func_id = _get_func_data(user_type, is_payment)
    return {
        'func': data,
        'function_id': func_id
    }


def _get_func_data(user_type, is_payment):
    """
    http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=11600136
    """
    now_t = datetime.now()
    query = Q(is_online=True) & Q(start_time__lte=now_t) & (Q(end_time__gte=now_t) | Q(end_time__isnull=True))
    obj = IndexFunction.objects.filter(query)
    card_data = []
    function_id = ''
    if IndexFunction.get_visible():
        if obj.filter(user_type=user_type, is_payment=is_payment):
            data = obj.filter(user_type=user_type, is_payment=is_payment)
        elif obj.filter(user_type=user_type, is_payment=SLIDE_PAYMENT_TYPE.ALL_PAYMENT):
            data = obj.filter(user_type=user_type, is_payment=SLIDE_PAYMENT_TYPE.ALL_PAYMENT)
        elif obj.filter(user_type=SLIDE_USER_TYPE.ALL_USER, is_payment=is_payment):
            data = obj.filter(user_type=SLIDE_USER_TYPE.ALL_USER, is_payment=is_payment)
        else:
            data = obj.filter(user_type=SLIDE_USER_TYPE.ALL_USER, is_payment=SLIDE_PAYMENT_TYPE.ALL_PAYMENT)
        if data:
            first_data = data.first()
            function_id = first_data.id
            card_data = json.loads(first_data.card_data)
            card_data = sorted(card_data, key=lambda card: int(card['rank']))
        for item in card_data:
            item.update({"id": function_id})
    return card_data, function_id
