<?php
namespace App\Helper;

use FFMpeg;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use OSS\OssClient;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use App\Services\Base\ErrorCode;
use App\Models\BaseAttachment;

trait AttachmentHelper
{
    /**
     * @param Request $request
     * @param $key
     * @param string $tag
     * @param float|int $size
     * @param array $mimeType
     * @return array|mixed
     * @throws \OSS\Core\OssException
     */
    public function uploadAttachment(Request $request, $key, $tag = 'files', $size = 200 * 1024 * 1024, array $mimeType = []) {
        if ($request->hasFile($key)) {
            $files = $request->file($key);
            if ($files === null) {
                throw new \Exception(trans('api.ATTACHMENT_FILE_NULL'));
            }
            if ($files instanceof UploadedFile) {
                $files = [$files];
            }

            $result = [];
            foreach ($files as $idx => $file) {
                if (!$file->isValid()) {
                    throw new \Exception(trans('api.ATTACHMENT_TYPE_ERROR'));
                    continue;
                }
                $fileSize = $file->getSize();
                if ($fileSize > $size) {
                    throw new \Exception(trans('api.ATTACHMENT_SIZE_EXCEEDED'));
                    continue;
                }
                $fileMimeType = $file->getMimeType();
                if (!empty($mimeType) && !in_array($fileMimeType, $mimeType)) {
                    throw new \Exception(trans('api.ATTACHMENT_TYPE_ERROR'));
                    continue;
                }
                $clientName = $file->getClientOriginalName();
                $md5 = md5($clientName . time());
                //因为 $md5 32 位字符太长，创建群聊头像失败
                $md5_filename = substr($md5, 0, 20) . '.' . $file->getClientOriginalExtension();
                try {
                    //本地上传
                    if(env('FILESYSTEM_DRIVER')=='local'){
                        $rel_path = '/upload/' . $tag . '/' . date('Ymd');
                        $path = public_path() . $rel_path;
                        if (!file_exists($path)) {
                            if (!@mkdir($path, 0755, true)) {
                                throw new \Exception(trans('api.ATTACHMENT_MAKE_FOLDER_ERROR'));
                            }
                        }

                        $file->move($path, $md5_filename);

                        $real_path = $path . '/' . $md5_filename;
                        $url_path = $rel_path . '/' . $md5_filename;

                        if ($fileMimeType == "video/mp4" || $fileMimeType == "video/quicktime") {
                            $ffmpeg = FFMpeg\FFMpeg::create(array(
                                'ffmpeg.binaries'  => '/usr/bin/ffmpeg',
                                'ffprobe.binaries' => '/usr/bin/ffprobe'
                            ));
                            $video = $ffmpeg->open($real_path);
                            $vpath = public_path() . '/upload/vpic/';
                            if (!file_exists($vpath)) {
                                if (!@mkdir($vpath, 0755, true)) {
                                    return trans('api.ATTACHMENT_MAKE_FOLDER_ERROR');
                                }
                            }
                            $pic = $vpath.$md5.'.jpg';
                            $video
                                ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(1))
                                ->save( $pic );
                        }

                        $result[$idx] = 'https://'.$_SERVER['HTTP_HOST'].$url_path;
                    }elseif (env('FILESYSTEM_DRIVER')=='oss'){
                        //获取上传图片的临时地址
                        $tmppath = $file->getRealPath();
                        //生成文件名
                        $fileName = rand(100, 999) . time() . date('ymd') . '.' . $file->getClientOriginalExtension();
                        $pathName = 'golf/' . date('Y-m/d') . '/' . $fileName;
                        //上传图片到阿里云OSS
                        $oss = new OssClient(env('ALI_OSS_ACCESS_ID'), env('ALI_OSS_ACCESS_KEY'), env('ALI_OSS_ENDPOINT'));
                        $res = $oss->uploadFile(env('ALI_OSS_BUCKET'), $pathName, $tmppath, ['ContentType' => $file->getClientMimeType()]);
                        $url = $res['info']['url'];
                        $result[$idx] = $url;
                    }
                    $attachment = new BaseAttachment();
                    $attachment->name = $clientName;
                    $attachment->md5  = $md5;
                    $attachment->path = $url;
                    $attachment->url  = $url;
                    $attachment->size = $fileSize;
                    $attachment->file_type = $fileMimeType;
                    if (!$attachment->save()) {
                        @unlink($url);
                        throw new \Exception(trans('api.ATTACHMENT_SAVE_ERROR'));
                    }
                } catch (FileException $e) {
                    throw new \Exception(trans('api.ATTACHMENT_UPLOAD_INVALID'));
                }
            }
            if (count($result) == 1) {
                return array_shift($result);
            }
            return $result;
        } else {
            throw new \Exception(trans('api.ATTACHMENT_UPLOAD_INVALID'));
        }

    }

    /**
     * 删除附件
     *
     * @param $md5 string 删除文件的md5码
     * @return int 错误码or 0（成功）
     */
    public function deleteAttachment($md5) {
        $attachment = BaseAttachment::where(['md5' => $md5])->first();
        if (!$attachment) {
            return ErrorCode::ATTACHMENT_NOT_EXIST;
        }
        if (file_exists($attachment->path)) {
            if (@unlink($attachment->path)) {
                if ($attachment->delete()) {
                    return 0;
                } else {
                    return ErrorCode::ATTACHMENT_RECORD_DELETE_FAILED;
                }
            } else {
                return ErrorCode::ATTACHMENT_DELETE_FAILED;
            }
        } else {
            return ErrorCode::ATTACHMENT_NOT_EXIST;
        }

    }

}
