<?php

namespace Modules\Common\Http\Controllers\Qiniu;

use Catch\Base\CatchController;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class ImageUploadController extends CatchController
{
    public function uploadImage(Request $request) {
        $file = $request->photo;
        $qiniuConfig = config('common.qiniu');

        $auth = new Auth($qiniuConfig['accessKey'], $qiniuConfig['secretKey']);
        $token = $auth->uploadToken(config('common.qiniu.publicBucket'));
        $filePath = $file->path();
        $key = 'uploads'.DIRECTORY_SEPARATOR.'images'. DIRECTORY_SEPARATOR . date('Ymd') .
            DIRECTORY_SEPARATOR. Str::random(10) . time() . '.'. $file->extension();
        $uploadMgr = new UploadManager();
        list($ret, $err) =  $uploadMgr->putFile($token, $key, $filePath, null, 'application/octet-stream',
            true, null, 'v2');
        if($err !== null) {
            CommonBusinessException::throwError(Errors::UPLOAD_IMAGE_ERROR);
        } else {
            return $qiniuConfig['publicLinkDomain']. DIRECTORY_SEPARATOR . $key;
        }
    }
}
