# coding=utf-8
import os

from PIL import Image
from django.conf import settings
from django.db import models
from utils.file_operation import UploadFile, DeleteFile
from django.utils import timezone
from apps.agent.models import Store

class UploadManager(models.Manager):

    # def employee_addnew(self, employee, type, file):
    #     return self._addnew(employee.tenant, employee.user, type, file)
    #
    # def customer_addnew(self, customer, type, file):
    #     return self._addnew(customer.tenant, customer.user, type, file)

    def _addnew(self, tenant, user, type, file):
        width = None
        height = None

        path = UploadManager.calculatePath(type, tenant.id)
        filename = UploadFile(file, path, user.id)
        fullname = "%s%s" % (settings.MEDIA_ROOT, filename)
        size = os.path.getsize(fullname)

        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

        instance = self.model(
            tenant=tenant,
            user=user,
            type=type,
            name=file.name,
            picture="%s%s" % (settings.MEDIA_URL, filename),
            width=width,
            height=height,
            file_size="%.2f" % (float(size)/1024),
        )
        instance.save()
        return instance

    def _addnew_voice(self, tenant, user, type, file, time):

        path = UploadManager.calculatePath(type, tenant.id)
        filename = UploadFile(file, path, user.id)
        fullname = "%s%s" % (settings.MEDIA_ROOT, filename)
        size = os.path.getsize(fullname)

        instance = self.model(
            tenant=tenant,
            user=user,
            type=type,
            name=file.name,
            picture="%s%s" % (settings.MEDIA_URL, filename),
            width=200,
            height=200,
            file_size="%.2f" % (float(size)/1024),
            voice_time=time,
        )
        instance.save()
        return instance

    @staticmethod
    def calculatePath(type, tenant_id):
        path_map = {
            Upload.REPAIR_IMAGE: repair_image,
            Upload.INSPECTION_IMAGE: inspection_image,
            Upload.COMPANY_IMAGE: company_image,
            Upload.REPAIR_VOICE:repair_image,
        }

        return path_map[type] + str(tenant_id)  + '/'


repair_image = "repair/"
inspection_image = "inspection/"
company_image = "company/"

class Upload(models.Model):
    REPAIR_IMAGE = 1
    INSPECTION_IMAGE = 2
    COMPANY_IMAGE = 3
    REPAIR_VOICE = 4
    TYPE_CHOICES = (
        (REPAIR_IMAGE, u'报修图片'),
        (INSPECTION_IMAGE, u'巡检图片'),
        (COMPANY_IMAGE, u'营业执照图片'),
        (REPAIR_VOICE, u'报修语音')
    )

    store = models.ForeignKey(Store, verbose_name=u'门店', on_delete=models.PROTECT)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'操作人', on_delete=models.PROTECT)
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name=u"类型")
    name = models.CharField(verbose_name=u'图片名', max_length=250)
    picture = models.CharField(verbose_name=u'图片路径', max_length=250)
    width = models.IntegerField(verbose_name=u"图片宽度", blank=True, default=0)
    height = models.IntegerField(verbose_name=u"图片高度", blank=True, default=0)
    create_time = models.DateTimeField(verbose_name=u'上传时间', auto_now_add=True, editable=False)
    file_size = models.FloatField(verbose_name="文件大小",blank=True, default=0)

    objects = UploadManager()

    class Meta:
        db_table = 'system_upload'
        verbose_name = u'文件上传'
        ordering = ['-create_time']
        index_together = (
            'type',
            'create_time',
        )
        default_permissions = ()

    def del_images(self):
        picture = self.picture
        self.delete()
        DeleteFile(picture)

    def get_path(self):
        return '%s%s' % (settings.SERVER_DOMAIN, self.picture)


