#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime

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

from api.models import City
from api.tool.user_tool import get_user_and_payment_info


def format_operate_query(user=None, platform=None, device_id=None, city_id=None):
    """
    格式化 运营位的搜索 从 api/view/slide.py 迁移的子方法
    :param user:  user
    :param platform: 来源
    :param device_id: 设备id
    :param city_id: 城市id
    :return: query
    """

    params = {'platform': platform, 'device_id': device_id, 'user': user if user else None}
    user_payment_info = get_user_and_payment_info(**params)

    user_type = SLIDE_USER_TYPE.OLD_USER
    if user_payment_info and user_payment_info.get('is_new_user'):
        user_type = SLIDE_USER_TYPE.NEW_USER

    payment_type = SLIDE_PAYMENT_TYPE.HAVE_PAYMENT
    if user_payment_info and not user_payment_info.get('have_payment'):
        payment_type = SLIDE_PAYMENT_TYPE.NO_PAYMENT

    query = Q(is_online=True)
    query &= Q(user_type__in=[user_type, SLIDE_USER_TYPE.ALL_USER])
    query &= Q(payment_type__in=[payment_type, SLIDE_PAYMENT_TYPE.ALL_PAYMENT])

    region, country = (None, None)
    try:
        city = City.objects.get(id=city_id)
        if city.province:
            region = city.province.region
            country = city.province.country
    except City.DoesNotExist:
        pass

    if not city_id or city_id in WORLD_AREA_TYPE or (region and region.english_name == 'haiwai') or \
            (country and country.id != 'china'):
        city_query = Q(regions__isnull=True, cities__isnull=True)
    else:
        city_query = Q(cities=city_id) | Q(regions__isnull=True, cities__isnull=True)
        if region:
            city_query |= Q(regions=region)
    query &= city_query

    now = datetime.datetime.now()
    query &= Q(start_time__lte=now)
    query &= (Q(end_time__isnull=True) | Q(end_time__gte=now))

    return query
