<?php
namespace App\Services\Auth;

use App\Models\Auth\Permissions;

class AuthService{

	/**
	 * @title 用户登录
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function login(){
		$credentials = request(['username', 'password']);

		if (! $token = auth()->attempt($credentials)) {
			abort(0, 'Unauthorized');
		}
		$user = auth()->user();
		$user['token'] = $token;
		return $user;
	}

	/**
	 * @title 获取已授权菜单
	 *
	 * @return void
	 */
	public function getAuthMenu(){
		$order = "sort asc, id desc";
		$map = [];
		if(auth()->user()['uid'] != env('ADMIN_ROOT')){
			$map[] = ['name', 'IN', auth()->user()['permission']];
		}
		$map[] = ['type', '<>', 'button'];
		$list = Permissions::where($map)->orderBy('sort', 'asc')->orderBy('id', 'desc')->get();
		return (new \App\Support\Tree())->listToTree($list->toArray(), 'id', 'parent_id', 'children');
	}

	/**
	 * @title 获取已授权菜单
	 *
	 * @return void
	 */
	public function getAuthPermissions(){
		$map = [];
		if(auth()->user()['uid'] != env('ADMIN_ROOT')){
			$map[] = ['name', 'IN', request()->auth()['permission']];
		}
		$list = Permissions::where($map)->get();
		$data = [];
		foreach($list as $item){
			$data[] = $item['name'];
		};
		return $data;
	}
}
