package manage

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

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

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

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

func SaveGoodsCouponUser(goodsCouponUser *domain.GoodsCouponUser) (domain.GoodsCouponUser, error) {
	_, err := configs.Engine.Insert(&goodsCouponUser)
	if err != nil {
		return *goodsCouponUser, err
	}
	return *goodsCouponUser, nil
}

func SetGoodsCouponUser(goodsCouponUserMap map[string]interface{}, id int) (domain.GoodsCouponUser, bool, error) {
	var goodsCouponUser domain.GoodsCouponUser
	_, err := configs.Engine.Table("goods_coupon_user").Where("id = ?", id).Update(goodsCouponUserMap)
	if err != nil {
		return goodsCouponUser, false, err
	}
	return goodsCouponUser, true, nil
}

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