<?php

namespace App\Http\Controllers;

use App\Models\Log as LogModel;
use App\Models\Shop;
use App\Services\Business\BusinessFactory;
use App\Utils\UploadUtils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    public function __construct(Request $request)
    {
        $this->log = new LogModel([
            'module' => 'file',
            'action' => $request->getMethod(),
            'target_type' => 'upload',
        ]);
    }

    public function store(Request $request)
    {
        if (!$request->hasFile('uploadFile')) {
            $this->res = [
                'httpCode' => 404,
                'errorCode' => 404404,
                'errorMessage' => 'not found file',
            ];
        }
        $this->addLog(0, 'add');
//        $this->res['resource'] = UploadUtils::getFullImgUrl(UploadUtils::putForUploadedFile('image', $request->uploadFile));
        $this->res['shop_id'] = $request->get('shop_id') ?: 0;
        $path = $request->file('uploadFile')->store('ktt');
        $url = config('app.url') . '/' . $path;
        // 图片上传到花富贵儿 快团团图片库
        $shop = Shop::query()->find(1);
        $business = BusinessFactory::init()->make($shop->plat_id);
        $business->setShop($shop);
        $res = $business->uploadImage($url);
        if (isset($res['response'])) {
            $this->res['resource'] = $res['response']['result'];
            Storage::delete($path);
        } else {
            $this->res['resource'] = $url;
        }

        return response($this->res, $this->res['httpCode']);
    }
}
