package manage

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

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

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

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

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