# 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, FUNCTION_VERSION, WORLD_AREA_TYPE, PLATFORM_CHOICES, \
    SOURCE_POSITION_DEVICE_TYPE
from api.tool.user_tool import get_user_from_context, is_new_user_local, get_user_and_payment_info, \
    new_get_user_and_payment_info
from api.models.slide import ButtonSideslip
from api.models import IndexFunction, City, Province
from utils.version import version_gte, version_lte


@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, version=FUNCTION_VERSION.V1, city_id='', app_version=None):
    """
    首页功能区入口
    :return:
    """
    user = get_user_from_context(ctx)
    params = {'platform': platform, 'device_id': device_id, 'user': user if user else None}
    user_info = new_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, version=version, city_id=city_id, platform=platform, app_version=app_version)
    return {
        'func': data,
        'function_id': func_id
    }


def _get_func_data(user_type, is_payment, version=FUNCTION_VERSION.V1, city_id='', platform='', app_version=None):
    """
    http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=11600136
    """
    now_t = datetime.now()
    """新增城市和设备筛选"""
    # 规则如下：
    # 1. 定位在全部地区、无定位、定位在海外，只能看到全部地区的banner(不能看到配置具体城市的banner)
    # 2. 定位在具体城市，可以看到该城市、大区、全部地区的banner
    region, country_id = (None, None)
    try:
        city = City.objects.get(id=city_id)
        if city.province_id:
            province = Province.objects.select_related('region').get(id=city.province_id)
            region = province.region
            country_id = province.country_id
    except City.DoesNotExist:
        pass
    if not city_id or city_id in WORLD_AREA_TYPE or (region and region.english_name == 'haiwai') or \
            (country_id and country_id != 'china'):
        city_query = Q(relate_city__isnull=True, relate_region__isnull=True)
    else:
        city_query = Q(relate_city__city=city_id) | Q(relate_city__isnull=True, relate_region__isnull=True)
        if region:
            city_query |= Q(relate_region__region=region)
    query = city_query & Q(is_online=True) & Q(start_time__lte=now_t) & (Q(end_time__gte=now_t) | Q(end_time__isnull=True)) & Q(version=version)
    if platform == PLATFORM_CHOICES.IPHONE:
        query &= Q(device_type__in=[SOURCE_POSITION_DEVICE_TYPE.ALL_DEVICE_TYPE, SOURCE_POSITION_DEVICE_TYPE.IOS_DEVICE])
    elif platform == PLATFORM_CHOICES.ANDROID:
        query &= Q(device_type__in=[SOURCE_POSITION_DEVICE_TYPE.ALL_DEVICE_TYPE, SOURCE_POSITION_DEVICE_TYPE.ANDROID])
    else:
        query &= Q(device_type=SOURCE_POSITION_DEVICE_TYPE.ALL_DEVICE_TYPE)
    obj = IndexFunction.objects.filter(query)
    card_data = []
    function_id = ''
    if IndexFunction.get_visible(version):
        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 not data:
            return card_data, function_id

        first_data = None
        if app_version:
            for item in data:
                if not (
                    (item.min_version == '' and item.max_version == '') or
                    (item.min_version == '' and version_lte(app_version, item.max_version)) or
                    (version_gte(app_version, item.min_version) and item.max_version == '') or
                    (version_gte(app_version, item.min_version) and version_lte(app_version, item.max_version))
                ):
                    continue
                first_data = item
                break
        else:
            first_data = data.first()

        if not first_data:
            return card_data, function_id

        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
