# -*- coding: utf-8 -*-
# @Time    : 2019/4/10
import datetime

from django.db.models import Q

from api.tool.log_tool import logging_exception
from gm_types.gaia import POLYMER_CONTENT_TYPE, SLIDE_USER_TYPE, SLIDE_PAYMENT_TYPE, PLATFORM_CHOICES, \
    SOURCE_POSITION_DEVICE_TYPE

from api.models import City
from api.tool.user_tool import get_user_from_context, new_get_user_and_payment_info
from rpc.decorators import bind, bind_context
from ..models import CategoryPolymer, CategoryPolymerRecommend, CategoryMap
from api.tool.geo_tool import get_city_by_options
from api.tool.city_tool import get_city_id_by_options


@bind_context('api/category/polymer')
def get_category_polymer(ctx, category_polymer_id, city_id=None, lat=None, lng=None, platform='', device_id=''):
    """
    品类聚合页
    :param category_polymer_id:
    :return:
    """
    city_id = get_city_id_by_options(city_id, lat, lng)
    user = get_user_from_context(ctx)
    params = {'platform': platform, 'device_id': device_id, 'user': user if user else None}
    user_payment_info = new_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.NO_PAYMENT
    if user_payment_info and user_payment_info.get('have_payment'):
        payment_type = SLIDE_PAYMENT_TYPE.HAVE_PAYMENT
    device_type = SOURCE_POSITION_DEVICE_TYPE.ALL_DEVICE_TYPE
    if platform == PLATFORM_CHOICES.IPHONE:
        device_type = SOURCE_POSITION_DEVICE_TYPE.IOS_DEVICE
    elif platform == PLATFORM_CHOICES.ANDROID:
        device_type = SOURCE_POSITION_DEVICE_TYPE.ANDROID
    cp = CategoryPolymer.objects.get(id=category_polymer_id)
    slides = cp.get_banners(city_id, user_type=user_type, device_type=device_type, payment_type=payment_type)
    category_area = cp.get_areas()
    brands = cp.get_brands()
    groups = cp.get_groups()
    static_templates = cp.get_gadgets()
    return {
        'slides': slides,
        'category_area': category_area,
        'brands': brands,
        'groups': groups,
        'static_templates': static_templates,
        'search_word': cp.search_word,
        'id': cp.id,
        'name': cp.name,
        'tags': CategoryPolymer.get_tags(category_polymer_id),
        'tags_v3': CategoryPolymer.get_tags_v3(category_polymer_id),
        "operation_id": cp.operation_level_one_id if cp.operation_level_one_id else -1

    }


@bind('api/category/polymer_recommend')
def get_ctg_plm_recommend(cp_id, city_id=None, lat=None, lng=None):
    '''
    获取品类聚合页运营推荐位及tags_id
    '''
    city_id = get_city_id_by_options(city_id, lat, lng)

    recommends = CategoryPolymer.get_recommend(cp_id, city_id) or {}
    tags = CategoryPolymer.get_tags(cp_id)
    result = {}
    result['recommends'] = recommends
    result['tags'] = tags
    return result


@bind("categorypolymerrecommend/auto_create")
def categorypolymerrecommend_auto_create(data):
    try:
        # 城市处理
        cities = data["cities"]
        provinces = data["provinces"]
        all_cities = set()
        for item in cities:
            all_cities.add(item['id'])
        for item in provinces:
            cities_ls = set(City.objects.filter(province_id=item["id"]).values_list("id", flat=True))
            all_cities ^= cities_ls
        service_id = data["service_id"]
        is_related_city = True if all_cities else False
        sideskidcategory_id = data['content_id']
        #通过映射获取categorypolymerrecommend_id
        categorypolymer_id = CategoryMap.objects.get(sideskidcategory_id=sideskidcategory_id).categorypolymer_id
        obj = CategoryPolymerRecommend.objects.create(categorypolymer_id=categorypolymer_id, content_id=service_id,
                                                      content_type=POLYMER_CONTENT_TYPE.SERVICE, start_time=data['start_time'],
                                                      end_time=data['end_time'], rank=data['position'], is_related_city=is_related_city)
        if is_related_city:
            obj.add_related_cities(list(all_cities))
        obj.save()
        return {"result": "success"}
    except:
        logging_exception()
        return {"result": "fail"}


@bind('api/category/polymer_recommend/service_ids')
def query_category_polymer_recomment_services(cp_id, city_id):
    """
    获取品类聚合页运营推荐位相关美购
    :param cp_id:CategoryPolymer 主键id
    :param city_id:城市id
    :return: [123,456,236,789] service_id 按照rank排序
    """
    time_now = datetime.datetime.now()
    common_query = Q(is_online=True, start_time__lte=time_now, end_time__gte=time_now, categorypolymer_id=cp_id)
    city_query = Q(is_related_city=False)
    if city_id:
        temp_query = Q(category_recommend_cities__city_id=city_id, is_related_city=True)
        city_query = city_query | temp_query
    objs = CategoryPolymerRecommend.objects.filter(common_query, city_query).order_by('rank').only('content_id')
    ans = []
    for obj in objs:
        ans.append(int(obj.content_id))
    return ans
