<?php

declare(strict_types=1);

namespace App\Service;

use Aws\S3\S3Client;
use Hyperf\HttpServer\Contract\ResponseInterface;
use function Hyperf\Support\env;
use App\Tools\Result;
use Hyperf\HttpMessage\Upload\UploadedFile;

class MinioService
{
    /**
     * @Inject
     * @var ResponseInterface
     */
    protected $response;

    /**
     * @Inject
     * @var \Hyperf\Config\ConfigInterface
     */
    protected $config;

    protected $s3Client;

    public function __construct()
    {
        $this->s3Client = new S3Client([
            'version' => 'latest',
            'region'  => 'chinese',
            'endpoint' => env("OSS_ENDPOINT"),
            'use_path_style_endpoint' => true,
            'credentials' => [
                'key'    => env("OSS_KEY"),
                'secret' => env("OSS_SECRET"),
            ],
        ]);
    }

    /**
     * 没几把鸟用用来测试的
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function listBuckets()
    {
        try {
            // 获取所有存储桶列表
            $result =  $this->s3Client->listBuckets();
            // 提取存储桶名称
            $buckets = array_column($result['Buckets'], 'Name');
            return  Result::success($buckets);
        } catch (\Aws\Exception\AwsException $e) {
            return  Result::error("报错了");
        } catch (\Exception $e) {
            return  Result::error("报错了");
        }
    }

    /**
     * 上传文件
     * @return array|string[]
     */
    public function uploadFile($data)
    {
        $acceptExt = ['png', 'jpg', 'jpeg', 'gif', 'xls', 'xlsx', 'pdf', 'doc', 'docx', 'ppt', 'zip', 'pptx', 'mp4', 'flv','rar','tar'];
        try {
            if (!in_array( $data['ext'], $acceptExt)) {
                return Result::error('文件名后缀不允许');
            }
            $fileName = time().mt_rand(1, 1000000) . '.' . $data['ext'];
            $finalPath =  DIRECTORY_SEPARATOR.date('Ymd').DIRECTORY_SEPARATOR  . $fileName;
            $key = $data['contentType'].$finalPath;
            var_dump("key:",$key);
            $result = $this->s3Client->putObject([
                'Bucket' => env("BUCKET"),
                'Key' => $key,
                'Body' => base64_decode($data['fileContent']),
                'ACL' => 'public-read',
                'ContentType' => $data['contentType'],
            ]);
            $rep = [
                'imgUrl'=>$result['ObjectURL'],
                'id'=>uniqid(),
                'src'=>$key,
                'fileName'=>$fileName,
                'fileType'=> $data['ext'],
                'oldFileName'=>$data['fileName']
            ];
            return  Result::success($rep);
        } catch (\Exception $e) {
            return  Result::error($e->getMessage());
        }
    }

}