<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
namespace wendasns;

use think\Exception;
use think\helper\Str;
use think\facade\Filesystem;

class Image
{
	private $filename;
	private $type;
	
	public function portrait($uid){
		$this->filename = md5((string)$uid);
		$this->type = 'portrait';
		return $this;
		//throw new Exception('');
	}

	public function content($type,$filename=''){
		$this->filename = $filename;
		$this->type = $type;
		return $this;
	}
	
	public function upload($file){
		$mode = configure('upload.mode','local');
		if($mode=='local'){
			return $this->_local($file);
		}else{
			return '';
		}
	}
	
    private function _local($file)
    {
    	if(!$this->filename){
    		$file_name = Str::random(6);
    		$suffix = substr($file->getOriginalName(),-3);
    		$file_name = $file_name.$file->getOriginalName();
    		$file_name = md5($file_name);
    		$this->filename = $file_name.'.'.$suffix;
    	}else{
    		$suffix = substr($file->getOriginalName(),-3);
    		$file_name = $this->filename;
    		$this->filename = $this->filename.'.'.$suffix;
    	}
    	$app = app('http')->getName();
    	include root_path('route').'app.php';
    	$path = root_path('runtime'.DIRECTORY_SEPARATOR.$app);
    	Filesystem::getAdapter()->setPathPrefix($path);
    	Filesystem::putFileAs($this->type, $file, $this->filename);
    	if($this->type=='portrait'){
    		return $this->filename;
    	}
    	$src = (string)url('wendasns/api/image', ['type'=>$this->type,'name'=>$file_name], $suffix, true);
    	return $src;
    }
    
    private function _cloud($file)
    {
    	
    }
}