package manage

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

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

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

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

func SaveUser(user *domain.User) (domain.User, error) {
	_, err := configs.Engine.Insert(&user)
	if err != nil {
		return *user, err
	}
	return *user, nil
}

func SetUser(userMap map[string]interface{}, id int) (domain.User, bool, error) {
	var user domain.User
	_, err := configs.Engine.Table("user").Where("id = ?", id).Update(userMap)
	if err != nil {
		return user, false, err
	}
	return user, true, nil
}

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