from django.db import models

# Create your models here.


class Category(models.Model):
    """类别表"""
    cname = models.CharField(max_length=10, verbose_name="类别名称")

    def __str__(self):
        return self.cname


class Goods(models.Model):
    """商品表"""
    gname = models.CharField(max_length=100, verbose_name="商品名称")
    gbesc = models.CharField(max_length=100, verbose_name="商品描述")
    oldprice = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="原价")
    price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="现价")
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    def __str__(self):
        return self.gname

    def get_img_url(self):
        return self.inventory_set.first().color.color_url

    def get_colors(self):
        colors = []
        for inventory in self.inventory_set.all():
            color = inventory.color
            if color not in colors:
                colors.append(color)
        return colors

    def get_sizes(self):
        sizes = []
        for inventory in self.inventory_set.all():
            size = inventory.size
            if size not in sizes:
                sizes.append(size)
        return sizes

    def get_detail_info(self):
        datas = {}

        for detail in self.goodsdetail_set.all():
            # 获取详情名称
            detail_name = detail.get_dname()
            # 判断detail_name是否在字典中存在
            if detail_name not in datas:
                datas[detail_name] = [detail.gdurl]
            else:
                datas[detail_name].append(detail.gdurl)

        return datas


class GoodsDetailName(models.Model):
    """商品详情名称表"""
    gdname = models.CharField(max_length=30, verbose_name="商品详情名称")

    def __str__(self):
        return self.gdname


class GoodsDetail(models.Model):
    """商品详情表"""
    gdurl = models.ImageField(upload_to="")
    goods_detail_name = models.ForeignKey(GoodsDetailName, on_delete=models.CASCADE)
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE)

    def __str__(self):
        return self.goods_detail_name.gdname

    def get_dname(self):
        return self.goods_detail_name.gdname


class Color(models.Model):
    """商品颜色表"""
    color_name = models.CharField(max_length=10, verbose_name="颜色名称")
    color_url = models.ImageField(upload_to="")

    def __str__(self):
        return self.color_name


class Size(models.Model):
    """商品尺寸表"""
    sname = models.CharField(max_length=10, verbose_name="商品尺寸")

    def __str__(self):
        return self.sname


class Inventory(models.Model):
    """库存表"""
    count = models.PositiveIntegerField(verbose_name="库存数量")
    color = models.ForeignKey(Color, on_delete=models.CASCADE)
    size = models.ForeignKey(Size, on_delete=models.CASCADE)
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE)

    def __str__(self):
        return self.count




