<?php

namespace app\controller\admin\api\v1;

use support\Request;
use App\Utils\ApiResponse;
use App\model\Users;
use App\model\BankLog;
use hg\apidoc\annotation as Apidoc;
use App\dao\BankDao;
use Intervention\Image\ImageManagerStatic as Image;
use Exception;
use support\exception\BusinessException;

/**
 * @Apidoc\Title("上传文件控制器")
 */
class UploadController
{
    protected $noNeedLogin = ['image','index','imageAiEditor'];
    /**
     * @Apidoc\Title("1.0 测试图片上传")
     * @Apidoc\Url("admin/api/v1/Upload/image")
     * @Apidoc\Method("POST")
     */
    public function image(Request $request)
    {
        // 调用 base 方法上传文件，指定上传目录
        $data = $this->base($request, '/upload/img/' . date('Ymd'));

        // 获取上传文件的实际路径
        $realpath = $data['realpath'];

        try {
            // 验证文件类型
            $validMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!in_array(mime_content_type($realpath), $validMimeTypes)) {
                unlink($realpath);
                return json([
                    'code' => 400,
                    'msg' => '只允许上传图片文件'
                ]);
            }

            // 使用 Intervention Image 处理图片
            $img = Image::make($realpath);
            $max_height = 11700;
            $max_width = 11700;
            $width = $img->width();
            $height = $img->height();
            $ratio = 1;

            // 如果图片尺寸超过限制，则按比例缩放
            if ($height > $max_height || $width > $max_width) {
                $ratio = $width > $height ? $max_width / $width : $max_height / $height;
            }
            // 缩放并保存图片
            $img->resize($width * $ratio, $height * $ratio)->save($realpath);
        } catch (Exception $e) {
            // 出现异常时，删除上传的文件并返回错误信息
            unlink($realpath);
            return json([
                'code' => 500,
                'msg' => '处理图片发生错误'
            ]);
        }

        // 返回成功的响应，包含图片的 URL、文件名和文件大小
        return json([
            'code' => 200,
            'msg' => '上传成功',
            'data' => [
                'url' => $data['url'],
                'name' => $data['name'],
                'size' => $data['size'],
            ]
        ]);
    }
    public function index(Request $request){
        return ApiResponse::success(200,[]);
    }
    /**
     * 获取上传数据
     * @param Request $request
     * @param $relative_dir
     * @return array
     * @throws BusinessException|\Random\RandomException
     */
    protected function base(Request $request, $relative_dir): array
    {
        $relative_dir = ltrim($relative_dir, '\\/');
        $file = current($request->file());

        if (!$file || !$file->isValid()) {
            throw new BusinessException('未找到上传文件', 400);
        }

        // 使用配置文件中定义的上传路径
        // $uploadPath = config('upload.path');  // 从配置文件中获取路径
        $uploadPath = public_path('uploads/images');
        $base_dir = rtrim($uploadPath, '\\/');

        // 如果路径不存在，创建路径
        $full_dir = $base_dir . DIRECTORY_SEPARATOR . $relative_dir;
        if (!is_dir($full_dir)) {
            mkdir($full_dir, 0777, true);
        }

        // 处理上传的文件
        $ext = $file->getUploadExtension() ?: null;
        $mime_type = $file->getUploadMimeType();
        $file_name = $file->getUploadName();
        $file_size = $file->getSize();

        // 文件类型验证
        if (!$ext && $file_name === 'blob') {
            [$___image, $ext] = explode('/', $mime_type);
            unset($___image);
        }

        $ext = strtolower($ext);
        $ext_forbidden_map = ['php', 'php3', 'php5', 'css', 'js', 'html', 'htm', 'asp', 'jsp'];
        if (in_array($ext, $ext_forbidden_map)) {
            throw new BusinessException('不支持该格式的文件上传', 400);
        }

        // 生成文件路径
        $relative_path = $relative_dir . '/' . bin2hex(pack('Nn', time(), random_int(1, 65535))) . ".$ext";
        $full_path = $base_dir . DIRECTORY_SEPARATOR . $relative_path;

        // 移动文件到新路径
        $file->move($full_path);

        $image_with = $image_height = 0;
        if ($img_info = getimagesize($full_path)) {
            [$image_with, $image_height] = $img_info;
            $mime_type = $img_info['mime'];
        }

        return [
            'url' => "https://weapp.ycylzj.com.cn/uploads/images/$relative_path",
            'name' => $file_name,
            'realpath' => $full_path,
            'size' => $file_size,
            'mime_type' => $mime_type,
            'image_with' => $image_with,
            'image_height' => $image_height,
            'ext' => $ext,
        ];
    }
       /**
     * @Apidoc\Title("1.0 AiEditor图片上传")
     * @Apidoc\Url("admin/api/v1/Upload/imageAiEditor")
     * @Apidoc\Method("POST")
     */
    public function imageAiEditor(Request $request)
    {
        // 调用 base 方法上传文件，指定上传目录
        $data = $this->base($request, '/upload/img/' . date('Ymd'));

        // 获取上传文件的实际路径
        $realpath = $data['realpath'];

        try {
            // 验证文件类型
            $validMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!in_array(mime_content_type($realpath), $validMimeTypes)) {
                unlink($realpath);
                return json([
                    'code' => 400,
                    'msg' => '只允许上传图片文件'
                ]);
            }

            // 使用 Intervention Image 处理图片
            $img = Image::make($realpath);
            $max_height = 11700;
            $max_width = 11700;
            $width = $img->width();
            $height = $img->height();
            $ratio = 1;

            // 如果图片尺寸超过限制，则按比例缩放
            if ($height > $max_height || $width > $max_width) {
                $ratio = $width > $height ? $max_width / $width : $max_height / $height;
            }
            // 缩放并保存图片
            $img->resize($width * $ratio, $height * $ratio)->save($realpath);
        } catch (Exception $e) {
            // 出现异常时，删除上传的文件并返回错误信息
            unlink($realpath);
            return json([
                'code' => 500,
                'msg' => '处理图片发生错误'
            ]);
        }

        // 返回成功的响应，包含图片的 URL、文件名和文件大小
        return json([
            'errorCode' => 0,
            'msg' => '上传成功',
            'data' => [
                'src' => $data['url'],
                'alt' => $data['url'],
            ]
        ]);
    }
}
