<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\model\Slider as SliderModel;
use app\admin\model\Attachment;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Env;

/**
 * 上传控制器
 */
class File extends AdminBase
{
    /**
     * 图片上传
     * @param int $upload_type
     * @param int $type
     * @return mixed
     */
    public function upload($upload_type = 0, $type = 0)
    {
        $file = $this->request->file('file');
        $name = $file->getOriginalName();
        //dump($mime);exit;
        // 获取附件信息
        $file_info = [
            'uid'    => $this->adminId,
            'name'   => $name,
            'mime'   => $file->getMime(),
            'ext'    => self::getExtension($name),
            'size'   => $file->getSize(),
            'md5'    => explode('.',$name)[0],
        ];
        $exist = Attachment::where(['md5' => $file_info['md5']])->find();
        if(!$exist){
            $save  = Filesystem::disk('public')->putFile( 'images', $file);
            if($save){
                $file_info['path'] = "/uploads/".$save;
                if($add = Attachment::create($file_info)) {
                    $data['img_url'] = sysConfig('app_url')."/uploads/".$save;
                    return ajaxmsg('上传成功',200, $data);
                }
            }else {
                return ajaxmsg('上传失败',0);
            }
        }else{
            $data['img_url'] = sysConfig('app_url')."/".$exist['path'];
            return ajaxmsg('文件已存在',200,$data);
        }
        
    }
    
    public function getExtension($filename){ 
		$myext = substr($filename, strrpos($filename, '.')); 
		return str_replace('.','',$myext); 
	}
}