<?php

namespace App\Http\Controllers\Admin;

use App\Models\BaseAttachmentModel;
use App\Models\ClassModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\Uploader;

class UploadController extends Controller
{
    public function ueditorUpload(Request $request)
    {
        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(url('/plugins/ueditor/config.json'))), true);
        $action = $_GET['action'];
        switch ($action) {
            case 'config':
                $result =  json_encode($CONFIG);
                break;

            /* 上传图片 */
            case 'uploadimage':
                $config = array(
                    "pathFormat" => $CONFIG['imagePathFormat'],
                    "maxSize" => $CONFIG['imageMaxSize'],
                    "allowFiles" => $CONFIG['imageAllowFiles']
                );
                $fieldName = $CONFIG['imageFieldName'];
                $up = new Uploader($fieldName, $config);
                $fileInfo = $up->getFileInfo();
                if($fileInfo['state'] == 'SUCCESS') {
                    BaseAttachmentModel::create([
                        'path' => $fileInfo['url'],
                        'name' => $fileInfo['title'],
//                        'type' => $fileInfo['type'],
                        'class' => 'ueditor',
                        'size' => $fileInfo['size'],
                    ]);
                    ClassModel::firstOrCreate(['class' => 'ueditor']);
                }
                return json_encode($up->getFileInfo());
            /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':


                /* 列出图片 */
            case 'listimage':

                /* 列出文件 */
            case 'listfile':


                /* 抓取远程文件 */
            case 'catchimage':


            default:
                $result = json_encode(array(
                    'state'=> '请求地址出错'
                ));
                break;
        }
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                return htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                return json_encode(array(
                    'state'=> 'callback参数不合法'
                ));
            }
        } else {
            return $result;
        }
    }
}
