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

use Modules\Auth\Models\Permission;
use Modules\Auth\Models\Admin;
use App\Support\Tree;

class MenuService {

	/**
	 * @title 获取权限节点列表
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getDataList($request) {
		$map = [];

		if ($request->filled('title')) {
			$map[] = ['title', 'like', '%' . $request->input('title') . '%'];
		}
		if ($request->filled('name')) {
			$map[] = ['name', 'like', '%' . $request->input('name') . '%'];
		}
		if ($request->filled('pid')) {
			$map[] = ['parent_id', '=', $request->input('pid')];
		}

		$query = Permission::where($map)->orderBy('sort', 'asc')->orderBy('id', 'desc');


		if($request->filled('is_tree') && $request->filled('is_tree') == 1){
			$query = $query->get()->toArray();
			$tree = new Tree();
			$data = $tree->list_to_tree($query, 0, 'id', 'parent_id');
		}else{
			$data = [
				'total' => $query->count(),
				'page' => $request->input('page', 1),
				'data' => $query->offset($request->input('offset', 0))->limit($request->input('limit', 10))->get(),
			];
		}
		return $data;
	}

	/**
	 * @title 获取我的权限节点
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getMyMenuList($request){
		$map = [];
		$data = [];
		$uid = auth('admin')->user()['uid'];

		$tree = new Tree();
		if($uid != env('ADMIN_ID', 1)){
			$map[] = ['uid', '=', $uid];

			$admin = Admin::with(['roles'])->where($map)->first();
			$permission = [];
			$menu = [];
			foreach ($admin->roles as $key => $role) {
				$menu = array_merge($menu, $role->permissions->append(['meta'])->toArray());
				$permission = array_merge($permission, $role->permissions->pluck('name')->toArray());
			}
			$data = [
				'menu' => $tree->list_to_tree($menu, 0, 'id', 'parent_id'),
				'permissions' => $permission
			];
		}else{
			$query = Permission::where($map)->orderBy('sort', 'asc');

			$data = [
				'menu' => $tree->list_to_tree($query->where('type', '=', 'menu')->get()->append(['meta'])->toArray(), 0, 'id', 'parent_id'),
				'permissions' => $query->pluck('name')
			];
		}

		return $data;
	}

	/**
	 * @title 添加权限节点
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function create($request) {
		$request->validate([
			'title' => 'required|unique:auth_permissions',
			'name' => 'required|unique:auth_permissions',
		]);
		$data = $request->all();
		$data['status'] = 1;

		return Permission::create($data);
	}

	/**
	 * @title 修改权限节点
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function update($request) {
		try {
			$permission = Permission::findOrFail($request->input('id'));
		} catch (\Throwable $th) {
			throw new \Exception("权限节点不存在！", 1);
		}

		$data = $request->all();
		foreach ($data as $key => $value) {
			if (in_array($key, ['affix', 'color', 'component', 'fullpage', 'hidden', 'hiddenBreadcrumb', 'icon', 'name', 'parent_id', 'redirect', 'sort', 'title', 'type', 'path', 'status'])) {
				$permission->$key = $value;
			}
		}

		$permission->save();
		return $permission;
	}

	/**
	 * @title 删除权限节点
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function delete($request) {
		if($request->filled('id')){
			try {
				$permission = Permission::findOrFail($request->input('id'));
			} catch (\Throwable $th) {
				throw new \Exception("权限节点不存在！", 1);
			}

			$permission->roles()->detach();
			$permission->delete();
		}
		if($request->filled('ids')){
			try {
				$permission = Permission::whereIn('id', $request->input('ids'));
				foreach ($permission->get() as $item) {
					$item->roles()->detach();
				}
				$permission->delete();
			} catch (\Throwable $th) {
				throw new \Exception($th->getMessage(), 1);
			}
		}

		return $permission;
	}

	/**
	 * @title 批量导入
	 *
	 * @param [array] $data
	 * @return void
	 */
	public function importMenu($data, $parent_id = 0){
		foreach ($data as $key => $value) {
			$save = [
				'title' => $value['title'],
				'name' => $value['name'],
				'path' => $value['path'],
				'component' => $value['component'],
				'type' => $value['type'],
				'affix' => isset($value['affix']) ? $value['affix'] : 0,
				'parent_id' => $parent_id,
				'status' => 1,
				'sort' => isset($value['sort']) ? $value['sort'] : $key,
				'icon' => isset($value['icon']) ? $value['icon'] : '',
				'hidden' => isset($value['hidden']) ? $value['hidden'] : 0,
				'created_at' => date('Y-m-d H:i:s'),
				'updated_at' => date('Y-m-d H:i:s'),
			];
			$res = Permission::insertGetId($save);
			if (isset($value['children']) && !empty($value['children'])) {
				$this->importMenu($value['children'], $res);
			}
		}
	}
}
