package manage

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

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

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

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

func SaveGoodsCoupon(goodsCoupon *domain.GoodsCoupon) (domain.GoodsCoupon, error) {
	_, err := configs.Engine.Insert(&goodsCoupon)
	if err != nil {
		return *goodsCoupon, err
	}
	return *goodsCoupon, nil
}

func SetGoodsCoupon(goodsCouponMap map[string]interface{}, id int) (domain.GoodsCoupon, bool, error) {
	var goodsCoupon domain.GoodsCoupon
	_, err := configs.Engine.Table("goods_coupon").Where("id = ?", id).Update(goodsCouponMap)
	if err != nil {
		return goodsCoupon, false, err
	}
	return goodsCoupon, true, nil
}

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