# coding=utf-8

import json
from datetime import datetime

from django.db.models import Q
from gm_types.gaia import (
    SERVICE_DISPLAY_PORT, SLIDE_USER_TYPE, SLIDE_PAYMENT_TYPE,
    WORLD_AREA_TYPE, SLIDE_TYPE, SERVICE_HOME_OPERATION
)

from api.models import (
    ServiceHomeOperation,
    NewCategory, ServiceHomeBackground,
    Special,
    ServiceRelatedOperation,
)
from api.tool.user_tool import  get_user_and_payment_info, get_user_from_context
from api.tool.city_tool import is_oversea
from api.tool.geo_tool import get_city_by_id

from rpc.decorators import bind_context
from api.tool.get_query import get_query_by_usertype_and_location


@bind_context('api/service_home/background')
def get_background(ctx):
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    base_query = Q(is_online=True, start_time__lte=now, end_time__gte=now)

    query = base_query
    background = ServiceHomeBackground.objects.filter(query).order_by('-id')
    result = {}
    if background.exists():
        background = background.first()
        result = {
            "background_img": background.background_img,
            "font_color": background.font_color,
        }
    return result


@bind_context('api/service_home/new_category')
def get_new_category(ctx, platform=None, device_id=None, city_id=None):
    user = get_user_from_context(ctx)
    query = get_query_by_usertype_and_location(user, platform=platform, device_id=device_id, city_id=city_id)

    new_category_qs = NewCategory.objects.filter(query).order_by('ordering', '-id').distinct()
    result = []
    for category in new_category_qs[:20]:
        data = {
            'name': category.name,
            'icon_img': category.icon,
            'order': category.ordering,
            'tags': list(category.tags.values_list('id', flat=True)),
        }
        result.append(data)
    return result


@bind_context('api/service_home/operational_location')
def get_operational_location(ctx, platform=None, device_id=None, city_id=None, display=SERVICE_DISPLAY_PORT.APP):
    now = datetime.now()
    base_query = Q(servicehome__is_online=True, servicehome__start_time__lte=now, servicehome__end_time__gte=now, servicehome__operation_type=SERVICE_HOME_OPERATION.ARRANGE)

    user = get_user_from_context(ctx)
    user_info = get_user_and_payment_info(user, platform, device_id)
    ### 获取新老用户信息
    user_type_choices = [SLIDE_USER_TYPE.ALL_USER]
    user_type_choices.append(SLIDE_USER_TYPE.NEW_USER if user_info.get('is_new_user') else SLIDE_USER_TYPE.OLD_USER)
    ## 获取是否支付信息
    payment_choices = [SLIDE_PAYMENT_TYPE.ALL_PAYMENT]
    payment_choices.append(SLIDE_PAYMENT_TYPE.HAVE_PAYMENT if user_info.get('have_payment') else SLIDE_PAYMENT_TYPE.NO_PAYMENT)

    user_query = Q(servicehome__user_type__in=user_type_choices) & Q(servicehome__payment_type__in=payment_choices)

    city_query = Q(servicehome__cities__isnull=True, servicehome__regions__isnull=True)
    if not city_id or city_id in WORLD_AREA_TYPE or is_oversea([city_id])[0]:
        pass
    else:
        city_query |= Q(servicehome__cities=city_id)
        region = None
        city = get_city_by_id(city_id)
        if city and city.province:
            try:
                region = city.province.region
            except:
                pass
        if region:
            city_query |= Q(servicehome__regions=region)

    display = 2 ** int(display)
    display_list = [i for i in range(2, 2 ** (1 + len(SERVICE_DISPLAY_PORT.choices))) if i % (display * 2) // display]
    port_query = Q(servicehome__display_port__in=display_list)
    query = base_query & user_query & city_query & port_query

    show_positions = [1,2,3]
    res_details = []
    for sp in show_positions:
        pos_ope = ServiceRelatedOperation.objects.filter(position=sp).filter(query).order_by('-servicehome_id').first()
        if not pos_ope:
            continue
        p_detail = {}
        p_detail['position'] = pos_ope.position
        p_detail['img'] = pos_ope.image
        p_detail['id'] = pos_ope.jump_id
        p_detail['jump_id'] = pos_ope.jump_id
        p_detail['banner_id'] = pos_ope.servicehome_id
        p_detail['operation_type'] = pos_ope.servicehome.operation_type
        p_detail['jump_type'] = pos_ope.jump_type
        try:
            if pos_ope.jump_type == SLIDE_TYPE.SPECIAL:
                p_detail['is_new_special'] = Special.objects.get(id=pos_ope.jump_id).is_new_special
        except:
            import traceback
            traceback.format_exc()
            pass
        res_details.append(p_detail)
    result = {}
    result['details'] = res_details
    result['operation_type'] = SERVICE_HOME_OPERATION.ARRANGE
    return result
