#  coding: utf-8
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.auth.models import User
from django.db import models


class Category(models.Model):
    name = models.CharField(max_length=64, unique=True, verbose_name=u'类别名称')
    ename = models.CharField(max_length=64, unique=True, verbose_name=u'类别标识（唯一）')
    description = models.TextField(max_length=512, blank=True, verbose_name=u'栏目简介')
    parent = models.ForeignKey('self', default=None, blank=True, null=True, verbose_name=u'父级类别')
    sort = models.IntegerField(default=0, verbose_name=u'排序')
    is_show = models.BooleanField(default=True, verbose_name=u'是否显示')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')

    def __unicode__(self):
        if self.parent:
            return '%s-->%s' % (self.parent.name, self.name)
        else:
            return self.name

    def get_blog_num(self):  # 返回类别的博客数
        blog_num = self.blog_set.filter(is_show=True).count()
        return blog_num

    def get_absolute_url(self):
        return '/blogs/{}'.format(self.ename)

    class Meta:
        verbose_name_plural = verbose_name = u'博客类别'
        ordering = ['-sort', '-created_time']


class Blog(models.Model):
    title = models.CharField(max_length=64, verbose_name=u'标题')
    summary = models.TextField(max_length=512, blank=True, verbose_name=u'简介')
    content = RichTextUploadingField(u'内容')
    category = models.ForeignKey(Category, verbose_name=u'所属类别')
    author = models.ForeignKey(User, verbose_name=u'作者')
    featured_image = models.CharField(max_length=512, blank=True, null=True, verbose_name=u'标题图')
    sort = models.IntegerField(default=0, verbose_name=u'排序')
    is_original = models.BooleanField(default=True, verbose_name=u'是否原创')
    is_top = models.BooleanField(default=False, verbose_name=u'是否置顶')
    is_show = models.BooleanField(default=True, verbose_name=u'是否显示')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')

    def __unicode__(self):
        return self.title

    def author_name(self):
        blog_author_name = self.author.username
        if self.author.first_name or self.author.last_name:
            blog_author_name = ''.join((self.author.first_name, self.author.last_name))
        return blog_author_name

    def get_absolute_url(self):
        return '/blog/b-{}'.format(self.id)

    class Meta:
        verbose_name_plural = verbose_name = u'博客'
        ordering = ['-is_top', '-sort','-created_time']
