<?php

namespace App\Http\Controllers;

use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class TinymceController
{
    public function upload(Request $request)
    {
        $file = $request->file('file');
       // $dir = trim($request->get('dir'), '/');
        $disk = $this->disk();

        //定死上传目录
        $dir = config("admin.upload.tinymce_directory.image").'/'.date('Ymd');
        if (empty($dir)) {
            die('dir error');
        }
        //定死上传目录 end

        $newName = $this->generateNewName($file);

        $disk->putFileAs($dir, $file, $newName);

        return ['location' => $disk->url("{$dir}/$newName")];
    }

    protected function generateNewName(UploadedFile $file)
    {
        return uniqid(md5($file->getClientOriginalName())).'.'.$file->getClientOriginalExtension();
    }

    /**
     * @return \Illuminate\Contracts\Filesystem\Filesystem|FilesystemAdapter
     */
    protected function disk()
    {
        $disk = request()->get('disk') ?: config('admin.upload.disk');

        return Storage::disk($disk);
    }
}
