<?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 __construct()
    {
        $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)) {
            $this->uploadPathIsWritable = 1;
        }
        if (is_writable(app()->getRootPath().'public'.$this->videoUploadPath)) {
            $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');
        if (!$this->videoUploadPathIsWritable) {
            return $this->json(1, '上传文件夹需要写入权限');
        }
        if ($this->validate->checkVideo($video)) {
            $md5 = $video->md5();//文件md5
//            if ($fileItem = File::where('md5', $md5)->find()) {
//                $return['src']          = $fileItem['src'];
//                $fileItem['updated_at'] = date('Y-m-d H:i:s');
//                $fileItem->save();
//                return $this->json(200, '该文件已存在 路径为:'.$fileItem['path'], $return);
//            }

            $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);
        }
    }

    //文件上传(通用)
    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 wangImage()
    {

        $imageArr = request()->file('wang_img'); // 该方式,前端js上传方法中字段名称必须以数组形式传参 如 wang_img[] = 值
        $errno    = 0;
        $data     = [];

        if (!$this->uploadPathIsWritable) {
            $errno  = 1;
            $data[] = '上传文件夹需要写入权限';
        } else {
            foreach ($imageArr as $image) {
                $md5 = $image->md5();//文件md5
                if ($fileItem = File::where('md5', $md5)->find()) {
                    $return['src']          = $fileItem['src'];
                    $fileItem['updated_at'] = date('Y-m-d H:i:s');

                    $data[] = $fileItem['src'];
                    $fileItem->save();
                    continue;
                }

                if ($this->validate->checkImage($image)) {
                    $src    = Filesystem::putFile('images/'.date('Ym'), $image, 'uniqid');
                    $src    = $this->uploadPath.$this->DIRECTORY_SEPARATOR.$src;
                    $data[] = $src;
                    if ($this->isCompress) {
                        Image::resize($src);
                    }
                    File::add($image, $src, $md5);    //加入上传文件表
                } else {
                    $errno  = 1;
                    $data   = [];
                    $data[] = Lang::get($this->validate->getError());
                    break;
                }
            }
        }

        $return['errno'] = $errno;
        $return['data']  = $data;
        return json($return);
    }

    public function uploadImage($image)
    {
        // 字段名 image-image避免冲突 layui组件自动生成的隐藏file input框中name容易重名冲突
        $md5     = $image->md5();//文件md5
        $type    = request()->param('type/s', '');
        $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'];
                $return['thumb_src']    = Image::getThumb($fileItem['src'], 100, 100, TImage::THUMB_SCALING);
                return $return;
            }

            $info   = @getimagesize($image->getPathname());
            $width  = $info[0] ?? 0;
            $height = $info[1] ?? 0;

            // 海报限制大小 750 * 1334
            switch ($type) {
                case 'porter':
                    if ($width != 750 || $height != 1334) {
                        return $this->json(1, '海报背景图尺寸大小固定为:750 * 1334');
                    }
                    break;
            }

            //            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);
        }
    }
}