package goods

import (
	"pychr/global"
	"pychr/model/goods"
	goodsReq "pychr/model/goods/request"
)

type GoodsShowService struct {
}

// CreateGoodsShow 创建商品记录
// Author [piexlmax](https://github.com/piexlmax)
func (goodsShowService *GoodsShowService) CreateGoodsShow(goodsShow *goods.GoodsShow) (err error) {
	err = global.GVA_DB.Create(goodsShow).Error
	return err
}

// DeleteGoodsShow 删除商品记录
// Author [piexlmax](https://github.com/piexlmax)
func (goodsShowService *GoodsShowService) DeleteGoodsShow(ID string) (err error) {
	err = global.GVA_DB.Delete(&goods.GoodsShow{}, "id = ?", ID).Error
	return err
}

// DeleteGoodsShowByIds 批量删除商品记录
// Author [piexlmax](https://github.com/piexlmax)
func (goodsShowService *GoodsShowService) DeleteGoodsShowByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]goods.GoodsShow{}, "id in ?", IDs).Error
	return err
}

// UpdateGoodsShow 更新商品记录
// Author [piexlmax](https://github.com/piexlmax)
func (goodsShowService *GoodsShowService) UpdateGoodsShow(goodsShow goods.GoodsShow) (err error) {
	err = global.GVA_DB.Save(&goodsShow).Error
	return err
}

// GetGoodsShow 根据ID获取商品记录
// Author [piexlmax](https://github.com/piexlmax)
func (goodsShowService *GoodsShowService) GetGoodsShow(ID string) (goodsShow goods.GoodsShow, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&goodsShow).Error
	return
}

// GetGoodsShowInfoList 分页获取商品记录
// Author [piexlmax](https://github.com/piexlmax)
func (goodsShowService *GoodsShowService) GetGoodsShowInfoList(info goodsReq.GoodsShowSearch) (list []goods.GoodsShow, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&goods.GoodsShow{})
	var goodsShows []goods.GoodsShow
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.LangType != 0 {
		db = db.Where("lang_type = ?", info.LangType)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	if info.Type != 0 {
		db = db.Where("type = ?", info.Type)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&goodsShows).Error
	return goodsShows, total, err
}
