<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace Modules\System\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\BaseController;

class File extends BaseController {

	/**
	 * @title 上传文件
	 *
	 * @param Request $request
	 * @return void
	 */
	public function upload(Request $request){
		$type = $request->input('type', 'images');

		try {
			switch ($type) {
				case 'avatar':
					$this->data['data'] = $this->avatar($request);
					break;
				case 'images':
					$this->data['data'] = $this->images($request);
					break;
				case 'files':
					$this->data['data'] = $this->files($request);
					break;
				default:
					$this->data['data'] = $this->images($request);
					break;
			}
		} catch (\Throwable $th) {
			$this->data['code'] = 0;
			$this->data['message'] = $th->getMessage();
		}
		return response()->json($this->data);
	}

	/**
	 * @title 上传头像
	 *
	 * @param Request $request
	 * @return void
	 */
	protected function avatar(Request $request){
		$file = $request->file('file');

		if ($file->isValid()) {
			$ext = $file->extension();
			$name = $file->hashName();

			$path = $file->store('avatar/'.date('Ymd'));

			$data = [
				'path' => $path,
				'url' => Storage::disk()->url($path),
				'src' => Storage::disk()->url($path),
				'name'=> $name,
				'size'=> $file->getSize(),
				'ext' => $ext,
			];
			return $data;
		}else{
			throw new \Exception('上传失败');
		}
	}

	protected function images(Request $request){
		$file = $request->file('file');

		if ($file->isValid()) {
			$ext = $file->extension();
			$name = $file->hashName();

			$path = $file->store('images/'.date('Ymd'));

			$data = [
				'path' => $path,
				'url' => Storage::disk()->url($path),
				'src' => Storage::disk()->url($path),
				'name'=> $name,
				'size'=> $file->getSize(),
				'ext' => $ext,
			];
			return $data;
		}else{
			throw new \Exception('上传失败');
		}
	}

	protected function files(Request $request){
		$file = $request->file('file');

		if ($file->isValid()) {
			$ext = $file->extension();
			$name = $file->hashName();

			$path = $file->store('files/'.date('Ymd'));

			$data = [
				'path' => $path,
				'url' => Storage::disk()->url($path),
				'src' => Storage::disk()->url($path),
				'name'=> $name,
				'size'=> $file->getSize(),
				'ext' => $ext,
			];
			return $data;
		}else{
			throw new \Exception('上传失败');
		}
	}
}