package dao

import (
	"errors"
	"github.com/gofrs/uuid/v5"
	"gorm.io/gorm"
	"server/global"
)

type SysUser struct {
	global.GVA_MODEL
	UUID        uuid.UUID    `json:"uuid" gorm:"index;comment:用户UUID"`                                                     // 用户UUID
	Username    string       `json:"userName" gorm:"index;comment:用户登录名"`                                                  // 用户登录名
	Password    string       `json:"-"  gorm:"comment:用户登录密码"`                                                             // 用户登录密码
	NickName    string       `json:"nickName" gorm:"default:系统用户;comment:用户昵称"`                                            // 用户昵称
	SideMode    string       `json:"sideMode" gorm:"default:dark;comment:用户侧边主题"`                                          // 用户侧边主题
	HeaderImg   string       `json:"headerImg" gorm:"default:https://qmplusimg.henrongyi.top/gva_header.jpg;comment:用户头像"` // 用户头像
	BaseColor   string       `json:"baseColor" gorm:"default:#fff;comment:基础颜色"`                                           // 基础颜色
	ActiveColor string       `json:"activeColor" gorm:"default:#1890ff;comment:活跃颜色"`                                      // 活跃颜色
	AuthorityId uint         `json:"authorityId" gorm:"default:888;comment:用户角色ID"`                                        // 用户角色ID
	Authority   SysAuthority `json:"authority" gorm:"foreignKey:AuthorityId;references:AuthorityId;comment:用户角色"`
	TunnelIds   []int        `json:"tunnelIds" gorm:"-"`
	Tunnels     []Tunnel     `json:"tunnels" gorm:"many2many:user_tunnel"`
	Phone       string       `json:"phone"  gorm:"comment:用户手机号"`                     // 用户手机号
	Email       string       `json:"email"  gorm:"comment:用户邮箱"`                      // 用户邮箱
	Enable      int          `json:"enable" gorm:"default:1;comment:用户是否被冻结 1正常 2冻结"` //用户是否被冻结 1正常 2冻结
}

func (SysUser) TableName() string {
	return "sys_users"
}

// TODO: 用户查询

// QueryUserByUserName  按用户名查询用户
func QueryUserByUserName(userName string) (SysUser, error) {
	var user SysUser
	err := global.GVA_DB.Where("username =?", userName).First(&user).Error
	return user, err
}

// QueryUserByUserId  按用户Id查询用户
func QueryUserByUserId(id uint) (SysUser, error) {
	var user SysUser
	err := global.GVA_DB.Where("id =?", id).First(&user).Error
	return user, err
}

// QueryUserAndAuthorityByUserName 按用户名查询用户和角色
func QueryUserAndAuthorityByUserName(userName string) (user SysUser, err error) {
	err = global.GVA_DB.Where("username = ?", userName).Preload("Authority").Preload("Tunnels").First(&user).Error
	return
}

// QueryUserInfoList 条件查询用户信息列表
func QueryUserInfoList(limit, offset int) (userList []SysUser, total int64, err error) {
	db := global.GVA_DB.Model(&SysUser{})
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Preload("Authority").Preload("Tunnels").Find(&userList).Error
	return
}

func CreateUserTunnels(user SysUser, ids []int) error {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var tunnels []Tunnel
		err := tx.Model(&Tunnel{}).Where("id in (?)", ids).Find(&tunnels).Error
		if err != nil {
			return err
		}
		err = tx.Model(&user).Debug().Association("Tunnels").Replace(tunnels)
		if err != nil {
			return err
		}
		return nil
	})
}

// QueryUserAuthority 查询用户角色
func QueryUserAuthority(id, authorityId uint) (authority SysAuthority, err error) {
	err = global.GVA_DB.Where("sys_user_id = ? AND sys_authority_authority_id = ?", id, authorityId).First(&authority).Error
	return
}

// GetUserInfoByUUID 获取用户信息 按UUID
func GetUserInfoByUUID(uuid uuid.UUID) (user SysUser, err error) {
	err = global.GVA_DB.Preload("Authority").First(&user, "uuid = ?", uuid).Error
	return user, err
}

// TODO: 用户新增

// CreateUser 创建用户
func (u SysUser) CreateUser() error {
	return global.GVA_DB.Create(&u).Error
}

// TODO: 用户修改

// UpdateUser 修改用户
func (u SysUser) UpdateUser() error {
	return global.GVA_DB.Save(&u).Error
}

// UpdateUserAuthority 修改用户权限
func UpdateUserAuthority(id, authorityId uint) error {
	return global.GVA_DB.Model(&SysUser{}).Where("id = ?", id).Update("authority_id", authorityId).Error
}

// SetUserAuthorities 设置用户权限
func SetUserAuthorities(id uint, authorityId uint) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var user SysUser
		TxErr := tx.Where("id = ?", id).First(&user).Error
		if TxErr != nil {
			global.GVA_LOG.Debug(TxErr.Error())
			return errors.New("查询用户数据失败")
		}
		TxErr = tx.Delete(&[]SysUserAuthority{}, "sys_user_id = ?", id).Error
		if TxErr != nil {
			return TxErr
		}

		useAuthority := SysUserAuthority{
			SysUserId: id, SysAuthorityAuthorityId: authorityId,
		}
		TxErr = tx.Create(&useAuthority).Error
		if TxErr != nil {
			return TxErr
		}
		TxErr = tx.Model(&user).Update("authority_id", authorityId).Error
		if TxErr != nil {
			return TxErr
		}
		// 返回 nil 提交事务
		return nil
	})
}

// SetUserInfo 修改用户信息
func (u SysUser) SetUserInfo() error {
	return global.GVA_DB.Model(&SysUser{}).Updates(&u).Error
}

// SetUserInfoById 修改用户信息 按id
func (u SysUser) SetUserInfoById() error {
	return global.GVA_DB.Model(&SysUser{}).
		Where("id=?", u.ID).
		Updates(&u).Error
}

// TODO: 用户删除

// DeleteUser 删除用户
func DeleteUser(id int) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("id = ?", id).Delete(&SysUser{}).Error; err != nil {
			return err
		}
		if err := tx.Delete(&[]SysUserAuthority{}, "sys_user_id = ?", id).Error; err != nil {
			return err
		}
		return nil
	})
}
