package dao

// Role 角色
type Role struct {
	ID        int64  `gorm:"primary_key" json:"id"`                             //编号
	TenantId  string `gorm:"type:varchar(12);default '000000'" json:"tenantId"` //租户id
	ParentId  int64  `gorm:"type:bigint" json:"parentId"`                       //父主键
	RoleName  string `gorm:"type:varchar(255)" json:"roleName"`                 //角色别名
	Sort      int    `gorm:"type:int" json:"sort"`                              //排序
	RoleAlias string `gorm:"type:varchar(255)" json:"roleAlias"`                //角色别名
	IsDeleted int    `gorm:"type:int" json:"isDeleted"`                         //是否删除
}

func (Role) TableName() string {
	return "role"
}

func (c *Role) Get() error {
	return Db.Debug().Model(&c).Where("id = ?", c.ID).Find(&c).Error
}

func (c *Role) GetRole() error {
	return Db.Debug().Model(&c).Where("id = ? and is_deleted = 0", c.ID).Find(&c).Error
}

func (c Role) GetRoles(offset, limit int) ([]Role, error) {
	var Roles []Role
	db := Db.Debug().Model(&c)
	if c.RoleName != "" {
		db = db.Where("role_name like ?", "%"+c.RoleName+"%")
	}
	if c.RoleAlias != "" {
		db = db.Where("role_alias like ?", "%"+c.RoleAlias+"%")
	}
	if c.TenantId != "" {
		db = db.Where("tenant_id like ?", "%"+c.TenantId+"%")
	}
	err := db.Where("is_deleted = 0").Offset(offset).Limit(limit).Find(&Roles).Error
	return Roles, err
}

func (c *Role) Save() error {
	return Db.Debug().Model(&c).Save(&c).Error
}

func (c *Role) Update() error {
	return Db.Debug().Model(&c).Where(" id = ? ", c.ID).Updates(&c).Error
}

func (c *Role) Remove() error {
	return Db.Debug().Model(&c).Where("id = ?", c.ID).Updates(map[string]interface{}{"is_deleted": c.IsDeleted}).Error
}

func (c *Role) IsExistChild() bool {
	var count int64
	_ = Db.Debug().Model(&c).Where("parent_id = ? and is_deleted = 0", c.ParentId).Count(&count).Error
	return count > 0
}

func (c *Role) UpdatePwd(pwd string) error {
	return Db.Debug().Model(&c).Where(" id = ? ", c.ID).Updates(map[string]interface{}{"password": pwd}).Error
}

func (c *Role) GetAll() ([]Role, error) {
	var Roles []Role
	err := Db.Debug().Model(&c).Where("is_deleted = 0").Find(&Roles).Error
	return Roles, err
}

func (c *Role) UpdateRoles(RoleIds []string, roleIds string) error {
	err := Db.Debug().Model(&c).Where("id in ?", RoleIds).Updates(map[string]interface{}{"role_id": roleIds}).Error
	return err
}