package manage

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

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

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

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

func SaveManageUser(manageUser *domain.ManageUser) (domain.ManageUser, error) {
	_, err := configs.Engine.Insert(&manageUser)
	if err != nil {
		return *manageUser, err
	}
	return *manageUser, nil
}

func SetManageUser(manageUserMap map[string]interface{}, id int) (domain.ManageUser, bool, error) {
	var manageUser domain.ManageUser
	_, err := configs.Engine.Table("manage_user").Where("id = ?", id).Update(manageUserMap)
	if err != nil {
		return manageUser, false, err
	}
	return manageUser, true, nil
}

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