package manage

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

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

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

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

func SaveGoodsCommodityArea(goodsCommodityArea *domain.GoodsCommodityArea) (domain.GoodsCommodityArea, error) {
	_, err := configs.Engine.Insert(&goodsCommodityArea)
	if err != nil {
		return *goodsCommodityArea, err
	}
	return *goodsCommodityArea, nil
}

func SetGoodsCommodityArea(goodsCommodityAreaMap map[string]interface{}, id int) (domain.GoodsCommodityArea, bool, error) {
	var goodsCommodityArea domain.GoodsCommodityArea
	_, err := configs.Engine.Table("goods_commodity_area").Where("id = ?", id).Update(goodsCommodityAreaMap)
	if err != nil {
		return goodsCommodityArea, false, err
	}
	return goodsCommodityArea, true, nil
}

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