<?php


namespace App\Http\Controllers\Api;


use App\Facade\TableName;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UploadController
{
    public function uploadFile(Request $request)
    {
        $UserID = $request->input('UserID');
        $base64img = $request->input('image');

        if (empty($UserID)) return apiReturnFail(__('messages.api.upload.missing_user_info'));
        if (empty($base64img)) return apiReturnFail(__('messages.api.upload.empty_image'));

        $base64img = str_replace(' ', '+', $base64img);
        $image_patern = '/^(data:\s*image\/(\w+);base64,)/';
        $ext = '';
        if (preg_match($image_patern, $base64img, $result)) $ext = $result[2];
        if (!in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'bmp'])) return apiReturnFail(__('messages.api.upload.incorrect_file_type'));

        //接收base64数据
        $image = $base64img;
        //设置图片名称
        $imageName = uniqid() . '.' . $ext;
        //判断是否有逗号 如果有就截取后半部分
        if (strstr($image, ",")) {
            $image = explode(',', $image);
            $image = $image[1];
        }

        //设置图片保存路径
        $path = 'uploads' . DIRECTORY_SEPARATOR . "api" . DIRECTORY_SEPARATOR . date('Ymd');

        //判断目录是否存在 不存在就创建
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }

        //图片路径
        $imageSrc = $path . "/" . $imageName;

        //生成文件夹和图片
        $r = file_put_contents($imageSrc, base64_decode($image));
        if (!$r) {
            return apiReturnFail(__('messages.api.upload.upload_failed'));
        } else {

            unlink(DB::connection('write')->table(TableName::agent() . 'UserHeadAuditoria')->where('UserID',$UserID)->value('Image'));

            $imageSrc = str_replace("./", "/", $imageSrc);
            DB::table(TableName::agent() . 'UserHeadAuditoria')
                ->updateOrInsert(['UserID' => $UserID], ['UserID' => $UserID, 'Image' => $imageSrc, 'UpdateTime' => now(),'Status'=>0]);
            return apiReturnSuc($imageSrc);
        }

    }
}
