#!/usr/bin/env python
# -*- coding: utf-8 -*-

from urllib.parse import urljoin

from django.conf import settings
from django.db.models import Q

from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_dataquery.dict_mixin import to_dict

from talos.models.subscript_article import (
    SubscriptArticle,
    SubCategory,
    SubscriptArticleTag,
    SubscriptArticleCategory,
)
from talos.services.tag import TagService


class SubscriptArticleDB(DataBuilder):

    def getval_tag_ids(self, obj):
        tags = list(SubscriptArticleTag.objects.filter(
            article_id=obj.id, is_online=True).values_list("tag_id", flat=True))

        return tags

    def getval_category_ids(self, obj):
        category_ids = list(SubscriptArticleCategory.objects.filter(
            article_id=obj.id, is_online=True).values_list("category_id", flat=True))

        return category_ids

    def getval_tags_name(self, obj):

        tags = self.getval_tag_ids(obj)
        tag_info_list = TagService.get_tags_by_tag_ids(tags)

        return "、".join([tag.name for tag in tag_info_list])

    def getval_categoy_name(self, obj):

        category_ids = self.getval_category_ids(obj)
        cate_info_list = SubCategory.objects.filter(id__in=category_ids, is_online=True)

        return "、".join([category.name for category in cate_info_list])


@DB
class SubscriptArticleDQ(DataSQLQuery):
    model = SubscriptArticle
    data_model = SubscriptArticleDB

    # def filter_user_id(self, srch_key, srch_val, regex=False):
    #     return Q(user_id=srch_val)

    # def filter_last_modified(self, srch_key, srch_val, regex=False):
    #     return self._qry_time_range(srch_key, srch_val, regex)

    def update(self, updates, **kwargs):

        tag_ids = updates.pop('tag_ids', None)
        if tag_ids is not None:
            tag_ids = list(map(lambda i: int(i), tag_ids))

        category_ids = updates.pop('category_ids', None)
        if category_ids is not None:
            category_ids = list(map(lambda i: int(i), category_ids))

        obj = SubscriptArticle.objects.get(**kwargs)

        update_fields = [
            "name", "title", "url", "image_url", "share_img", "share_content",
            "is_header_article", "ordering", "is_online"
        ]

        to_update = False
        for field in update_fields:
            value = updates.pop(field, None)
            if value is not None:
                to_update = True
                setattr(obj, field, value)

        if to_update:
            obj.save()

        # 更新tag
        if tag_ids is not None:
            tags = list(SubscriptArticleTag.objects.filter(article_id=obj.id).values_list('tag_id', flat=True))

            rm_ids = set(tags) - set(tag_ids)
            if rm_ids:
                SubscriptArticleTag.objects.filter(article_id=obj.id, tag_id__in=rm_ids).update(is_online=False)

            _ids = set(tags) & set(tag_ids)
            if _ids:
                SubscriptArticleTag.objects.filter(article_id=obj.id, tag_id__in=_ids).update(is_online=True)

            new_ids = set(tag_ids) - set(tags)
            ats = [
                SubscriptArticleTag(
                    article_id=obj.id,
                    tag_id=tag_id
                )
                for tag_id in new_ids
            ]
            if ats:
                SubscriptArticleTag.objects.bulk_create(ats)

        # 更新category
        if category_ids is not None:
            cids = list(SubscriptArticleCategory.objects.filter(article_id=obj.id).values_list('category_id', flat=True))

            rm_ids = set(cids) - set(category_ids)
            if rm_ids:
                SubscriptArticleCategory.objects.filter(article_id=obj.id, category_id__in=rm_ids).update(is_online=False)

            _ids = set(cids) & set(category_ids)
            if _ids:
                SubscriptArticleCategory.objects.filter(article_id=obj.id, category_id__in=_ids).update(is_online=True)

            new_ids = set(category_ids) - set(cids)
            acs = [
                SubscriptArticleCategory(
                    article_id=obj.id,
                    category_id=tag_id
                )
                for tag_id in new_ids
            ]
            if acs:
                SubscriptArticleCategory.objects.bulk_create(acs)

        return {'id': obj.id}

    def create(self, **kwargs):

        tag_ids = kwargs.pop('tag_ids', None)
        category_ids = kwargs.pop('category_ids', None)

        obj = SubscriptArticle.objects.create(**kwargs)

        # 更新tag
        ats = [
            SubscriptArticleTag(
                article_id=obj.id,
                tag_id=tag_id
            )
            for tag_id in tag_ids
        ]
        if ats:
            SubscriptArticleTag.objects.bulk_create(ats)

        # 更新category
        acs = [
            SubscriptArticleCategory(
                article_id=obj.id,
                category_id=category_id
            )
            for category_id in category_ids
        ]
        if acs:
            SubscriptArticleCategory.objects.bulk_create(acs)

        return {'id': obj.id}




class SubCategoryDB(DataBuilder):
    pass


@DB
class SubCategoryDQ(DataSQLQuery):
    model = SubCategory
    data_model = SubCategoryDB
