package manage

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

func GetBackMenuById(id int64) (domain.BackMenu, error) {
	var backMenu domain.BackMenu
	_, err := configs.Engine.Table("back_menu").Where("id = ?", id).Get(&backMenu)
	if err != nil {
		return backMenu, err
	}
	return backMenu, nil
}

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

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

func SetBackMenu(backMenuMap map[string]interface{}, id int64) (domain.BackMenu, bool, error) {
	var backMenu domain.BackMenu
	_, err := configs.Engine.Table("back_menu").Where("id = ?", id).Update(backMenuMap)
	if err != nil {
		return backMenu, false, err
	}
	return backMenu, true, nil
}

func DeleteBackMenu(id int64) bool {
	var backMenu domain.BackMenu
	i, err := configs.Engine.Table("back_menu").Where("id = ?", id).Delete(&backMenu)
	if err != nil {
		return false
	}
	return i > 0
}
