package manage

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

func GetGoodsById(id int64) (domain.Goods, error) {
	var goods domain.Goods
	_, err := configs.Engine.Table("goods").Where("id = ?", id).Get(&goods)
	if err != nil {
		return goods, err
	}
	return goods, nil
}

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

func GetGoodsList(goods domain.Goods, pageNum, pageSize int) (vo.BaseListVo, error) {
	var arr []domain.Goods
	Count, err := configs.Engine.Table("goods").Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &goods)
	var vo vo.BaseListVo
	if err != nil {
		return vo, err
	}
	if err != nil {
		return vo, err
	}
	vo.PageNum = pageNum
	vo.PageSize = pageSize
	vo.List = make([]any, len(arr))
	for i, v := range arr {
		vo.List[i] = v
	}
	vo.Total = int(Count)
	return vo, nil
}

func SaveGoods(goods *domain.Goods) (domain.Goods, error) {
	_, err := configs.Engine.Table("goods").Insert(&goods)
	if err != nil {
		return *goods, err
	}
	return *goods, nil
}

func SetGoods(goodsMap map[string]interface{}, id int64) (domain.Goods, bool, error) {
	var goods domain.Goods
	_, err := configs.Engine.Table("goods").Where("id = ?", id).Update(goodsMap)
	if err != nil {
		return goods, false, err
	}
	return goods, true, nil
}

func DeleteGoods(id int64) bool {
	var goods domain.Goods
	i, err := configs.Engine.Table("goods").Where("id = ?", id).Delete(&goods)
	if err != nil {
		return false
	}
	return i > 0
}
