# coding=utf-8

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

from utils.exceptions import CustomError

from apps.images.models import Images
from apps.option.models import Option


class Commodity(models.Model):
    CASH = 1
    POINT = 2
    TYPE_CHOICE = (
        (CASH, u'现金商品'),
        (POINT, u'积分商品')
    )
    TYPE_JSON = [{'id': item[0], 'value': item[1]} for item in TYPE_CHOICE]

    name = models.CharField(verbose_name=u'商品名称', max_length=100)
    category = models.ForeignKey(Option, verbose_name=u'类别', on_delete=models.PROTECT)
    show_image = models.ForeignKey(Images, verbose_name=u'图片', on_delete=models.PROTECT, null=True, blank=True)
    initial_sale_count = models.IntegerField(verbose_name=u'起始销量', default=0)
    total_sales = models.IntegerField(verbose_name=u'实际总销量', default=0, editable=False)
    sort = models.PositiveSmallIntegerField(verbose_name=u'排序', default=0)
    type = models.PositiveSmallIntegerField(verbose_name=u'类型', choices=TYPE_CHOICE, default=CASH)
    price = models.BigIntegerField(verbose_name=u'销售价格', default=0)
    vip_price = models.BigIntegerField(verbose_name=u'会员价格', default=0)
    point_price = models.BigIntegerField(verbose_name=u'积分价格', default=0)
    status = models.PositiveSmallIntegerField(choices=settings.SALES_STATUS_CHOICES, verbose_name=u"状态", default=settings.ONLINE)
    notes = models.CharField(max_length=500, verbose_name=u"备注", null=True, blank=True)
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'创建人', editable=False, on_delete=models.PROTECT)
    create_time = models.DateTimeField(verbose_name=u"创建时间", default=timezone.now, editable=False)
    delete = models.BooleanField(verbose_name=u'删除', default=False, editable=False)

    class Meta:
        db_table = "commodity"
        verbose_name = u'商品信息'
        ordering = ['sort','-id']
        index_together = (
            'name',
            'create_time',
        )
        default_permissions = ()
        permissions = []


class CommodityImage(models.Model):
    DETAILS = 1
    CAROUSEL = 2
    TYPE_CHOICE = (
        (DETAILS, u'详情'),
        (CAROUSEL, u'轮播')
    )

    commodity = models.ForeignKey(Commodity, verbose_name=u'商品', on_delete=models.PROTECT, editable=False)
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICE, default=DETAILS)
    image = models.ForeignKey(Images, verbose_name=u'图片', on_delete=models.PROTECT)

    class Meta:
        db_table = "commodity_image"
        verbose_name = u'商品图片'
        default_permissions = ()
        permissions = []

    @staticmethod
    def getById(id):
        try:
            id = int(id)
        except:
            raise CustomError(u'无效的ID')

        instance = CommodityImage.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的产品图片')
        return instance
