<?php

namespace App\Services;

use App\Model\SystemConfig;
use App\Server\Upload\OssServer;

class UploadServer
{
    /***
     * 上传到阿里云
     * @param $field
     * @param $request
     * @param string $tag
     * @param float|int $size
     * @param array $mimeType
     * @return mixed
     */
    public function aliUpload($field, $request, $size = 10 * 1024 * 1024, array $mimeType = ['image/jpeg', 'image/png', 'image/gif','video/mp4','video/quicktime'])
    {
        $conf = SystemConfig::get('ali_config', 'oss', '{}');
        $conf = json_decode($conf, true);
        $class = isset($request['class']) ? $request['class'] : 1;
        $file = $request[$field];
        if ($file === null) {
            return ['message' => '没有文件被上传'];
        }
        if (!$file->isValid()) {
            return ['message' => '不允许上传'];
        }
        $fileSize = $file->getSize();
        if ($fileSize > $size) {
            return ['message' => '文件大小超过限制'];
        }
        $fileMimeType = $file->getMimeType();
        if (!empty($mimeType) && !in_array($fileMimeType, $mimeType)) {
            return ['message' => '文件格式不被允许'];
        }

        $clientName = $file->getClientOriginalName();
        $md5 = md5($clientName . time());
        $md5_filename = $md5 . '.' . $file->getClientOriginalExtension();

        $file_Path = $file->getRealPath();

        try {
            $ok = OssServer::publicUpload($conf['BucketName']['value'], $md5_filename, $file_Path);

            if (!$ok) {
                return ['message' => '上传失败'];
            } else {
                return ['url' => $conf['FileUrl']['value'] . $md5_filename, 'message' => '上传成功'];
            }
        } catch (\Exception $e) {
            return ['message' => $e->getMessage()];
        }
    }

    /**
     * 直接上
     * @param $field
     * @param $request
     * @param float|int $size
     * @param array $mimeType
     * @return array
     */
    public function direct_upload($field,$clientName,$ext)
    {
        $conf = SystemConfig::get('ali_config', 'oss', '{}');

        $md5 = md5($clientName . time());
        $md5_filename = $md5 . '.' . $ext;


        try {
            $ok = OssServer::publicUpload($conf['BucketName']['value'], $md5_filename, $field);
            if (!$ok) {
                return ['message' => '上传失败'];
            } else {
                return ['url' => $conf['FileUrl']['value'] . $md5_filename, 'message' => '上传成功'];
            }
        } catch (\Exception $e) {
            return ['message' => $e->getMessage()];
        }
    }

    public function fileUpload($field, $request, $tag = 'files', $size = 10 * 1024 * 1024, array $mimeType = ['image/jpeg', 'image/png', 'image/gif','video/mp4','video/quicktime','text/plain'])
    {
        $tag = $request['folder'];
        $class = isset($request['class']) ? $request['class'] : 1;
        $width = isset($request['width']) ? $request['width'] : 0;
        $height = isset($request['height']) ? $request['height'] : 0;
        $rel_path = $tag . '/' . date('Ymd');
        $path = public_path() . $rel_path;

        if (!file_exists($path)) {
            if (!@mkdir($path, 0755, true)) {
                return ['message' => '目录创建失败'];
            }
        }

        $file = $request[$field];
        if ($file === null) {
            return ['message' => '没有文件被上传'];
        }
        if (!$file->isValid()) {
            return ['message' => '不允许上传'];
        }

        $fileSize = $file->getSize();
        if ($fileSize > $size) {
            return ['message' => '文件大小超过限制'];
        }
        $fileMimeType = $file->getMimeType();

        if (!empty($mimeType) && !in_array($fileMimeType, $mimeType)) {
            return ['message' => '文件格式不被允许'];
        }
        $clientName = $file->getClientOriginalName();
        $md5 = md5($clientName . time());
        $md5_filename = $md5 . '.' . $file->getClientOriginalExtension();

        try {
            if (!$file->move($path, $md5_filename)) {
                return ['message' => '上传失败'];
            }

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

            $source_info = null;
            if (($source_info = getimagesize($real_path)) != null) {
                $source_width = $source_info[0];
                $source_height = $source_info[1];
                if ($width || $height) {
                    if ($width == 0) {
                        $width = $source_width * ($height / $source_height);
                    }
                    if ($height == 0) {
                        $height = $source_height * ($width / $source_width);
                    }
                    Image::make($real_path)->resize($width, $height)->save($real_path);
                }
            }
            return ['message' => "上传成功", 'fileurl' => $url_path, 'name' => $md5_filename];
        } catch (\Exception $e) {
            return ['message' => $e->getMessage()];
        }
    }


    /**
     * 删除附件
     *
     * @param $md5 string 删除文件的md5码
     * @return int 错误码or 0（成功）
     */
    public function deleteAttachment($md5_filename)
    {
        $conf = SystemConfig::get('ali_config', 'oss', '{}');
        $conf = json_decode($conf, true);
        OssServer::publicDeleteObject($conf['BucketName']['value'], $md5_filename);
    }
}
