<?php

namespace app\controller\manager;

use app\exception\RepositoryException;
use app\service\Image;
use app\model\{System, File};
use app\validate\Upload as VUpload;
use think\facade\{Filesystem, Config, Lang};
use think\Image as TImage;
use app\controller\BaseController;

class Upload extends BaseController
{
    protected $noNeedLogin = ['video', 'file', 'image', 'wangImage'];
    private $isCompress = true;
    private $validate;
    private $uploadPath;
    private $videoUploadPath;
    private $uploadPathIsWritable = 0;
    private $videoUploadPathIsWritable = 0;
    private $DIRECTORY_SEPARATOR = "/";
    public function initialize()
    {
        $system = System::getSystem();
        if (!empty($system)) {
            $this->isCompress = $system['compress'] ?? true;
        }
        $this->validate        = new VUpload();
        $this->uploadPath      = Config::get('filesystem.disks.local.url');
        $this->videoUploadPath = Config::get('filesystem.disks.video.url');

        if (!is_writable(app()->getRootPath().'public'.$this->uploadPath)) {
            mkdir(app()->getRootPath().'public'.$this->uploadPath, 0777, true);
        }
        $this->uploadPathIsWritable = 1;

        if (!is_writable(app()->getRootPath().'public'.$this->videoUploadPath)) {
            mkdir(app()->getRootPath().'public'.$this->videoUploadPath, 0777,true);
        }
        $this->videoUploadPathIsWritable = 1;
        $this->DIRECTORY_SEPARATOR = DIRECTORY_SEPARATOR == "\\" ? "/" : DIRECTORY_SEPARATOR;
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", '-1');
        set_time_limit(0);
    }

    //视频上传
    public function video()
    {
        $video = request()->file('video_video');
        try {
            if ($this->validate->checkVideo($video)) {
                if (!$this->videoUploadPathIsWritable) {
                    throw new \Exception('上传文件夹需要写入权限');
                }

                $md5 = $video->md5();//文件md5

                $path    = request()->param('path/s', '');//指定路径 基于public下  若为空则默认
                $hasPath = !empty($path);

                // 去除以/storage/开头的部分  如/storage/20210808/test => 20210808/test
                $path     = ltrim(trim($path, $this->DIRECTORY_SEPARATOR), \app\model\Attachment::ROOT_NAME.$this->DIRECTORY_SEPARATOR);
                $datePath = $hasPath ? $path : 'videos'.$this->DIRECTORY_SEPARATOR.date('Ym');//自定义目录
                $src      = Filesystem::putFile($datePath, $video, 'uniqid');

                $src = $this->uploadPath.'/'.$src;
                $return['src'] = $src;
                File::add($video, $src, $md5, 'video');    //加入上传文件表
                return $this->json(0, 'ok', $return);
            } else {

                $errorMsg = Lang::get($this->validate->getError());
                return $this->json(1, $errorMsg);
            }
        } catch (RepositoryException $e) {
            return $this->json(1, $e->getMessage());
        }
    }

    //文件上传(通用)
    public function file()
    {
        $file     = request()->file('file_file');
        $md5      = $file->md5();//文件md5
        $fileName = $file->getOriginalName();//原始文件名
//        if ($fileItem = File::where('md5', $md5)->find()) {
//            $return['src']          = $fileItem['src'];
//            $return['name']         = $fileName;
//            $fileItem['updated_at'] = date('Y-m-d H:i:s');
//            return $this->json(200, '该文件已存在 路径为:'.$fileItem['path'], $return);
//        }
        if ($this->validate->checkFile($file)) {
            try {
                if (!$this->uploadPathIsWritable) {
                    throw new \Exception('上传文件夹需要写入权限');
                }

                $src            = Filesystem::putFile('files'.$this->DIRECTORY_SEPARATOR.date('Ym'), $file, 'uniqid');
                $src            = $this->uploadPath.$this->DIRECTORY_SEPARATOR.$src;
                $return['src']  = $src;
                $return['name'] = $fileName;
                File::add($file, $src, $md5, 'file');    //加入上传文件表
            } catch (\Exception $e) {
                return $this->json(1, $e->getMessage());
            }
            return $this->json(0, 'ok', $return);
        } else {
            $errorMsg = Lang::get($this->validate->getError());
            return $this->json(1, $errorMsg);
        }
    }

