<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class UeditorController extends Controller
{
    //

    public function index(Request $request)
    {
        $action = $request->action;
        switch ($action) {
            case 'config':
                $callback = $request->callback;

                $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(public_path("config.json"))), true);

                return  response($callback.'('.json_encode($CONFIG).')');
                break;
            case 'uploadimage':

                if($request->hasFile('upfile') && $request->file('upfile')->isValid()){
                    $path = $request->has('path') ? $request->path.'/' : date('Ym').'/';
                    //获取文件的原文件名 包括扩展名
                    $yuanname= $request->file('upfile')->getClientOriginalName();
                    $size = $request->file('upfile')->getSize();
                    //获取文件的扩展名
                    $kuoname=$request->file('upfile')->getClientOriginalExtension();
                    //获取文件的绝对路径,但是获取到的在本地不能打开
                    $filePath=$request->file('upfile')->getRealPath();
                    //要保存的文件名 时间+扩展名
                    $filename=time() . '_' . uniqid() .'.'.$kuoname;

                    $img = Image::make($filePath);
                    if ($img->getWidth()>720) {
                        $img->resize(720, null, function ($constraint) {
                            $constraint->aspectRatio();
                        });
                        $img->encode('jpg', 90);
                        $data = $img->getEncoded();
                        $imageUrl = Storage::put($path.$filename, $data);
                    } else {
                        $imageUrl = Storage::put($path.$filename, file_get_contents($filePath));
                    }


                    if($imageUrl){
                        return [
                            'state' => 'SUCCESS',
                                'url'   => config('customer.chxq_oss_url').$path.$filename,
                                'title' => $filename,
                                'original'  => $yuanname,
                                'type'  => $kuoname,
                                'size'  => $size
                            ];
                    }else{
                        return $this->response->error('图片上传失败,请重试', 500);
                    }
                }else{
                    return $this->response->error('图片上传失败,请重试', 500);
                }

                break;
        }
    }

}