<?php

namespace app\common\api;

use app\common\validate\Upload;

/**
 * Description of UploadApi
 *
 * @author sgq
 */
class UploadApi {

    protected $fileSize = 5 * 1024 * 1024;
    protected $fileExt = "jpg,png,gif,pdf,xls,xlsx";
    protected $fileMime = "image/jpg,image/png,image/gif,application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    public function __construct($config = []) {
        $this->fileSize = isset($config["maxSize"]) ? $config["maxSize"] : $this->fileSize;
        $this->fileExt = isset($config["fileExt"]) ? $config["fileExt"] : $this->fileExt;
        $this->fileMime = isset($config["fileMime"]) ? $config["fileMime"] : $this->fileMime;
    }

    /**
     * 批量上传文件
     * @param type $files
     * @return type
     */
    public function uploadList($files, $path = "uploadfiles") {
        try {
            validate(['image' => ["fileSize" => $this->fileSize, "fileExt" => $this->fileExt, "fileMime" => $this->fileMime]])
                    ->check($files);
            $savename = [];
            foreach ($files as $file) {
                $savename[] = \think\facade\Filesystem::disk("public")->putFile($path, $file);
            }
            return $savename;
        } catch (\think\exception\ValidateException $e) {
            echo $e->getMessage();
        }
    }

    /**
     * 单个文件上传
     * @param type $file
     * @param type $type 图片 => image 文件 => file 其他 => hybrid
     * @return type
     */
    public function uploadOne($file, $type, $path = "uploadfiles") {
        $upload_result = new \StdClass();
        try {
            switch ($type) {
                case 'image':
                    $check = ['image' => $file];
                    break;
                case 'file':
                    $check = ['file' => $file];
                    break;
                case 'hybrid':
                    $check = ['hybrid' => $file];
                    break;
                case 'system':
                    $check = ['system' => $file];
                    break;
                default:
                    $upload_result->code = 500;
                    $upload_result->msg = "不支持的上传类型";
                    return $upload_result;
            }

            validate(Upload::class)->check($check);
            $savename = \think\facade\Filesystem::disk("public")->putFile($path, $file);
            $upload_result->code = 200;
            $upload_result->filepath = $savename;
            return $upload_result;
        } catch (\think\exception\ValidateException $e) {
            $upload_result->code = 500;
            $upload_result->msg = $e->getMessage();
            return $upload_result;
        }
    }

}
