# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement

import json
from django.db.models import Q, F

from gm_dataquery.db import DB
from gm_dataquery.dataquery import DataSQLQuery, DataBuilder
from gm_types.gaia import AGILE_TAG_TYPE, AGILE_TAG_RECOMMEND_TYPE

from agile.models.agile_tag import (
    AgileTag,
    AgileTagType,
    AgileTagMapping,
    AgileTagRecommendType,
    AgileTagHeraRecommend,
)
from polymer.models import AgileTagRelationPolymer
from api.models.tag import Tag


class AgileTagDB(DataBuilder):
    def getval_tag_type(self, obj):
        _types = list(AgileTagType.objects.filter(
            agile_tag_id=obj.id, is_online=True).values_list('agile_tag_type', flat=True))
        if not _types:
            return ''
        tag_types = [AGILE_TAG_TYPE.getDesc(key=agile_type) for agile_type in _types]
        tag_types = '; '.join(tag_types)
        return tag_types

    def getval_tag_map(self, obj):
        old_tag_ids = list(AgileTagMapping.objects.filter(
            agile_tag_id=obj.id, is_online=True).values_list('old_tag_id', flat=True))
        old_tags = list(Tag.objects.filter(id__in=old_tag_ids).values_list('name', flat=True))
        return old_tags if old_tags else '-'

    def getval_agile_tag_has_polymer(self, obj):
        return AgileTagRelationPolymer.objects.filter(
            is_online=True,
            agile_tag_id=obj.id
        ).exist()


@DB
class AgileTagDQ(DataSQLQuery):
    model = AgileTag
    data_model = AgileTagDB

    def filter_tag_type(self, srch_key, srch_val, regex=False):
        if srch_val:
            _ids = list(AgileTagType.objects.filter(
                is_online=True,
                agile_tag_type=int(srch_val)
            ).values_list("agile_tag_id", flat=True))
            return Q(id__in=_ids)
        return Q()

    def filter_style(self, srch_key, srch_val, regex=False):
        return Q(style=srch_val)

    def filter_agile_tag_has_polymer(self, srch_key, srch_val, regex=False):
        _ids = list(AgileTagRelationPolymer.objects.filter(
            is_online=True
        ).values_list("agile_tag_id", flat=True))

        if srch_val == "1":
            return Q(pk__in=_ids)
        elif srch_val == "0":
            return ~Q(pk__in=_ids)
        else:
            return Q()

    def filter_agile_tag_recommend_types(self, srch_key, srch_val, regex=False):
        if srch_val:
            _ids = list(AgileTagRecommendType.objects.filter(
                is_online=True,
                agile_tag_type__in=srch_val
            ).values_list("agile_tag_id", flat=True))
            return Q(id__in=_ids)
        return Q()

    def create(self, **kwargs):
        #重写即可
        pass

    def update(self, updates, **kwargs):
        # 重写即可
        pass


class AgileTagTypeDB(DataBuilder):
    pass


@DB
class AgileTagTypeDQ(DataSQLQuery):
    model = AgileTagType
    data_model = AgileTagTypeDB


class AgileTagHeraRecommendDB(DataBuilder):

    def getval_agile_tag_ids(self, obj):
        _tag_ids = obj.agile_tag_sort_ids
        tag_id_list = []
        if _tag_ids:
            tag_id_list = json.loads(_tag_ids)
        return tag_id_list

    def getval_agile_tags_name(self, obj):
        agile_tags_name = ""

        agile_tag_ids = obj.agile_tag_sort_ids
        if agile_tag_ids:
            _sortd_id_list = json.loads(agile_tag_ids)
            agile_tag_list = AgileTag.objects.filter(is_online=True, pk__in=_sortd_id_list).values("id", "name")
            _names_list = (tag["name"] for tag in sorted(agile_tag_list, key=lambda item: _sortd_id_list.index(item["id"])))
            agile_tags_name = ";".join(_names_list)

        return agile_tags_name


@DB
class AgileTagHeraRecommendDQ(DataSQLQuery):
    model = AgileTagHeraRecommend
    data_model = AgileTagHeraRecommendDB

    def create(self, **kwargs):
        _tag_ids = kwargs.pop("agile_tag_ids", [])
        kwargs["agile_tag_sort_ids"] = json.dumps(_tag_ids) if _tag_ids else ""
        return super(AgileTagHeraRecommendDQ.sqlquery, self).create(**kwargs)

    def update(self, updates, **kwargs):
        if "agile_tag_ids" in updates:
            _tag_ids = updates.pop("agile_tag_ids", [])
            updates["agile_tag_sort_ids"] = json.dumps(_tag_ids) if _tag_ids else ""

        return super(AgileTagHeraRecommendDQ.sqlquery, self).update(updates, **kwargs)
