package models

import (
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/utils"
	"errors"
)

/***
*CreateBy:lou
*Date:2020/5/15
*TableName:角色表
**********/

type Roletab struct {
	RoleId         int    `xorm:"not null pk comment('角色ID') VARCHAR(40)" json:"role_id"`
	RoleKey        string   `xorm:"comment('角色代码') VARCHAR(40)" json:"role_key"`
	Rolename       string   `xorm:"comment('角色名') VARCHAR(40)" json:"rolename"`
	RoleSort       int      `xorm:"comment('角色顺序') INT(0)" json:"role_sort"`
	Status         string   `xorm:"comment('状态') VARCHAR(1)" json:"status"`
	Remark         string   `xorm:"comment('备注') VARCHAR(100)" json:"remark"`
	DataScope      string   `xorm:"comment('')  VARCHAR(128)" json:"data_scope"`
	Createtime     string   `xorm:"comment('创建时间') VARCHAR(14)" json:"createtime"`
	Lastmodifytime string   `xorm:"comment('最近一次更新时间') VARCHAR(14)" json:"lastmodifytime"`
	Lastmodify     string   `xorm:"comment('最近一次更新人员') VARCHAR(40)" json:"lastmodify"`
	Params         string   `json:"params" xorm:"-"`
	MenuIds        []int `json:"menuIds" xorm:"-"`
	DeptIds        []string `json:"deptIds" xorm:"-"`
}

type RoleB struct {
	RoleKey        string `json:"role_key"`
	Rolename       string `json:"rolename"`
	RoleSort       int    `json:"role_sort"`
	Status         string `json:"status"`
	Remark         string `json:"remark"`
	DataScope      string `json:"data_scope"`
	Createtime     string `json:"createtime"`
	Lastmodifytime string `json:"lastmodifytime"`
	Lastmodify     string `json:"lastmodify"`
}

func (t *Roletab) TableName() string {
	return "roletab"
}
// 清除string字段的右侧空格
func (t *Roletab) Clipped() {
	utils.TrimStruct(t, *t)
}

type MenuIdList struct {
	MenuId int `json:"menuId"`
}

func (t *Roletab) GetPage(pageSize int, pageIndex int) ([]Roletab, int, error) {
	var doc []Roletab
	e := db.Eloquent.Master()
	table := e.Select("*").Table("roletab").Where("1=1")
	if t.RoleId != 0 {
		table = table.And("role_id = ?", t.RoleId)
	}
	if t.Rolename != "" {
		rolename := "%"+t.Rolename+"%"
		table = table.And("rolename like ?", rolename)
	}
	if !utils.ValueIsEmpty(t.Status) {
		table = table.And("status = ?", t.Status)
	}
	if t.RoleKey != "" {
		table = table.And("role_key = ?", t.RoleKey)
	}

	// 数据权限控制
	//dataPermission := new(DataPermission)
	//dataPermission.UserId = t.DataScope
	//table = dataPermission.GetDataScope("roletab", table)

	if err := table.OrderBy("role_sort").Limit(pageSize, (pageIndex-1)*pageSize).Find(&doc); err != nil {
		return nil, 0, err
	}
	rolecount := new(Roletab)
	count, err := table.Count(rolecount)
	if err != nil {
		return nil, 0, err
	}
	for k,_:=range doc{
		doc[k].Clipped()
	}
	return doc, int(count), nil
}

func (t *Roletab) Get() (SysRole Roletab, err error) {
	e := db.Eloquent.Master()
	table := e.Table("roletab").Where("1=1")
	if t.RoleId != 0 {
		table = table.And("role_id = ?", t.RoleId)
	}
	if t.Rolename != "" {
		table = table.And("rolename = ?", t.Rolename)
	}
	if _,err = table.Get(&SysRole); err != nil {
		return
	}
	return
}

func (t *Roletab) GetList() (SysRole []Roletab, err error) {
	e := db.Eloquent.Master()
	table := e.Table("roletab")
	if t.RoleId != 0 {
		table = table.Where("role_id = ?", t.RoleId)
	}
	if t.Rolename != "" {
		table = table.Where("rolename = ?", t.Rolename)
	}
	if err = table.OrderBy("role_sort").Find(&SysRole); err != nil {
		return
	}
	for k,_:= range SysRole{
		SysRole[k].Clipped()
	}
	return
}

