package manage

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

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

func GetGoodsIntroductionListInId(ids []int64) ([]domain.GoodsIntroduction, error) {
	rows, err := configs.Engine.Table("goods_introduction").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
		rows.Scan(&u)
		list = append(list, u)
	}
	return list, nil
}

func GetGoodsIntroductionList(goodsIntroduction domain.GoodsIntroduction, pageNum, pageSize int) (vo.BaseListVo, error) {
	var arr []domain.GoodsIntroduction
	Count, err := configs.Engine.Table("goods_introduction").Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &goodsIntroduction)
	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 SaveGoodsIntroduction(goodsIntroduction *domain.GoodsIntroduction) (domain.GoodsIntroduction, error) {
	_, err := configs.Engine.Table("goods_introduction").Insert(&goodsIntroduction)
	if err != nil {
		return *goodsIntroduction, err
	}
	return *goodsIntroduction, nil
}

func SetGoodsIntroduction(goodsIntroductionMap map[string]interface{}, id int64) (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(id int64) bool {
	var goodsIntroduction domain.GoodsIntroduction
	i, err := configs.Engine.Table("goods_introduction").Where("id = ?", id).Delete(&goodsIntroduction)
	if err != nil {
		return false
	}
	return i > 0
}
