# coding=utf-8

from PIL import Image

from django.db import models
from django.conf import settings
from django.utils import timezone

from utils.file_operation import UploadFile, DeleteFile, DownloadFace

class ImagesManager(models.Manager):

    def employee_addnew(self, user, type, file):
        return self._addnew(user, type, file)

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

        path = ImagesManager.calculatePath(type, user.id)
        modify_size = ImagesManager.canModifySize(type)
        filename = UploadFile(file, path)
        fullname = "%s/%s" % (settings.MEDIA_ROOT, filename)

        try:
            img = Image.open(fullname)
            width, height = img.size
            # 缩略图压缩宽或高最大200
            if modify_size and (width > 200 or height > 200):
                if width > height:
                    size = (200, int(height * 200 / width))
                elif width < height:
                    size = (int(width * 200 / height), 200)
                else:
                    size = (200, 200)
                img = img.resize(size, Image.ANTIALIAS)
                img.save(fullname)
                width, height = img.size
        except:
            pass
        instance = self.model(
            user=user,
            type=type,
            name=file.name,
            picture=filename,
            width=width,
            height=height,
            create_time=timezone.now()
        )
        instance.save()
        return instance

    @staticmethod
    def calculatePath(type, user_id):
        path_map = {
            Images.USEDVEHICLE_FILE: usedvehicle_file,
            Images.USEDVEHICLE_THUMBNAIL: usedvehicle_thumbnail_file,

        }

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

    @staticmethod
    def canModifySize(type):
        modify_size = False
        can_modify_list = [
            Images.USEDVEHICLE_THUMBNAIL
        ]
        if type in can_modify_list:
            modify_size = True

        return modify_size

usedvehicle_file = "usedvehicle/detail/"
usedvehicle_thumbnail_file = "usedvehicle/"

class Images(models.Model):
    USEDVEHICLE_FILE = 1
    USEDVEHICLE_THUMBNAIL = 2
    TYPE_CHOICES = (
        (USEDVEHICLE_FILE, u'二手车图片'),
        (USEDVEHICLE_THUMBNAIL, u'二手车缩略图'),
    )

    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"图片宽度")
    height = models.IntegerField(verbose_name=u"图片高度")
    create_time = models.DateTimeField(verbose_name=u'上传时间', default=timezone.now, editable=False)

    objects = ImagesManager()

    class Meta:
        db_table = 'images'
        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%s' % (settings.SERVER_DOMAIN, settings.MEDIA_URL, self.picture)

    # @staticmethod
    # def downLoadFace(customer, url):
    #     save_path = customer_face_file + str(customer.user.id) + '/'
    #     filename = DownloadFace(url, save_path, 'jpg')
    #     name = filename.split('/')[-1]
    #     fullname = "%s/%s" % (settings.MEDIA_ROOT, filename)
    #     width = None
    #     height = None
    #     try:
    #         img = Image.open(fullname)
    #         width, height = img.size
    #     except:
    #         pass
    #     instance = Images.objects.create(
    #         tenant=customer.tenant, user=customer.user, type=Images.CUSTOMER_FACE, name=name, picture=filename,
    #         width=width, height=height, create_time=timezone.now()
    #     )
    #     instance.save()
    #     return instance
