package manage

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

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

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

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

func SaveGoodsOrder(goodsOrder *domain.GoodsOrder) (domain.GoodsOrder, error) {
	_, err := configs.Engine.Insert(&goodsOrder)
	if err != nil {
		return *goodsOrder, err
	}
	return *goodsOrder, nil
}

func SetGoodsOrder(goodsOrderMap map[string]interface{}, id int) (domain.GoodsOrder, bool, error) {
	var goodsOrder domain.GoodsOrder
	_, err := configs.Engine.Table("goods_order").Where("id = ?", id).Update(goodsOrderMap)
	if err != nil {
		return goodsOrder, false, err
	}
	return goodsOrder, true, nil
}

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