package service

import (
	"errors"
	"gorm.io/gorm"
	gdb "wireguard-ui/global/client"
	"wireguard-ui/global/constant"
	"wireguard-ui/http/param"
	"wireguard-ui/http/vo"
	"wireguard-ui/model"
	"wireguard-ui/utils"
)

type user struct {
	*gorm.DB
}

func User() user {
	return user{
		gdb.DB,
	}
}

// CreateUser
// @description: 创建用户
// @receiver s
// @param user
// @return err
func (s user) CreateUser(user *model.User) (err error) {
	// 更新
	if user.Id != "" {
		updates := map[string]any{
			"nickname": user.Nickname,
			"avatar":   user.Avatar,
			"contact":  user.Contact,
			"is_admin": user.IsAdmin,
			"status":   user.Status,
		}

		return s.Model(&model.User{}).Where("id = ?", user.Id).Updates(&updates).Error
	}

	// 判断账号是否已经存在
	if _, err = s.GetUserByAccount(user.Account); err == nil {
		return errors.New("账号已经存在，请勿重复创建！")
	}

	defaultPassword := utils.Password().GenerateHashPassword("admin123")
	if user.Password == "" { // 没有密码给一个默认密码
		user.Password = defaultPassword
	} else {
		user.Password = utils.Password().GenerateHashPassword(user.Password)
	}

	// 没有头像就生成一个头像
	if user.Avatar == "" {
		user.Avatar, _ = utils.Avatar().GenerateAvatar(true)
	}

	// 创建
	return s.Create(&user).Error
}

// Delete
// @description: 删除用户
// @receiver s
// @param id
// @return error
func (s user) Delete(id string) error {
	return s.Model(&model.User{}).Where("id = ?", id).Delete(&model.User{}).Error
}

// List
// @description: 用户列表
// @receiver s
// @param p
// @return data
// @return count
// @return err
func (s user) List(p param.Page) (data []vo.UserItem, count int64, err error) {
	if err = s.Model(&model.User{}).
		Scopes(Paginate(p.Current, p.Size)).
		Order("created_at DESC").
		Find(&data).
		Offset(-1).Limit(-1).
		Count(&count).Error; err != nil {
		return
	}

	return
}

// GetUserByAccount
// @description: 根据账户获取用户信息
// @receiver s
// @param id
// @return data
// @return err
func (s user) GetUserByAccount(account string) (data vo.User, err error) {
	err = s.Model(&model.User{}).Where("account = ?", account).Take(&data).Error
	return
}

// GetUserById
// @description: 根据id获取用户信息
// @receiver s
// @param id
// @return data
// @return err
func (s user) GetUserById(id string) (data vo.User, err error) {
	err = s.Model(&model.User{}).Where("id = ?", id).Take(&data).Error
	return
}

// Status
// @description: 修改用户状态
// @receiver s
// @param id
// @return error
func (s user) Status(id string, state constant.Status) error {
	return s.Model(&model.User{}).Where("id = ?", id).Update("status", state).Error
}

// ChangePassword
// @description: 修改密码
// @receiver s
// @param id
// @param password
// @return error
func (s user) ChangePassword(id, password string) error {
	return s.Model(&model.User{}).Where("id = ?", id).Update("password", utils.Password().GenerateHashPassword(password)).Error
}
