<?php
namespace App\Tools;
use App\Constants\ErrorCode;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Upload\UploadedFile;
use App\Tools\Result;
use ZX\Tools\File\MimeTypes;
use function Hyperf\Support\env;
use Hyperf\HttpServer\Contract\RequestInterface;


class CommonService
{
    #[Inject]
    protected RequestInterface $request;
    public static function uploadFile(UploadedFile $uploadedFile, array $acceptExt, string $fileType = 'image')
    {
        $ext = $uploadedFile->getExtension();

        if (!in_array($ext, $acceptExt)) {
            return Result::error('文件名后缀不允许');
        }
        //图片检测安全
        if ($fileType == 'image') {
            $res = self::checkMimeType($uploadedFile, $ext);
            if ($res == false) {
                return Result::error('文件安全检测未通过');
            }
        }
        $date = date('Ymd');
        $filePath =  $fileType . DIRECTORY_SEPARATOR . $date ;
        $allDir = 'public' . DIRECTORY_SEPARATOR . $filePath;
        if (!is_dir($allDir)) {
            if (!mkdir($allDir, 0755, true)) {
                return Result::error('创建文件夹失败');
            }
        }
        $fileName = time().mt_rand(1, 1000000) . '.' . $ext;
        $finalPath = BASE_PATH . DIRECTORY_SEPARATOR . $allDir . DIRECTORY_SEPARATOR . $fileName;
        $showPath = $filePath . DIRECTORY_SEPARATOR . $fileName;
        $uploadedFile->moveTo($finalPath);

        return ['id' => uniqid(), 'src' => $showPath, 'fileName' => $fileName];
    }


    //检测文件是否合法
    public static function checkMimeType(UploadedFile $uploadedFile, string $ext = '')
    {
        try {
            $filePath = $uploadedFile->getRealPath();
            $fileMimeType = mime_content_type($filePath);
            $mimeTypes = MimeTypes::getImage();
            $isExist = array_key_exists($fileMimeType, $mimeTypes);
            if (!$isExist) {
                return Result::error('非允许mime types类型');
            }
            list($width, $height, $type, $attr) = getimagesize($filePath, $ext);
            if ($width <= 0 || $height <= 0) {
                return false;
            } else {
                return true;
            }

        } catch (\Exception $e) {
            return false;
        }

    }

    public  function imgUrl(string $str)
    {
        $scheme =$this->request->geturi()->getScheme() ?? 'http';
        $host =  $this->request->getUri()->getHost() ?? '127.0.0.1';
        $port = $this->request->getUri()->getPort() ?? config('server.servers.port', 9500);

        $url = '';
        if ($port == 80 || $port == 443) {
            $url = "{$scheme}://{$host}/{$str}";
        } else {
            $url = "{$scheme}://{$host}:{$port}/{$str}";
        }
        return $url;
    }



}