#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf import settings
from django.db import models
from django.utils import timezone
import logging
import traceback
from django.utils.functional import cached_property

from gm_serializer import fields
from gm_types.gaia import VIDEO_CODE_STATUS
from gm_types.mimas import (
    TRACTATE_STATUS,
    TRACTATE_PLATFORM,
    TRACTATE_CONTENT_LEVEL,
    SOFT_ARTICLE_TYPE,
    SOFT_ARTICLE_RELATION_TYPE,
    SOFT_ARTICLE_ORDER,
)
from gm_upload import ImgUrlField, IMG_TYPE

from talos.cache.base import soft_article_pv_cache, soft_article_favor_count_cache, soft_article_vote_count_cache


class SoftArticle(models.Model):
    """
    软文（新帖子类型）---医生后台专用  对用户来说（tractate、softarticle）没有区别
    """

    class Meta:
        verbose_name = u'软文章'
        db_table = 'api_doctor_softarticle'
        app_label = 'talos'

    doctor_id = models.CharField(verbose_name="医生id", db_index=True, max_length=64)
    merchant_id = models.CharField(verbose_name="商户id", db_index=True, max_length=64)
    content = models.TextField(verbose_name=u'正文描述', default="")
    title = models.CharField(verbose_name=u'标题', default="", max_length=32)
    is_online = models.BooleanField(verbose_name=u"是否在线", default=True)
    status = models.CharField(verbose_name=u"审核状态", max_length=12,
                              choices=TRACTATE_STATUS, default=TRACTATE_STATUS.UNAUDITED)
    platform = models.CharField(verbose_name=u"数据来源", max_length=12, choices=TRACTATE_PLATFORM)
    content_level = models.CharField(verbose_name=u"内容等级", max_length=12,
                                     choices=TRACTATE_CONTENT_LEVEL, default=TRACTATE_CONTENT_LEVEL.NULL)
    article_type = models.IntegerField(verbose_name=u'帖子类型', choices=SOFT_ARTICLE_TYPE, default=0)

    hera_is_online = models.BooleanField(verbose_name=u"最终是否上下线", default=False)
    create_time = models.DateTimeField(verbose_name="创建时间", default=timezone.now)
    online_time = models.DateTimeField(verbose_name=u'医生操作上下线时间', default=timezone.now)
    show_order = models.IntegerField(verbose_name=u'展示顺序', choices=SOFT_ARTICLE_ORDER, default=SOFT_ARTICLE_ORDER.UNSET)
    last_modified = models.DateTimeField(verbose_name=u'最后修改时间', auto_now=True)
    audit_time = models.DateTimeField(verbose_name=u'最近一次的审核时间', null=True, default=None)

    @property
    def get_tag_list_sort_article(self):
        """
        帖子关联标签
        :return:
        """
        try:
            tag_id_list = list(
                SoftArticleRelation.objects.filter(softarticle_id=self.id, relation_type=1).values_list("relation_id",
                                                                                                        flat=True))
            return tag_id_list
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return []

    @property
    def get_is_video(self):
        """
        判断该帖子是否有视频
        :return:
        """
        try:
            bol = SoftArticleVideo.objects.filter(softarticle_id=self.id,is_online = True)
            if len(bol):
                return True
            else:
                return False
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())

    @property
    def view_amount(self):
        """
        浏览量
        :return:
        """
        return int(soft_article_pv_cache.get(str(self.id)) or 0)

    @property
    def vote_amount(self):
        """
        点赞数
        :return:
        """
        return int(soft_article_vote_count_cache.get(str(self.id)) or 0)

    @cached_property
    def reply_amount(self):
        """
        评论数
        :return:
        """
        try:
            extra = SoftArticleExtra.objects.get(softarticle_id=self.id)
        except SoftArticleExtra.DoesNotExist:
            return 0
        return extra.reply_count

    @property
    def favor_amount(self):
        """
        收藏数
        :return:
        """

        return int(soft_article_favor_count_cache.get(str(self.id)) or 0)


class SoftArticleExtra(models.Model):
    """
    新帖子 数据相关
    """

    class Meta:
        verbose_name = u'新帖子(软文)其他数据表'
        db_table = 'api_doctor_softarticle_extra'
        app_label = 'talos'

    softarticle_id = models.IntegerField(verbose_name="软文id", unique=True)
    reply_count = models.IntegerField(verbose_name="所有评论数", default=0)
    vote_count = models.IntegerField(verbose_name="点赞数", default=0)
    favor_count = models.IntegerField(verbose_name="收藏数", default=0)


class SoftArticleImages(models.Model):
    """
    新帖子(软文)  图片相关
    默认第一张图片为封面图，故未设置 is_cover 字段
    """

    class Meta:
        verbose_name = u'新帖子(软文) 图片相关'
        db_table = 'api_softarticle_images'
        app_label = 'talos'

    softarticle_id = models.IntegerField(verbose_name="软文id", db_index=True)
    image_url = ImgUrlField(img_type=IMG_TYPE.TOPICIMAGE, max_length=300, verbose_name=u'图片地址')
    width = models.IntegerField(verbose_name="图片宽度", default=0)
    height = models.IntegerField(verbose_name="图片高度", default=0)
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)


class SoftArticleVideo(models.Model):
    """
    新帖子(软文)  视频相关
    """

    class Meta:
        verbose_name = u'新帖子(软文) 视频相关'
        db_table = 'api_doctor_softarticle_video'
        app_label = 'talos'

    softarticle_id = models.IntegerField(verbose_name="软文id", db_index=True)
    video_cover_url = models.CharField(max_length=300, verbose_name="视频封面图地址", default="")
    width = models.IntegerField(verbose_name="视频封面图片宽度", default=0)
    height = models.IntegerField(verbose_name="视频封面图片高度", default=0)
    upload_img_cover = ImgUrlField(img_type=IMG_TYPE.TOPICIMAGE, max_length=300, verbose_name=u'上传的列表图片地址')
    raw_video_url = models.CharField(max_length=128, verbose_name=u"视频地址")
    water_video_url = models.CharField(max_length=128, verbose_name=u"带图片水印的视频地址", default="")
    persistent_id = models.CharField(max_length=128, verbose_name=u'七牛视频处理id', default="")
    persistent_status = models.IntegerField(verbose_name=u"七牛状态",
                                            choices=VIDEO_CODE_STATUS, default=VIDEO_CODE_STATUS.NOSTART)
    is_online = models.BooleanField(verbose_name=u"是否在线", default=True)
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)

    @classmethod
    def cleaned_video_url(cls, video_url):
        return video_url.replace(settings.VIDEO_HOST, '')


class SoftArticleRelation(models.Model):
    """
    医生后台的帖子(软文) 关联项
    """

    class Meta:
        verbose_name = u'医生新帖子(软文) 视频相关: Tag 美购 日记'
        db_table = 'api_doctor_softarticle_relation'
        app_label = 'talos'

    softarticle_id = models.IntegerField(verbose_name="软文id")
    relation_id = models.IntegerField(verbose_name="关联ID")
    relation_type = models.IntegerField(verbose_name="关联类型", choices=SOFT_ARTICLE_RELATION_TYPE)
