package manage

import (
	"demo/configs"
	"demo/data/domain"
	"demo/data/domain/vo"
)

func GetByIdGoodsSku(id int) (domain.GoodsSku, error) {
	var goodsSku domain.GoodsSku
	_, err := configs.Engine.Where("id = ?", id).Get(&goodsSku)
	if err != nil {
		return goodsSku, err
	}
	return goodsSku, nil
}

func GetInIdListGoodsSku(ids []int) ([]domain.GoodsSku, error) {
	rows, err := configs.Engine.In("id", ids).Rows(&domain.GoodsSku{})
	if err != nil {
		return make([]domain.GoodsSku, 0), err
	}
	defer rows.Close()
	var list []domain.GoodsSku
	for rows.Next() {
		var u domain.GoodsSku
		list = append(list, u)
	}
	return list, nil
}

func GetListGoodsSku(goodsSku domain.GoodsSku, pageNum, pageSize int) (vo.BaseListVo, error) {
	rows, err := configs.Engine.Limit(pageSize, (pageNum-1)*pageSize).Desc("id").Rows(&goodsSku)
	var vo vo.BaseListVo
	if err != nil {
		return vo, err
	}
	vo.PageNum = pageNum
	vo.PageSize = pageSize
	vo.List = make([]any, 0)
	for rows.Next() {
		var u domain.GoodsSku
		rows.Scan(&u)
		vo.List = append(vo.List, u)
	}
	//查询数量
	count, err := configs.Engine.Count(&goodsSku)
	vo.Total = int(count)
	return vo, nil
}

func SaveGoodsSku(goodsSku *domain.GoodsSku) (domain.GoodsSku, error) {
	_, err := configs.Engine.Insert(&goodsSku)
	if err != nil {
		return *goodsSku, err
	}
	return *goodsSku, nil
}

func SetGoodsSku(goodsSkuMap map[string]interface{}, id int) (domain.GoodsSku, bool, error) {
	var goodsSku domain.GoodsSku
	_, err := configs.Engine.Table("goods_sku").Where("id = ?", id).Update(goodsSkuMap)
	if err != nil {
		return goodsSku, false, err
	}
	return goodsSku, true, nil
}

func DeleteGoodsSku(goodsSku domain.GoodsSku) bool {
	i, err := configs.Engine.Where("id = ?", goodsSku.Id).Delete(&goodsSku)
	if err != nil {
		return false
	}
	return i > 0
}
