<?php

namespace api\user\controller;

use cmf\controller\RestUserBaseController;
use think\Db;

class UploadController extends RestUserBaseController
{
    // 用户密码修改
    public function one()
    {
        $file = $this->request->file('file');
        if(empty($file)){
             $this->error('file is empty');
        }
        // 移动到框架应用根目录/public/upload/ 目录下
        $info     = $file->validate([
            /*'size' => 15678,*/
            'ext' => 'jpg,jpeg,png,gif'
        ]);
        $fileMd5  = $info->md5();
        $fileSha1 = $info->sha1();

        $findFile = Db::name("asset")->where('file_md5', $fileMd5)->where('file_sha1', $fileSha1)->find();

        if (!empty($findFile)) {
            $this->success("上传成功!", ['url' => $findFile['file_path'], 'filename' => $findFile['filename'],'http_url'=>cmf_get_image_url($findFile['file_path'])]);
        }
        $info = $info->move(ROOT_PATH . 'public' . DS . 'upload');
        if ($info) {
            $saveName     = $info->getSaveName();
            $originalName = $info->getInfo('name');//name,type,size
            $fileSize     = $info->getInfo('size');
            $suffix       = $info->getExtension();

            $fileKey = $fileMd5 . md5($fileSha1);

            $userId = $this->getUserId();
            Db::name('asset')->insert([
                'user_id'     => $userId,
                'file_key'    => $fileKey,
                'filename'    => $originalName,
                'file_size'   => $fileSize,
                'file_path'   => $saveName,
                'file_md5'    => $fileMd5,
                'file_sha1'   => $fileSha1,
                'create_time' => time(),
                'suffix'      => $suffix
            ]);

            $this->success("上传成功!", ['url' => $saveName, 'filename' => $originalName,'http_url'=>cmf_get_image_url($saveName)]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }

    }


}
