# -*- coding: UTF-8 -*-

from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB

from api.models import Tag, TagAlert, TagAlertItem
from wiki.models import ItemTag, CollectTag
from gm_types.gaia import *
from gm_types.gaia import TAG_ALERT_TYPE


class TagDB(DataBuilder):
    def getval_tag_type(self, obj):
        return TAG_TYPE.getDesc(obj.tag_type)

    def getval_recommend_type(self, obj):
        return RECOMMEND_TYPE.getDesc(obj.recommend_type)

    def getval_children(self, obj):
        return ', '.join([str(item) for item in obj.children_relations])

    def getval_parents(self, obj):
        return ', '.join([str(item) for item in obj.parents_relations])

    def getval_new_wiki(self, obj):
        item = ItemTag.objects.filter(tag_id=obj.id)
        collect = CollectTag.objects.filter(tag_id=obj.id)
        if item:
            return '{}: {}'.format('百科', item[0].item.name.encode("utf-8"))
        elif collect:
            return '{}: {}'.format('聚合', collect[0].collect.name.encode("utf-8"))
        return ''


@DB
class TagDQ(DataSQLQuery):
    model = Tag
    data_model = TagDB

    def filter_is_new_wiki(self, k, v, regex=False):
        item_tag_ids = ItemTag.objects.all().values_list('tag_id', flat=True)
        collect_tag_ids = CollectTag.objects.all().values_list('tag_id', flat=True)
        q = Q(id__in=list(item_tag_ids)+list(collect_tag_ids))
        if v == '1':
            return q
        return ~q

    def filter_push_tag(self, srch_key, srch_val, regex=False):
        push_tag_ids = [1, 2, 3, 4, 5, 7, 9, 10, 11, 12, 13, 922, 929, 971, 992, 1024, 2054, 2212, 6933, 2214]
        if srch_val == '1':
            return Q(id__in=push_tag_ids)
        return Q()


class TagAlertDB(DataBuilder):
    def getval_alert_type(self, obj):
        return TAG_ALERT_TYPE.getDesc(obj.type)

    def getval_service_tag_name(self, obj):
        return obj.service_tag.name


@DB
class TagAlertDQ(DataSQLQuery):
        model = TagAlert
        data_model = TagAlertDB


class TagAlertItemDB(DataBuilder):
    pass


@DB
class TagAlertItemDQ(DataSQLQuery):
        model = TagAlertItem
        data_model = TagAlertItemDB
