<?php

namespace App\Http\Controllers;

use App\Models\SiteAlbumFolder;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    public $foldersTree =  [];

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $user = Auth::guard('web')->user();
            $permission = $user->permission;
            if (!$permission) {
                $permission = [];
            } else {
                $permission = json_decode($permission, true);
            }
            // 一次性查询所有文件夹
            $folders = SiteAlbumFolder::all();
            if ($permission) {
                $folders = $folders->filter(function ($folder) use ($permission) {
                    return in_array($folder->id, $permission);
                });
            }
            //dd($permission);

            if (empty($folders->count())) {
                die('未授权，请联系管理员');
            }
            // 构建父子关系树
            $fid = isset($_GET['fid'])? $_GET['fid'] : 0;
            $result = SiteAlbumFolder::buildTree($folders);
            $result = $result->toArray();
            foreach ($result as $key => $item) {
                $checked = false;
                foreach ($item['children'] as $child) {
                    if ($fid == $child['id']) {
                        $checked = true;
                    }
                    foreach ($child['children'] as $subChild) {
                        if ($fid == $subChild['id']) {
                            $checked = true;
                        }
                    }
                }
                if ($fid == $item['id']) {
                    $checked = true;
                }
                $result[$key]['checked'] = $checked;
            }

            //dd($result);
            $this->foldersTree = $result;

            return $next($request);
        });


    }
}
