<?php
namespace app\admin\controller;
/**
 * @title 图片上传接口
 * @desc
 * @author Rock
 * @version 1.0
 * @icon fa fa-file-image-o
 */

use think\Exception;
use upload\Uploader;
use app\common\model\base\Upload as UploadModel;
class Upload extends Base
{
    /** 无需登录的方法 */
    protected $noNeedLogin = ['getMime'];
    /**
     * @title: 自定义上传配置
     * @desc: 此处的配置会覆盖upload\Uploader类里的配置
     * @return {*}
     * @author: Rock
     * @method: POST
     * @Date: 2023-05-18 15:00:44
     */
    private $Config = [
        'attach_format_image'       =>  'jpg,jpeg,png,gif,bmp',
        'attach_format_image_size'  =>  '2MB',
        'attach_format_video'       =>  'mp4,3gp,avi,mpeg',
        'attach_format_video_size'  =>  '50MB',
        'attach_format_audio'       =>  'mp3,wav',
        'attach_format_audio_size'  =>  '5MB',
        'attach_format_file'        =>  'xls,xlsx,txt',
        'attach_format_file_size'   =>  '2MB',
        'allowExts'                 =>  ['jpg','png','jpeg','bmp','pdf','xls','doc','xlsx','docx','zip'],//允许上传的文件类型
    ];
    public function initialize()
    {
        parent::initialize();
    }
    /**
    * @title: 获取MIME类型列表
    * @desc:
    * @param {}
    * @return {}
    * @Author: Rock
    * @Date: 2021-05-17 14:49:01
    * @LastEditTime: Do not edit
    */
	public function getMime()
	{
		$mimes = Uploader::$mimes;
		return res(1,"获取成功",$mimes);
	}
    /**
     * @title 文件上传接口
     * @desc 文件上传接口,注意大于10M时,不会返回base64;图片文件会自动生成预览图,预览图文件命名为原图文件名拼接.prev加.后缀,如123.jpg,预览图为123.jpg.prev.jpg
     * @method GET/POST
     * @param {string} {file} {} {上传的文件}
     * @return {string} {data} {} {上传成功后的文件}
     * @author Rock
     */
    public function index()
    {
        try {
            $mimes = Uploader::$mimes;
            //上传文件是否压缩
            $Compress=input('Compress')??0;
            $this->Config['Compress'] = $Compress;
            $upload 			= new Uploader($this->Config);// 实例化上传类
            if(!$upload->upload()) {
                $errormsg = $upload->getErrorMsg();
                WLog('Uploader',$errormsg);
                return res(2,$errormsg);
            }else{
                $info 				= $upload->getUploadFileInfo();
                $saveData = [];
                $hashAry = array_column($info,'hash');
                $list = UploadModel::where('md5','IN',$hashAry)->select()->toArray();
                $list = array_column($list,null,'md5');
                foreach($info as &$file){
                    // 文件小于10M时返回base64,大于则不返回
                    $imgurl=str_replace(public_path(),'',$file['savepath']).$file['savename'];
                    if($file['size']<5242880){
                        $base64 = file2base64($file['savepath'].$file['savename']);
                        $file['base64']=$base64;
                    }
                    $file['src'] = DS.$imgurl;
                    $file['fullpath'] = WEBURL.DS.$imgurl;
                    if(!isset($list[$file['hash']])){
                        $saveData[] = [
                            'name'  =>  $file['name'],
                            'savename'=>$file['savename'],
                            'size'=>$file['size'],
                            'ext'=>strtolower($file['extension']),
                            'path'=>$file['src'],
                            'fullpath'=>$file['savepath'].$file['savename'],
                            'md5'=>$file['hash'],
                            'type'  =>  $file['type'],
                            'uid'   =>  $this->userinfo['user_id']
                        ];
                    }else{
                        unlink($file['savepath'].$file['savename']);
                        $oldFile = $list[$file['hash']];
												$oldFile['path'] = str_replace('\\',"/",$oldFile['path']);
                        $file['src'] = $oldFile['path'];
                        $file['savename'] = $oldFile['savename'];
                        $file['fullpath'] = WEBURL.$oldFile['path'];
                    }
                }
                if(!empty($saveData)){
                    (new UploadModel)->saveAll($saveData);
                }
                return res(1,'上传成功',$info);
            }
        }catch (\Exception $e){
            WLog('Uploader',$e->getFile().' '.$e->getLine().':'.$e->getMessage());
            return res(2,'上传失败',$e->getFile().' '.$e->getLine().':'.$e->getMessage());
        }
    }
    /**
     * @title: 通过Md5检查文件是否曾经上传过
     * @desc:
     * @param {string} {md5} {必传} {文件MD5值}
     * @return {*}
     * @Author: Rock
     * @Date: 2022-02-22 19:09:19
     * @LastEditTime: Do not edit
     */
    public function checkMd5($md5='')
    {
        $info = UploadModel::where('md5',$md5)->find();
         $mimeList= Uploader::$mimes;
        if($info){
            $ext = strtolower($info->ext);
            $data = [
                'base64'    =>  in_array($ext,['jpg','png','jpeg','gif'])?file2base64($info->fullpath):'',
                'extension' =>  $info->ext,
                'fullpath'  =>  WEBURL.$info->path,
                'hash'      =>  $info->md5,
                'key'       =>  'file',
                'mime'      =>  isset($mimeList[$ext])?$mimeList[$ext]:'',
                'name'      =>  $info->name,
                'savename'  =>  $info->savename,
                'savepath'  =>  $info->fullpath,
                'size'      =>  $info->size,
                'src'       =>  $info->path,
            ];
						// 如果不是当前用户上传的,给当前用户创建一份上传记录,以便当前用户在文件库里使用
						$newData = $info->toArray();
						unset($newData['id']);
						$newData['uid'] = $this->userinfo['user_id'];
						UploadModel::create($newData);
            return res(1,'已上传',$data);
        }else{
            return res(1,"未上传");
        }
    }
    /**
     * @title: 获取已上传文件列表
     * @desc: 描述
     * @param {int} {pageNo} {1} {页码}
     * @param {int} {pageSize} {20} {每页数量}
     * @return {*}
     * @author: Rock
     * @method: POST
     * @Date: 2023-04-10 10:55:39
     */
    public function getList(int $pageNo=1,int $pageSize=20)
    {
        $data = $this->request->param();
        $where = [];
        if(!$this->userinfo['is_developer']){
            $where[] = ['uid','=',$this->userinfo->user_id];
        }
        if(!empty($data['keyword'])){
            $keyword = $data['keyword'];
            $where[] = ['name|savename','LIKE',"%$keyword%"];
        }
        if(!empty($data['type'])){
            $where[] = ['type','=',$data['type']];
        }
        $res = UploadModel::where($where)->paginate(['page'=>$pageNo,'list_rows'=>$pageSize]);
        $list = $res->items();
        $total = $res->total();
        return pageRes(1,"获取成功",$total,$list,$where);
    }
    /**
     * @title: 获取可选项
     * @desc: 描述
     * @return {*}
     * @author: Rock
     * @method: POST
     * @Date: 2023-04-10 11:37:38
     */
    public function getOptions()
    {
        $data = [
            'typeList'  =>  UploadModel::typeList(),
        ];
        return res(1,"获取成功",$data);
    }
  /**
   * @title: 删除上传文件
   * @desc: 描述
   * @param {int} {id} {} {上传文件ID}
   * @return {*}
   * @author: Rock
   * @method: POST
   * @Date: 2023-06-08 14:42:45
   */
		public function doDelete(int $id)
		{
			$info = UploadModel::find($id);
			try{
				if($info){
					if(file_exists($info->fullpath)){
						@unlink($info->fullpath);
					}
					$prePath = $info->fullpath.'.prev.jpg';
					if(file_exists($prePath)){
						@unlink($prePath);
					}
				}
			}catch(\Exception $e){
				$msg = $e->getMessage();
				WLog('UploadDelete',$msg);
				if(false!==strpos($msg,'file_exists(): open_basedir restriction in effect')){
					return res(2,"删除失败:网站开启防跨站攻击,无法删除文件,请检查是否属于本站文件");
				}
			}
			$info->delete();
			return res(1,"删除成功");
		}
}