    //图片上传(通用)
    public function image()
    {
        // 字段名 image-image避免冲突 layui组件自动生成的隐藏file input框中name容易重名冲突
        $image   = request()->file('image_image');
        try {
            $res = $this->uploadImage($image);
            return $this->json(0, '上传成功', $res);
        } catch (RepositoryException $e) {
            return $this->json(1, $e->getMessage());
        }
    }

    public function uploadImage($image)
    {
        // 字段名 image-image避免冲突 layui组件自动生成的隐藏file input框中name容易重名冲突
        $md5     = $image->md5();//文件md5
        $path    = request()->param('path/s', '');//指定路径 基于public下  若为空则默认
        $hasPath = !empty($path);

        if ($this->validate->checkImage($image)) {
            //            if ($fileItem = File::where('md5', $md5)->find()) {
            //                $return['src']          = $fileItem['src'];
            //                $fileItem['updated_at'] = date('Y-m-d H:i:s');
            //
            //                return $this->json(200, '该文件已存在 路径为:'.$fileItem['path'], $return);
            //            }

            try {
                if (!$this->uploadPathIsWritable) {
                    throw new \Exception('上传文件夹需要写入权限');
                }

                // 去除以/storage/开头的部分  如/storage/20210808/test => 20210808/test
                if (strpos(trim($path, $this->DIRECTORY_SEPARATOR), \app\model\Attachment::ROOT_NAME.$this->DIRECTORY_SEPARATOR) === 0) {
                    $path = substr(trim($path, $this->DIRECTORY_SEPARATOR), strlen(\app\model\Attachment::ROOT_NAME.$this->DIRECTORY_SEPARATOR));
                }

                $datePath = $hasPath ? $path : 'images'.$this->DIRECTORY_SEPARATOR.date('Ym');//自定义目录
                $datePath = ($datePath == $this->DIRECTORY_SEPARATOR."storage") ? $this->DIRECTORY_SEPARATOR : $datePath;

                $src      = Filesystem::putFile($datePath, $image, 'uniqid');

                $src      = $this->uploadPath . $this->DIRECTORY_SEPARATOR . $src;
                $suffix   = strtolower($image->getOriginalExtension());
                if ($suffix == 'gif') {
                    $return['thumb_src'] = $src;    //TODO获取GIF缩略图
                } else {
                    $return['thumb_src'] = Image::getThumb($src, 100, 100, TImage::THUMB_SCALING);   //上传返回缩略图宽度为100
                }
                $return['src'] = $src;
                if ($this->isCompress) {
                    Image::resize($src);
                }
                File::add($image, $src, $md5);    //加入上传文件表
            } catch (\Exception $e) {
                throw new RepositoryException($e->getMessage());
            }
            return $return;
        } else {
            $errorMsg = Lang::get($this->validate->getError());
            throw new RepositoryException($errorMsg);
        }
    }

    //富文本编辑器上传图片
    public function tinyImage()
    {
        $image = request()->file('file');

        if (!$image) {
            // 字段名不对
            header("HTTP/1.1 404 config field error");
            exit;
        }

        if (!$this->uploadPathIsWritable) {
            header("HTTP/1.1 403 Insufficient folder permissions");
            exit;
        } else {
            $md5 = $image->md5();//文件md5
//            if ($fileItem = File::where('md5', $md5)->find()) {
//                $fileItem['updated_at'] = date('Y-m-d H:i:s');
//
//                $fileItem->save();
//                $res['location'] = $fileItem['src'];
//                return json($res);
//            }

            if (!in_array(strtolower($image->getMime()), ['image/png','image/jpeg','image/jpg','image/gif'])) {
                header("HTTP/1.1 400 MIME TYPE ERROR");
                exit;
            }

            checkPathExistWithMake(public_path().$this->uploadPath.'/images/'.date('Ym'));

            // tinymce富文本对图片进行操作后(xuan)上传的是blob文件。
            // 针对blob文件未读取到后缀名 自动生成后缀 默认用mimetype后缀 如image/jpeg =》jpeg
            $newFileName = $image->hashName('uniqid');
            if (isset(explode('.',$newFileName)[1]) && empty(explode('.',$newFileName)[1])) {
                $ext = explode('/', $image->getOriginalMime());
                $newFileName .= $ext[1];
            }

            $src    = Filesystem::putFileAs('images/'.date('Ym'), $image, $newFileName);
            $src    = $this->uploadPath.$this->DIRECTORY_SEPARATOR.$src;
            if ($this->isCompress) {
                // 剪切
                //Image::resize($src);
            }
            File::add($image, $src, $md5);    //加入上传文件表
            $res['location'] = $src;
            return json($res);
        }
    }
}