<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace app\services\auth;

use app\model\auth\Roles;
use app\model\auth\PermissionAccess;
use app\model\auth\RolesAccess;
use Xin\Support\Arr;

class RoleService{
	/**
	 * @title 获取角色列表
	 *
	 * @param [type] $request
	 * @param [type] $is_tree
	 * @return void
	 */
	public function getRolesList($request, $is_tree){
		$param = $request->param();
		$map = [];
		if(isset($param['keyword']) && $param['keyword']){
			$map[] = ['title', 'LIKE', '%' . $param['keyword'] . '%'];
		}
		$list = Roles::with(['permissions'])->where($map)->order('sort asc, id desc')->select()->each(function($item){
			$item->data_range = strval($item->data_range);
			$permission_id = [];
			foreach($item->permissions as $val){
				$permission_id[] = $val['id'];
			}
			$item->permission_id = $permission_id;
		});
		if($is_tree){
			return Arr::tree($list->toArray(), null, 0, ['id'=>'id', 'parent' => 'parent_id', 'child' => 'children']);
		}else{
			return $list;
		}
	}
	public function deleteRole($request){
		$id = $request->param('id', 0);
		$parent = Roles::where('parent_id', $id)->findOrEmpty();
		if (!$parent->isEmpty()) {
			throw new \think\Exception("存在子角色，无法删除", 0);
		}
		$role = Roles::find($id);
		// 删除权限
		PermissionAccess::where('role_id', '=', $role_id)->delete();
		// 删除部门关联
		// $role->detachDepartments();
		// 删除用户关联
		RolesAccess::where('role_id', '=', $role_id)->delete();
		// 删除
		$role->delete();
	}
	/**
	 * @title 更新角色权限
	 *
	 * @param [type] $role_id
	 * @param [type] $data
	 * @return void
	 */
	public function updateRolePermission($role_id, $data){
		PermissionAccess::where('role_id', '=', $role_id)->delete();
		$save = [];
		foreach ($data as $permiss) {
			$save[] = ['role_id' => $role_id, 'permission_id' => $permiss];
		}
		(new PermissionAccess())->saveAll($save);
		return true;
	}
	public function updateRoleAuth($request){
		$role_id = $request->param('role_id', '');
		$data_range = $request->param('data_range', '');
		$dashboard = $request->param('dashboard', '');
		$mobile_module = $request->param('mobile_module', '');
		$role = Roles::find($role_id);
		$save = [
			'data_range' => $data_range,
			'dashboard' => $dashboard,
			'mobile_module' => $mobile_module
		];
		return $role->save($save);
	}

	public function updateRole($request){
		$data = $request->param();
		return Roles::update($data);
	}
}