from django.db import models
from utils.exceptions import CustomError
from PIL import Image
from django.conf import settings
from apps.tenant.models import Tenant
from utils.file_operation import UploadFile, DeleteFile

class Poster(models.Model):

    CAROUSEL =1
    POPUP = 2

    LOCATION_CHOICES = (
        (CAROUSEL, u'轮播'),
        (POPUP, u'弹窗'),
    )

    title = models.CharField(verbose_name=u'标题', max_length=100)
    content = models.CharField(verbose_name=u'内容',max_length=500)
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u"创建人", on_delete=models.PROTECT,
                                    editable=False)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    enable = models.BooleanField(verbose_name=u"在用", default=True)
    image = models.CharField(verbose_name=u'图片路径', max_length=250)
    width = models.IntegerField(verbose_name=u"图片宽度")
    height = models.IntegerField(verbose_name=u"图片高度")
    location = models.PositiveSmallIntegerField(choices=LOCATION_CHOICES, verbose_name=u"位置")
    tenant = models.ForeignKey(Tenant, verbose_name=u'租户', editable=False, on_delete=models.PROTECT, null=True)

    class Meta:
        db_table = 'poster'
        ordering = ['-id', 'tenant']
        verbose_name = u'轮播广告'

    def _add_img(self, file):
        width = None
        height = None

        path = "poster/"
        filename = UploadFile(file, path)
        fullname = "%s%s" % (settings.MEDIA_ROOT, filename)

        try:
            img = Image.open(fullname)
            width, height = img.size
            # 缩略图压缩宽或高最大200
            if width > 1440:
                img = img.resize((1440, int((height / width) * 1440)), Image.ANTIALIAS)
                img.save(fullname)
                width, height = img.size
        except:
            pass

        self.image = "%s%s" % (settings.MEDIA_URL, filename)
        self.width = width
        self.height = height
        self.save()

    def del_images(self):
        image = self.image
        # self.delete()
        DeleteFile(image)
