package dao

import "server/global"

type Commodity struct {
	global.GVA_MODEL
	Name           string         `json:"name" form:"name" gorm:"comment:商品名称"`
	SupplierId     int            `json:"supplierId" form:"supplierId" gorm:"comment:商品id"`
	Supplier       Supplier       `json:"supplier" form:"supplier" gorm:"foreignKey:SupplierId;references:id;"`
	Genre          int            `json:"genre" form:"genre" gorm:"comment:商品类型id"`
	CommodityGenre CommodityGenre `json:"commodityGenre" form:"commodityGenre" gorm:"foreignKey:Genre;references:id;"`
	UnitPrice      float64        `json:"unitPrice" form:"unitPrice" gorm:"comment:单价"`
	Remark         string         `json:"remark" form:"remark" gorm:"comment:备注"`
}

func (Commodity) TableName() string {
	return "commodity"
}

func QueryAllCommodity() (commodities []Commodity, err error) {
	err = global.GVA_DB.Preload("Supplier").Preload("CommodityGenre").Find(&commodities).Error
	return commodities, err
}

func QueryCommodityList(limit, offset int) (commodities []Commodity, total int64, err error) {
	// 创建db
	db := global.GVA_DB.Model(&Commodity{})
	// 如果有条件搜索 下方会自动创建搜索语句

	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Order("id desc").Limit(limit).Offset(offset).Preload("Supplier").Preload("CommodityGenre").Find(&commodities).Error
	return commodities, total, err
}

func QueryCommodityByGenre(genre int) (commodities []Commodity, err error) {
	err = global.GVA_DB.Where("genre =?", genre).Preload("Supplier").Preload("CommodityGenre").Find(&commodities).Error
	return commodities, err
}

func (c Commodity) CreateCommodity() error {
	return global.GVA_DB.Create(&c).Error
}

func (c Commodity) UpdateCommodity() error {
	return global.GVA_DB.Select("*").Omit("created_at").Where("id = ?", c.ID).Updates(&c).Error
}

func (c Commodity) DeleteCommodity() error {
	return global.GVA_DB.Unscoped().Delete(&c).Error
}
