<?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\Permissions;
use Xin\Support\Arr;

class MenuService{

	/**
	 * @title 获取菜单
	 *
	 * @param boolean $is_tree
	 * @return void
	 */
	public function getSystemMenu($is_menu = true, $is_tree = true){
		$order = "sort asc, id desc";
		$map = [];
		if(request()->user['uid'] != env('ADMIN')){
			$map[] = ['name', 'IN', request()->auth()['permission']];
		}
		if($is_menu){
			$map[] = ['type', '<>', 'button'];
			$map[] = ['hidden', '=', 0];
		}
		$list = Permissions::where($map)->order($order)->append(['meta'])->select()
			->each(function($item){
				$item->hidden = (int) $item['hidden'];
				$item->hiddenBreadcrumb = (int) $item['hiddenBreadcrumb'];
			})->toArray();
		if($is_tree){
			$menu = Arr::tree($list, null, 0, ['id'=>'id', 'parent' => 'parent_id', 'child' => 'children']);
	
			return $menu;
		}else{
			return $list;
		}
	}
	/**
	 * @title 创建数据
	 *
	 * @param [type] $data
	 * @return void
	 */
	public function createData($data){
		return Permissions::create($data);
	}
	/**
	 * @title 保存数据
	 *
	 * @param [type] $data
	 * @return void
	 */
	public function saveData($data){
		$menu = Permissions::where('id', $data['id'])->findOrEmpty();
		//移除时间，时间自动系统
		unset($data['create_time']);
		unset($data['update_time']);
		if(!$menu->isEmpty()){
			return $menu->save($data);
		}else{
			throw new \think\Exception("未找到数据！", 0);
		}
	}
	/**
	 * @title 删除菜单
	 *
	 * @param [type] $data
	 * @return void
	 */
	public function deleteMenu($data){
		return Permissions::destroy($data);
	}
}