<?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\Users;
use app\model\auth\Permissions;
use Xin\Support\Arr;
use think\facade\Env;

class AuthService{

	/**
	 * @title 用户登录
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function login($request){
		$params = $request->post();
		$map = [];
		foreach($params as $field => $value){
			if(in_array($field, ['username', 'email', 'mobile']) && $field != 'password'){
				$map[$field] = $value;
			}
		}
		$user = Users::where($map)->field(['uid','username', 'password', 'email', 'avatar', 'department_id', 'status'])->findOrEmpty();
		if (!$user->isEmpty()) {
			if(!password_verify($params['password'], $user->password)){
				throw new \think\Exception('密码不正确！', 100002);
			}
			
			if($user->status != 1){
				throw new \think\Exception('当前用户不可用', 100003);
			}
			return $user->append(['token']);
		}else{
			throw new \think\Exception('当前用户不存在', 100001);
		}
	}

	/**
	 * @title 获取已授权菜单
	 *
	 * @return void
	 */
	public function getAuthMenu(){
		$order = "sort asc, id desc";
		$map = [];
		if(request()->user['uid'] != Env::get('ADMIN')){
			$map[] = ['name', 'IN', request()->auth()['permission']];
		}
		$map[] = ['type', '<>', 'button'];
		$list = Permissions::where($map)->order($order)->append(['meta'])->select()
			->each(function($item){
				$item->hidden = (int) $item['hidden'];
				$item->hiddenBreadcrumb = (int) $item['hiddenBreadcrumb'];
			})->toArray();

		return Arr::tree($list, null, 0, ['id'=>'id', 'parent' => 'parent_id', 'child' => 'children']);
	}

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