from django.utils import timezone
from gm_types.error import ERROR

from utils.rpc import gen
from .base import BaseService

from talos.models.soft_article import SoftArticleFavor, SoftArticle


class SoftArticleFavorService(BaseService):

    model = SoftArticleFavor

    @classmethod
    def get_soft_article_favord_info_for_user(cls, soft_article_ids, user_id):
        """
        获取用户对软文的已收藏的数据
        :param soft_article_ids:
        :param user_id:
        :return:
        """
        result = dict()
        if not soft_article_ids or not user_id:
            return result

        tfs = list(cls.model.objects.filter(
            softarticle_id__in=soft_article_ids,
            user_id=user_id,
            is_deleted=False
        ).values_list("softarticle_id", flat=True))
        if not tfs:
            return result

        result = {tv: True for tv in tfs}
        return result

    @classmethod
    def create(cls, softarticle_id, user_id):
        """
        新帖子收藏
        :param softarticle_id:
        :param user_id:
        :return:
        """

        tf, _ = cls.model.objects.update_or_create(
            user_id=user_id, softarticle_id=softarticle_id,
            defaults={'is_deleted': False, 'is_read': False}
        )

        return tf

    @classmethod
    def cancel(cls, user_id, softarticle_id):
        """
        取消收藏
        :param user_id:
        :param softarticle_id:
        :return:
        """
        try:
            tf = cls.model.objects.get(user_id=user_id, softarticle_id=softarticle_id)
        except SoftArticleFavor.DoesNotExist:
            return gen(ERROR.TRACTATE_NOT_FOUND)

        if not tf.is_deleted:
            tf.is_deleted = True
            tf.is_read = True
            tf.save()

        return tf

    @classmethod
    def get_unread_favorite_num(cls, user_id):
        soft_article_ids = SoftArticle.objects.filter(user_id=user_id).values_list('id', flat=True)
        return cls.model.objects.filter(softarticle_id__in=soft_article_ids, is_read=False).count()

    @classmethod
    def tractate_favorite_read(cls, user_id):
        soft_article_ids = SoftArticle.objects.filter(user_id=user_id).values_list('id', flat=True)
        cls.model.objects.filter(softarticle_id__in=soft_article_ids).update(is_read=True, update_time=timezone.now())

    @classmethod
    def tractate_favorite_list(cls, user_id, start_num, count):
        """
        获取新版本帖子ID list
        :param user_id:
        :param start_num:
        :param count:
        :return:
        """
        softarticle_ids = list(cls.model.objects.filter(
            user_id=user_id, is_deleted=False
        ).order_by('-id').values_list('softarticle_id', flat=True)[start_num: start_num + count])

        return softarticle_ids
