package manage

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

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

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

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

func SaveGoodsIntroduction(goodsIntroduction *domain.GoodsIntroduction) (domain.GoodsIntroduction, error) {
	_, err := configs.Engine.Insert(&goodsIntroduction)
	if err != nil {
		return *goodsIntroduction, err
	}
	return *goodsIntroduction, nil
}

func SetGoodsIntroduction(goodsIntroductionMap map[string]interface{}, id int) (domain.GoodsIntroduction, bool, error) {
	var goodsIntroduction domain.GoodsIntroduction
	_, err := configs.Engine.Table("goods_introduction").Where("id = ?", id).Update(goodsIntroductionMap)
	if err != nil {
		return goodsIntroduction, false, err
	}
	return goodsIntroduction, true, nil
}

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