package manage

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

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

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

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

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