package manage

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

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

func GetInIdListGoods(ids []int) ([]domain.Goods, error) {
	rows, err := configs.Engine.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
		list = append(list, u)
	}
	return list, nil
}

func GetListGoods(goods domain.Goods, pageNum, pageSize int) (vo.BaseListVo, error) {
	rows, err := configs.Engine.Limit(pageSize, (pageNum-1)*pageSize).Desc("id").Rows(&goods)
	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.Goods
		rows.Scan(&u)
		vo.List = append(vo.List, u)
	}
	//查询数量
	count, err := configs.Engine.Count(&goods)
	vo.Total = int(count)
	return vo, nil
}

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

func SetGoods(goodsMap map[string]interface{}, id int) (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(goods domain.Goods) bool {
	i, err := configs.Engine.Where("id = ?", goods.Id).Delete(&goods)
	if err != nil {
		return false
	}
	return i > 0
}
