<?php

namespace App\Controller;

use App\Constants\Config;
use App\Helpers\AppHelper;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\RequestInterface;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use function Hyperf\Config\config;

#[Controller(prefix: 'upload')]
class UploadController extends AbstractController
{
    /**
     * @url common/uploadImage
     * @return array
     * @throws \Exception
     */
    // #[RequestMapping(path: "upload-image", methods: "post")]
    public function uploadImage(): array
    {
        $baseConfigKey = 'plugin.admin.upload.qiniu.';
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = config('upload.qiniu.access_key');
        $secretKey = config('upload.qiniu.secret_key');

        $bucket = config('upload.qiniu.bucket');
        $file = $this->request->file('file');
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        $returnBody = '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}';
        $policy = array(
            'returnBody' => $returnBody
        );
        // 生成上传 Token
        $token = $auth->uploadToken($bucket, policy: $policy);
        // 要上传文件的本地路径
        // 上传到存储后保存的文件名
        $filePath = $file->getRealPath();
        $key = date('Y-m') . '/' . $file->getClientFilename();
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath, null, 'application/octet-stream', true, null, 'v2');

        return [
            'code' => 0,
            'msg' => '上传成功@@',
            'data' => [
                'base_url' => AppHelper::getImageBaseUrl(),
                'base_path' => $ret['key'],
                'src' => AppHelper::getImageBaseUrl() . $ret['key'],
                'name' => $ret['key'],
                'size' => $ret['fsize'],
            ]
        ];
    }

    #[RequestMapping(path: "image", methods: "post")]
    public function image()
    {
        $file = $file = $this->request->file('file');

        if (!$file || $file->getError() !== UPLOAD_ERR_OK) {
            return $this->response->json(['code' => 400, 'msg' => '文件上传失败']);
        }

        // 校验类型
//        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
//        if (!in_array($file->getClientMediaType(), $allowedTypes)) {
//            return $this->response->json(['code' => 415, 'msg' => '不支持的图片格式']);
//        }

        // 限制大小 (例如 5MB)
        $maxSize = 5 * 1024 * 1024;
        if ($file->getSize() > $maxSize) {
            return $this->response->json(['code' => 413, 'msg' => '图片大小不能超过 5MB']);
        }

        // 保存路径
        $filename = uniqid() . '.' . pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);
        $targetPath = BASE_PATH . '/uploads/' . $filename;

        // 确保目录存在
        if (!is_dir(dirname($targetPath))) {
            mkdir(dirname($targetPath), 0777, true);
        }

    
        // 移动文件
        $file->moveTo($targetPath);

        // 构造返回 URL
        $url = '/uploads/' . $filename;

        return $this->response->json([
            'errno' => 0,
            'msg' => '上传成功!!~',
            'data' => [
                'url' => Config::getDomain() . $url,
            ]
        ]);
    }


    /**
     * 上传关键词监控页面
     * @url upload/search-image
     */
    #[RequestMapping(path: 'search-image', methods: 'post')]
    public function uploadSearchImage()
    {
        $file = $file = $this->request->file('file');

        if (!$file || $file->getError() !== UPLOAD_ERR_OK) {
            return $this->response->json(['code' => 400, 'msg' => '文件上传失败']);
        }

        // 校验类型
//        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
//        if (!in_array($file->getClientMediaType(), $allowedTypes)) {
//            return $this->response->json(['code' => 415, 'msg' => '不支持的图片格式']);
//        }

        // 限制大小 (例如 5MB)
        $maxSize = 5 * 1024 * 1024;
        if ($file->getSize() > $maxSize) {
            return $this->response->json(['code' => 413, 'msg' => '图片大小不能超过 5MB']);
        }

        // 保存路径
        $filename = uniqid() . '.' . pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);
        $date = date('m-d');
        $targetPath = BASE_PATH . '/uploads/' . $filename;

        // 确保目录存在
        if (!is_dir(dirname($targetPath))) {
            mkdir(dirname($targetPath), 0777, true);
        }


        // 移动文件
        $file->moveTo($targetPath);

        // 构造返回 URL
        $url = '/uploads/' . $filename;

        return $this->response->json([
            'errno' => 0,
            'msg' => '上传成功~~',
            'data' => [
                'url' => Config::getDomain() . $url,
                'file_name' => $url
            ]
        ]);
    }
}