package manage

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

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

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

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

func SaveGoodsTopic(goodsTopic *domain.GoodsTopic) (domain.GoodsTopic, error) {
	_, err := configs.Engine.Insert(&goodsTopic)
	if err != nil {
		return *goodsTopic, err
	}
	return *goodsTopic, nil
}

func SetGoodsTopic(goodsTopicMap map[string]interface{}, id int) (domain.GoodsTopic, bool, error) {
	var goodsTopic domain.GoodsTopic
	_, err := configs.Engine.Table("goods_topic").Where("id = ?", id).Update(goodsTopicMap)
	if err != nil {
		return goodsTopic, false, err
	}
	return goodsTopic, true, nil
}

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