package models

import (
	"errors"
	"log"

	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
)

type Role struct {
	Id         int64  `form:"id"`
	Name       string `orm:"size(32)" form:"name" valid:"Required;MaxSize(32);MinSize(6)"`
	Permission int64  `form:"permission"`
}

func init() {
	orm.RegisterModel(new(Role))
}

func (r *Role) TableName() string {
	return "tb_role"
}

func checkRole(r *Role) (err error) {
	valid := validation.Validation{}
	b, _ := valid.Valid(&r)
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}

func GetRolelist() (roles []orm.Params, count int64) {
	o := orm.NewOrm()
	role := new(Role)
	qs := o.QueryTable(role)
	qs.Values(&roles)
	count, _ = qs.Count()
	return roles, count
}

// 添加权限组
func AddRole(r *Role) (int64, error) {
	if err := checkRole(r); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	role := new(Role)
	role.Name = r.Name
	role.Permission = r.Permission

	id, err := o.Insert(role)
	return id, err
}

// 更新用户
func UpdateRole(r *Role) (int64, error) {
	if err := checkRole(r); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	role := make(orm.Params)
	if len(r.Name) > 0 {
		role["Name"] = r.Name
	}
	if r.Permission != 0 {
		role["Permission"] = r.Permission
	}
	if len(role) == 0 {
		return 0, errors.New("update field is empty")
	}
	var table Role
	num, err := o.QueryTable(table).Filter("Id", r.Id).Update(role)
	return num, err
}

func DelRoleById(Id int64) (int64, error) {
	o := orm.NewOrm()
	status, err := o.Delete(&Role{Id: Id})
	return status, err
}

func GetRoleById(id int64) (role *Role) {
	role = &Role{Id: id}
	o := orm.NewOrm()
	err := o.Read(role, "Id")
	if err != nil {
		return nil
	}
	return role
}

func GetRoleIdByName(name string) int64 {
	role := &Role{Name: name}
	o := orm.NewOrm()
	err := o.Read(role, "Name")
	if err != nil {
		return -1
	}
	return role.Id
}
