# coding: utf-8
from __future__ import unicode_literals, print_function, absolute_import
import itertools
import json
import random

from gm_types.gaia import DIARY_ORDER_TYPE
from gm_types.gaia import TAG_TYPE

from api.models import SeoDigest, Service, FriendlySite, InnerHyperlink, SeoCategory
from api.tool.image_utils import get_full_path
from api.tool.log_tool import logging_exception
from rpc.cache import seo_cache
from rpc.decorators import bind, cache_page
from rpc.tool.error_code import gen, CODES
from search.utils.service import filter_service
from search.utils.diary import filter_diary
from api.tool.datetime_tool import get_timestamp_or_none

# TODO: TALOS MIGRATE
from talos.models.diary import Diary
from talos.services import UserService


@bind('api/seo/digest/detail')
@cache_page(86400)
def get_seo_digest(digest_id, related_digests_count=50, service_count=20, diary_count=50):
    try:
        digest = SeoDigest.objects.get(pk=digest_id)
    except SeoDigest.DoesNotExist:
        return gen(CODES.SEO_DIGEST_NOT_FOUND)

    digest_detail = digest.detail_data()
    related_digests = digest.related_digests_for_list(size=related_digests_count)

    digest_category_tag_id = digest.seo_category.tag_id

    filter_services_result = filter_service(0, size=service_count, filters={'tag_ids': [digest_category_tag_id]})
    service_ids = filter_services_result['service_ids']
    if service_ids is []:
        services_data = []
    else:
        services = Service.objects.filter(id__in=service_ids)
        services_data = services.values('id', 'name', 'image_header', 'gengmei_price',
                                        'is_multiattribute', 'short_description')
        for service_data, service in itertools.izip(services_data, services):
            sk_info = service.get_lowest_price_seckill_info()
            update_data = {
                'original_price_display': service.get_original_price_display(),
                'sell_amount': service.sell_amount_display,
                'is_seckill': True if sk_info else False,
                'label': service.label,
                'is_can_be_sold': service.is_can_be_sold(),
                'service_image': service.image_header,
                'service_id': service.id,
                'service_name': service.name,
            }
            cache_data = service._get_fields_value_from_cache()
            service_data.update(update_data)
            service_data.update(cache_data)
        services_data = list(services_data)

    filter_diaries_result = filter_diary(0, size=diary_count, filters={'tag_ids': [digest_category_tag_id]},
                                         sort_type=DIARY_ORDER_TYPE.POPULARITY)
    diary_ids = filter_diaries_result['diary_ids']

    return {
        'digest': digest_detail,
        'related_digests': related_digests,
        'related_services': services_data,
        'related_diaries_ids': diary_ids,
    }


@bind('api/friendlysite/list')
@cache_page(120)
def get_friendlysite_list(city_id=None):
    return FriendlySite.online_sites(city_id)


@bind('api/innerlink/list')
@cache_page(3600)
def get_innerhyperlink_list():
    return InnerHyperlink.links()


@bind('api/seo/category/detail')
@cache_page(86400)
def get_category_detail(category_id):
    try:
        category = SeoCategory.objects.get(pk=category_id)
    except SeoCategory.DoesNotExist:
        return gen(CODES.SEO_CATEGORY_NOT_FOUND)

    return category.detail_data()


@bind('api/seo/category/child_list')
@cache_page(86400)
def get_category_child_list(category_id, count=5):
    try:
        category = SeoCategory.objects.get(pk=category_id)
    except SeoCategory.DoesNotExist:
        return gen(CODES.SEO_CATEGORY_NOT_FOUND)

    child_categories = category.child_categories(count=count)
    child_categories_data = [category.simple_data() for category in child_categories]

    return child_categories_data


@bind('api/seo/category/digest_list')
def get_category_related_digests(category_id, start_num=0, count=5, order_by=None):
    try:
        category = SeoCategory.objects.get(pk=category_id)
    except SeoCategory.DoesNotExist:
        return gen(CODES.SEO_CATEGORY_NOT_FOUND)

    related_digests = category.related_digests(order_by=order_by, start_num=start_num, count=count)
    digests_data = [digest.detail_data() for digest in related_digests]

    return digests_data


@bind('api/seo/random_categories')
@cache_page(86400)
def get_random_categories(category_id, count=5):
    """
    :param category_id: only be used for make cache key
    :param count:
    :return:
    """
    category_ids_cache_time = 86400
    all_category_ids_cache_key = '{}:{}:{}'.format('seo', 'category', 'all')
    cache_data = seo_cache.get(all_category_ids_cache_key)

    if cache_data is None:
        all_ids = SeoCategory.get_all_category_ids()
        seo_cache.setex(all_category_ids_cache_key, category_ids_cache_time, json.dumps(all_ids))
    else:
        try:
            all_ids = json.loads(cache_data)
        except:
            logging_exception()
            all_ids = SeoCategory.get_all_category_ids()
            seo_cache.setex(all_category_ids_cache_key, category_ids_cache_time, json.dumps(all_ids))

    if len(all_ids) < count:
        count = len(all_ids)

    show_ids = random.sample(all_ids, count)
    show_categories = list(SeoCategory.objects.filter(id__in=show_ids).values('id', 'name'))

    return show_categories


@bind('api/seo/digest_list/sitemap')
@cache_page(2*60)
def get_digest_list():
    """返回一千条最新发布咨询"""
    digest_list = list(SeoDigest.objects.filter(is_online=True).order_by('-online_time').values('id', 'online_time')[0:1000])
    for d in digest_list:
        d['online_time'] = get_timestamp_or_none(d['online_time'])
    return digest_list


@bind('api/seo/program_list/sitemap')
@cache_page(2*60)
def get_program_list():
    ids = SeoCategory.get_all_category_ids()
    return ids


@bind('api/seo/seocategory/list')
@cache_page(2*60)
def get_seo_category_list():
    """获取所有在线项目三级分类树状结构
    notice: 线上seo分类（SeoCategory）数据量大时可能会悲剧
    """
    data = []
    seo = SeoCategory.objects.filter(is_online=True, category_type=TAG_TYPE.BODY_PART)
    for seo_first in seo:
        data_first = {}
        data_first['id'] = seo_first.id
        data_first['name'] = seo_first.name
        seo_sec = []
        for seo_sec_item in seo_first.child_categories():
            data_sec = {}
            data_sec['id'] = seo_sec_item.id
            data_sec['name'] = seo_sec_item.name
            seo_thr = []
            for seo_thr_item in seo_sec_item.child_categories():
                data_thr = {}
                data_thr['id'] = seo_thr_item.id
                data_thr['name'] = seo_thr_item.name
                seo_thr.append(data_thr)
            data_sec['third_item'] = seo_thr
            seo_sec.append(data_sec)
        data_first['second_item'] = seo_sec
        data.append(data_first)

    return data
