<?php
|
|
namespace app\operations\model\plus\operations;
|
|
use app\common\model\plus\operations\Role as RoleModel;
|
use app\operations\model\plus\operations\UserRole as UserRoleModel;
|
|
/**
|
* 区域代理角色模型
|
*/
|
class Role extends RoleModel
|
{
|
public static function getUsableList()
|
{
|
}
|
|
/**
|
* 获取所有角色列表
|
*/
|
public function getTreeData()
|
{
|
$all = $this->getAll();
|
return $this->formatTreeData($all);
|
}
|
|
/**
|
* 获取所有角色
|
*/
|
private function getAll()
|
{
|
$data = $this->order(['sort' => 'asc', 'create_time' => 'asc'])->select();
|
return $data ? $data->toArray() : [];
|
}
|
|
/**
|
* 获取权限列表
|
*/
|
private function formatTreeData(&$all, $parent_id = 0, $deep = 1)
|
{
|
static $tempTreeArr = [];
|
foreach ($all as $key => $val) {
|
// 根据角色深度处理名称前缀
|
$val['role_name_h1'] = $this->htmlPrefix($deep) . $val['role_name'];
|
$tempTreeArr[] = $val;
|
}
|
return $tempTreeArr;
|
}
|
|
/**
|
* 角色名称 html格式前缀
|
*/
|
private function htmlPrefix($deep)
|
{
|
// 根据角色深度处理名称前缀
|
$prefix = '';
|
if ($deep > 1) {
|
for ($i = 1; $i <= $deep - 1; $i++) {
|
$prefix .= ' ├ ';
|
}
|
$prefix .= ' ';
|
}
|
return $prefix;
|
}
|
|
public function add($data)
|
{
|
$this->startTrans();
|
try {
|
$arr = [
|
'role_name' => $data['role_name'],
|
'sort' => $data['sort'],
|
'area_id' => isset($data['area_id']) ? json_encode($data['area_id']) : null,
|
'app_id' => self::$app_id,
|
'create_time' => time(),
|
'update_time' => time(),
|
'client_id' => 0
|
];
|
$res = self::create($arr);
|
|
// 保存角色权限关系
|
$accessIds = isset($data['access_id']) ? $data['access_id'] : (isset($data['access_ids']) ? $data['access_ids'] : []);
|
if (!empty($accessIds)) {
|
RoleAccess::saveRoleAccess($res['role_id'], $accessIds);
|
}
|
|
// 事务提交
|
$this->commit();
|
return true;
|
} catch (\Exception $e) {
|
$this->error = $e->getMessage();
|
$this->rollback();
|
return false;
|
}
|
}
|
|
/**
|
* 编辑
|
* @param $data
|
* @return bool
|
*/
|
public function edit($data)
|
{
|
$this->startTrans();
|
try {
|
$this->save([
|
'role_name' => $data['role_name'],
|
'area_id' => isset($data['area_id']) ? json_encode($data['area_id']) : null,
|
'sort' => $data['sort'],
|
'update_time' => time()
|
]);
|
|
// 更新角色权限关系
|
$accessIds = isset($data['access_id']) ? $data['access_id'] : (isset($data['access_ids']) ? $data['access_ids'] : []);
|
if (isset($data['access_id']) || isset($data['access_ids'])) {
|
RoleAccess::saveRoleAccess($data['role_id'], $accessIds);
|
}
|
|
// 事务提交
|
$this->commit();
|
return true;
|
} catch (\Exception $e) {
|
$this->error = $e->getMessage();
|
$this->rollback();
|
return false;
|
}
|
}
|
|
public function del($role_id)
|
{
|
//如果角色下有用户,则不能删除
|
if(UserRoleModel::getUserRoleCount($role_id) > 0){
|
$this->error = '当前角色下存在用户,不允许删除';
|
return false;
|
}
|
RoleAccess::where('role_id', '=', $role_id)->delete();
|
return self::destroy(['role_id', '=', $role_id]);
|
}
|
}
|