# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import

import json

from django.conf import settings
from gm_types.gaia import SERVICE_ORDER_TYPE

from api.models import Service, ServiceItem
from api.models import Special, SpecialItem
from api.models import (GroupBuyTeamOrder, OrderExtra, ServiceItemPrice,
                        SKUPriceRule, Special)

from rpc.tool.es_helpers import get_objects_from_queryset_and_pk_list
from rpc.cache import service_config_cache
from rpc.cache import hospital_doctor_service_cache

from gaia.routers import thread_local
from search.utils.service import filter_service

import json

from doris.models.service import Promotion


def get_special_services(special_id=None):
    # TODO: 优化不用多次查找数据库
    services = []
    try:
        special = Special.objects.get(pk=special_id)
        service_ids = set(SpecialItem.objects.filter(special=special).values_list('service_id', flat=True))
        services = Service.objects.filter(id__in=service_ids)
    except:
        pass
    return services


def get_serviceitem_by_option_id(options, service_id):
    items = ServiceItem.objects.filter(service_id=service_id)
    option_ids = options.split('-')
    for option_id in option_ids:
        items = items.filter(serviceitemkey__serviceattroption__id=option_id)
    if len(items) < 1:
        return None
    return items.last()


def check_option_id_is_exist(option, options):
    for item in options:
        if option['option_id'] == item['option_id']:
            return True
    return False


def get_service_by_tags(tag_ids, offset=0, size=10,
                        sort_type=SERVICE_ORDER_TYPE.DEFAULT,
                        sort_params=None):
    filters = {'tag_ids': tag_ids}

    if sort_params is None:
        sort_params = {}

    service_ids = filter_service(
        offset=0, size=size,
        sort_type=sort_type, filters=filters,
        sort_params=sort_params
    )
    ids = service_ids['service_ids']
    services = get_objects_from_queryset_and_pk_list(
        Service.objects.filter(is_online=True), pk_list=ids
    )
    return services


def sell_count_display(num):
    if num >= 10000:
        return str(num / 10000) + u'w'
    if num >= 1000:
        return str(num / 1000) + u'k'
    return str(num)


class ServiceConfig(object):
    """
    购买须知配置
    """
    key = 'service_config'
    default_config = {
        'config_content': '',  # 配置内容
    }

    @classmethod
    def get(cls):
        try:
            config = json.loads(service_config_cache.get(cls.key))
        except:
            config = cls.default_config
        return config

    @classmethod
    def set(cls, new_config):
        if not new_config:
            return

        config = cls.get()
        for k, v in new_config.items():
            if k in config:
                config[k] = v

        try:
            service_config_cache.set(cls.key, json.dumps(config))
        except:
            service_config_cache.error(u'设置购买须知配置失败')


@thread_local(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def get_city_ids_has_online_service():
    _cache = hospital_doctor_service_cache
    _k = 'cities_w_online_service'

    city_ids = _cache.get(_k)
    if city_ids:
        return json.loads(city_ids)

    city_ids = set(Service.objects.filter(is_online=True).values_list('doctor__hospital__city', flat=True))
    if city_ids:
        city_ids = list(city_ids)
        _cache.setex(_k, 2 * 3600, json.dumps(city_ids))

    return city_ids


def _get_activity_info(groupbuyteam):

    order_obj = GroupBuyTeamOrder.objects.filter(groupbuy_team_id=groupbuyteam.id).first()
    order_extra_obj = OrderExtra.objects.filter(order_id=order_obj.order_id).first() if order_obj else None
    activity_id = order_extra_obj.promotion_id if order_extra_obj else None
    promotion_obj = Promotion.objects.filter(id=activity_id).first() if activity_id else None
    if promotion_obj:
        return {
            "activity_id": promotion_obj.id,
            "end_time": promotion_obj.offline_time
        }
    else:
        price = ServiceItemPrice.objects.get(id=groupbuyteam.price_id)
        rule = SKUPriceRule.objects.filter(id=price.selling_rule_id).first()
        activity_id = rule.activity_id if rule else None
        special = Special.objects.filter(id=activity_id).first() if activity_id else None
        if special:
            return {
                "activity_id": special.id,
                "end_time": special.end_time
            }
    return {}