import os

from django.db import models
from django.conf import settings
from PIL import Image

from apps.tenant.models import Tenant
from utils.file_operation import UploadFile, DeleteFile

class OperationHelp(models.Model):
    title = models.CharField(verbose_name=u'标题', max_length=100)
    content = models.TextField(verbose_name=u'内容',blank=True, null=True)
    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)
    tenant = models.ForeignKey(Tenant, verbose_name=u'企业', editable=False, on_delete=models.PROTECT)


    class Meta:
        db_table = 'operation_help'
        ordering = ['-id', 'tenant']
        verbose_name = u'运维帮助'


class OperationHelpUpfile(models.Model):
    operation_help = models.ForeignKey(OperationHelp,verbose_name=u'运维帮助', on_delete=models.PROTECT,null=True)
    file_path = models.CharField(verbose_name=u'路径', max_length=250)
    width = models.IntegerField(verbose_name=u"图片宽度")
    height = models.IntegerField(verbose_name=u"图片高度")
    radio_size = models.FloatField(verbose_name="视频大小", blank=True, default=0)
    tenant = models.ForeignKey(Tenant, verbose_name=u'企业', editable=False, on_delete=models.PROTECT, null=True)

    class Meta:
        db_table = 'operation_help_upfile'
        ordering = ['-id']
        verbose_name = u'运维帮助图片'

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

        path = "operation_help_upfile/"
        filename = UploadFile(file, path, user_id)
        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.file_path = "%s%s" % (settings.MEDIA_URL, filename)
        self.width = width
        self.height = height
        self.save()

    def _add_radio(self, file, user_id):

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

        radio_size = os.path.getsize(fullname)
        self.radio_size = "%.2f" % (radio_size/(1024*1024))
        self.file_path = "%s%s" % (settings.MEDIA_URL, filename)
        self.save()

    def del_file(self):
        file_path = self.file_path
        self.delete()
        DeleteFile(file_path)



