<?php

namespace app\admin\controller;

use app\model\AwsS3Model;
use app\model\FileModel;
use Aws\S3\S3Client;
use think\facade\Filesystem;
use think\facade\Config;

class Upload extends AdminBaseController
{

    // 上传图片
    public function upload()
    {
        try {
            // 获取文件
            $file = $this->request->file('file');
            $param = $this->request->param();
            $rootPath = $param['path'] ?? '';
            $filename = $param['name'] ?? '';

            // 将文件存储在本地
            $name = Filesystem::disk('local')->putFile($rootPath, $file);
            $path = '/bs/image/' . $name;

            if (!empty($filename) && file_exists(app()->getRootPath() . 'public' . $path)) {
                $newName = app()->getRootPath() . 'public/bs/' . $filename;
                copy(app()->getRootPath() . 'public' . $path, $newName);
                unlink(app()->getRootPath() . 'public' . $path);
                $path = '/bs/' . $filename;
            }

            // 返回路径
            return json(['code' => '0', 'message' => '上传成功', 'data' => ['path' => $path]]);
        } catch (\Exception $exception) {
            return json(['code' => '100500', 'message' => '系统繁忙', 'data' => [$exception->getMessage()]]);
        }
    }

    // 上传视频到aws s3
    public function uploadVideo()
    {
        try {
            // 获取文件
            $file = $this->request->file('file');
            // 检测文件是否存在
            if (!$file) {
                return json(['code' => 400, 'message' => 'No file uploaded']);
            }
            // 验证文件类型和大小
            $maxSize = 1024 * 1024 * 1024;  //限制1G
            if ($file->getSize() > $maxSize) {
                return json(['code' => 400, 'message' => 'The file size cannot exceed 1 GB']);
            }
            // 生成唯一的文件名
            $fileName = uniqid() . '.' . $file->getOriginalExtension();

            // 初始化S3客户端
            $s3Config = Config::get('common.aws_s3');

            $s3 = new S3Client([
                'version' => 'latest',
                'region'  => $s3Config['aws_region'],
                'credentials' => [
                    'key'    => $s3Config['aws_key'],
                    'secret' => $s3Config['aws_secret'],
                ],
            ]);
            // 上传文件到S3
            $result = $s3->putObject([
                'Bucket' => $s3Config['aws_bucket'],
                'Key'    => 'bourse-video-node/' . $fileName,   // s3中的存储路径
                'Body'   => fopen($file->getRealPath(), 'r'),
            ]);

            // 记录上传的文件
            $resData = AwsS3Model::create([
                'name' => $fileName,
                's3_url' => $result['ObjectURL'],
                'size' => $file->getSize(),
                'mime' => $file->getOriginalMime(),
                'ext' => $file->getOriginalExtension(),
            ]);;

            // 返回上传成功的地址
            return json(['code' => '0', 'message' => '上传成功', 'data' => [
                'id' => $resData->id,
                'url' => $result['ObjectURL'],
                'name' => $fileName,
                'size' => $file->getSize(),
                'mime' => $file->getOriginalMime(),
                'ext'=> $file->getOriginalExtension(),
            ]]);
        } catch (\Exception $exception) {
            return json(['code' => '100500', 'message' => '系统繁忙', 'data' => [$exception->getMessage()]]);
        }
    }

}