<?php
/**
 * @Copyright (c) 2019  XIGU Inc. All rights reserved.
 * @Link https://www.vlcms.com
 * @License江苏溪谷网络科技有限公司版权所有
 */

namespace app\common\logic;

use think\Env;

class Upload
{
    //上传文件最大字节
    protected $file_max_size;

    //文件后缀，多个用逗号分割或者数组
    protected $file_ext;

    //文件MIME类型，多个用逗号分割或者数组
    protected $file_mime_type;

    //文件保存路径
    protected $save_path;


    public function __construct()
    {
        $this -> file_max_size = '2048000';
        $this -> file_ext = 'jpg,png,jpeg,gif';
        $this -> file_mime_type = '';
        $this -> save_path = env('root_path') . 'public/upload/';
        $this -> path_name = 'images';
    }


    /**
     * @单图上传
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/5/15 14:26
     */
    public function oneImgUpload()
    {
        $result = ['code' => '200', 'msg' => '', 'data' => []];
        $this -> path_name = 'images';
        $this -> save_path = $this -> save_path . $this -> path_name;
        $fileInfo = $this -> upload();
        if (!empty($fileInfo)) {
            $result['data'] = $fileInfo;
        }
        return $result;
    }

    /**
     * @批量绑定渠道模板上传
     *
     * @author: zsl
     * @since: 2019/6/17 16:54
     */
    public function uploadChannelTpl()
    {
        $result = ['code' => '200', 'msg' => '', 'data' => []];
        $this -> path_name = 'channelBind';
        $this -> save_path = $this -> save_path . $this -> path_name;
        $this -> file_ext = 'xls,xlsx';
        $fileInfo = $this -> upload();
        if (!empty($fileInfo)) {
            $result['data'] = $fileInfo;
        }
        return $result;
    }

    /**
     * @文件上传
     *
     * @author: zsl
     * @since: 2019/5/15 14:29
     */
    public function fileUpload()
    {
        $result = ['code' => '200', 'msg' => '', 'data' => []];
        return $result;
    }


    /**
     * @单个文件上传
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/5/15 15:49
     */
    private function upload()
    {
        $res = [];
        // 获取表单上传文件 例如上传了001.jpg
        $file = request() -> file('file');
        if (empty($file)) {
            return false;
        }
        $info = $file -> validate(['size' => $this -> file_max_size, 'ext' => $this -> file_ext])
                -> move($this -> save_path);
        if ($info) {
            $res['fileName'] = $info -> getFilename();
            $res['saveName'] = str_replace('\\', '/', $info -> getSaveName());
            $res['thumbnail'] = get_image_url($res['saveName'], $this -> path_name);
            $res['ext'] = $info -> getExtension();
        } else {
            // 上传失败获取错误信息
            $res['error'] = $file -> getError();
        }
        return $res;
    }


}