package models

import (
	_ "gorm.io/driver/mysql"
)

type User struct {
	Model
	Name     string `gorm:"size:50 index:idx_name not null default:''" json:"name"`
	Password string `gorm:"size:50 not null default:''" json:"password"`
	Nickname string `gorm:"size:50 not null default:''" json:"nickname"`
	Avator   string `gorm:"size:255 not null default:''" json:"avator"`
	RoleName string `gorm:"-" json:"role_name"`
	RoleId   string `gorm:"-" json:"role_id"`
	Enabled  uint   `gorm:"size:2 not null default:1" json:"enabled"`
}

func CreateUser(name string, password string, avator string, nickname string, enabled uint) uint {
	user := &User{
		Name:     name,
		Password: password,
		Avator:   avator,
		Nickname: nickname,
		Enabled:  enabled,
	}
	DB.Create(user)
	return user.ID
}

func UpdateUser(id string, name string, password string, avator string, nickname string, enabled uint) {
	user := &User{
		Name:     name,
		Avator:   avator,
		Nickname: nickname,
		Enabled:  enabled,
	}
	if password != "" {
		user.Password = password
	}
	DB.Model(&User{}).Where("id = ?", id).Updates(user)
}
func FindUser(username string) User {
	var user User
	DB.Where("name = ?", username).First(&user)
	return user
}
func FindUserById(id interface{}) User {
	var user User
	DB.Select("user.*,role.name role_name,role.id role_id").Joins("join user_role on user.id=user_role.user_id").Joins("join role on user_role.role_id=role.id").Where("user.id = ?", id).First(&user)
	return user
}
func DeleteUserById(id string) {
	DB.Where("id = ?", id).Delete(User{})
}
func FindUsers() []User {
	var users []User
	DB.Select("users.*,roles.name role_name").Joins("left join user_role on users.id=user_role.user_id").Joins("left join roles on user_role.role_id=roles.id").Order("users.id desc").Find(&users)
	return users
}
func FindUserRole(query interface{}, id interface{}) User {
	var user User
	DB.Select(query).Where("users.id = ?", id).Joins("join user_role on users.id=user_role.user_id").Joins("join roles on user_role.role_id=roles.id").First(&user)
	return user
}
