package models

import (
	"fmt"
	"time"

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

type Role struct {
	Id        int       `orm:"column(id);auto" description:"编号"`
	Pid       int       `orm:"column(pid)" description:"关联的上级组id"`
	Types     int8      `orm:"column(types)" description:"类型【1:角色】【2:角色组】"`
	Name      string    `orm:"column(name);size(30)" description:"角色名称"`
	CompanyId int       `orm:"column(company_id)" description:"表company.id 编号"`
	Descript  string    `orm:"column(descript);size(255)" description:"描述"`
	CreateAt  time.Time `orm:"column(create_at);type(timestamp);auto_now_add" description:"创建时间"`
	DeleteAt  time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
	UpdateAt  time.Time `orm:"column(update_at);type(timestamp)"`
	IsDefault int8      `orm:"column(is_default)" description:"是否是默认项【0:不是默认】【1:是默认】"`
}

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

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

// AddRole insert a new Role into database and returns
// last inserted Id on success.
func AddRole(m *Role) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetRoleById retrieves Role by Id. Returns error if
// Id doesn't exist
func GetRoleById(id int) (v *Role, err error) {
	o := orm.NewOrm()
	v = &Role{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// UpdateRole updates Role by Id and returns error if
// the record to be updated doesn't exist
func UpdateRoleById(m *Role) (err error) {
	o := orm.NewOrm()
	v := Role{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteRole deletes Role by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRole(id int) (err error) {
	o := orm.NewOrm()
	v := Role{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Role{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}