// 获取角色对应的菜单ids
func (t *Roletab) GetRoleMeunId() ([]int, error) {
	menuIds := make([]int, 0)
	menuList := make([]MenuIdList, 0)
	e := db.Eloquent.Master()
	if err := e.Table("role_menu").Select("role_menu.menu_id").Join("LEFT", "menu", "menu.menu_id = role_menu.menu_id").Where("role_menu.role_id = ? ", t.RoleId).And(" role_menu.menu_id not in(select menu.parent_id from role_menu LEFT JOIN menu on menu.menu_id=role_menu.menu_id where role_menu.role_id =? )", t.RoleId).Find(&menuList); err != nil {
		return nil, err
	}
	for i := 0; i < len(menuList); i++ {
		menuIds = append(menuIds, menuList[i].MenuId)
	}
	return menuIds, nil
}

func (t *Roletab) Insert() (id int, err error) {
	e := db.Eloquent.Master()
	role := new(RoleB)
	role.Lastmodify = t.Lastmodify
	role.RoleKey = t.RoleKey
	role.Lastmodifytime = t.Lastmodifytime
	role.Rolename = t.Rolename
	role.Status = t.Status
	role.Remark = t.Remark
	role.Createtime = t.Createtime
	countrole := new(Roletab)
	affw, err := e.Table("roletab").Where("rolename=? or role_key = ?", t.Rolename, t.RoleKey).Count(countrole)
	if err != nil {
		return 0, err
	}
	if affw > 0 {
		return 0, errors.New("角色名称或者角色标识已经存在！")
	}
	_, err = e.Table("roletab").Insert(role)

	result := new(Roletab)
	result.Rolename = t.Rolename
	result.RoleKey = t.RoleKey
	ok, err := e.Table("roletab").Get(result)

	if !ok || err != nil {
		return 0, err
	}
	id = result.RoleId
	return
}

type DeptIdList struct {
	DeptId int `json:"DeptId"`
}

func (t *Roletab) GetRoleDeptId() ([]int, error) {
	deptIds := make([]int, 0)
	deptList := make([]DeptIdList, 0)
	e := db.Eloquent.Master()
	if err := e.Table("role_dept").Select("role_dept.dept_id").Join("LEFT", "dept", "dept.dept_id=role_dept.dept_id").Where("role_id = ? ", t.RoleId).And(" role_dept.dept_id not in(select dept.parent_id from role_dept LEFT JOIN dept on dept.dept_id=role_dept.dept_id where role_id =? )", t.RoleId).Find(&deptList); err != nil {
		return nil, err
	}

	for i := 0; i < len(deptList); i++ {
		deptIds = append(deptIds, deptList[i].DeptId)
	}

	return deptIds, nil
}

//修改
func (t *Roletab) Update(id int) (update Roletab, err error) {
	t.Clipped()
	e := db.Eloquent.Master()
	if _,err = e.Table("roletab").ID(id).Get(&update); err != nil {
		return
	}
	update.Clipped()
	if t.Rolename != "" && t.Rolename != update.Rolename {
		return update, errors.New("角色名称不允许修改！")
	}

	if t.RoleKey != "" && t.RoleKey != update.RoleKey {
		return update, errors.New("角色标识不允许修改！")
	}

	//参数1:是要修改的数据
	uprole := new(RoleB)
	uprole.RoleKey =t.RoleKey
	uprole.Rolename = t.Rolename
	uprole.Lastmodifytime = t.Lastmodifytime
	uprole.Lastmodify=t.Lastmodify
	uprole.Createtime=t.Createtime
	uprole.Remark =t.Remark
	uprole.Status=t.Status
	uprole.RoleSort=t.RoleSort
	uprole.DataScope=t.DataScope

	//参数2:是修改的数据v
	if _, err = e.Table(t.TableName()).Where("role_id =?",id).Update(uprole); err != nil {
		return
	}

	return
}

//批量删除
func (t *Roletab) BatchDelete(id []int) (Result bool, err error) {
	e := db.Eloquent.Master()
	roles_str := utils.IDsToStringIn(id)
	if _, err = e.Table("roletab").Where("role_id in ("+roles_str+")").Delete(&Roletab{}); err != nil {
		return
	}
	Result = true
	return
}
//批量查询
func (t *Roletab) GetRoles(roleIds []int) ([]string, error) {
	e := db.Eloquent.Master()
	role := make([]Roletab,0)
	roleIds_str := utils.IDsToStringIn(roleIds)
	if err := e.Table("roletab").Where("role_id in ("+roleIds_str+")").Find(&role); err != nil {
		return nil,err
	}
	var rolekeys []string
	for _,v:=range role{
		rolekeys = append(rolekeys,v.RoleKey)
	}
	return rolekeys,nil
}
