<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/13/013
 * Time: 16:14
 */

namespace common\helpers;
use Yii;

class ImageUtil
{
    /**
     * 文件保存根路径
     * @var string
     */
    public $basePath = '@webroot';
    /**
     * 文件保存根url
     * @var string
     */
    public $baseUrl = '@web';
    /**
     * 文件保存相对路径
     * @var string
     */
    public $savePath = 'upload';
    /**
     * a list of file name extensions that are allowed to be uploaded.
     * 定义允许上传的文件扩展名
     * @var array
     */
    public $extensions = [
        'image' => ['gif', 'jpg', 'jpeg', 'png', 'bmp'],
        'flash' => ['swf', 'flv'],
        'media' => ['swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'],
        'file' => ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'zip', 'rar', 'gz', 'bz2', 'pdf'],
    ];
    /**
     * the maximum number of bytes required for the uploaded file.
     * 最大文件大小
     * @var int
     */
    protected $_maxSize = 1000000;

    public function upload($image)
    {
        $base_path = rtrim(Yii::getAlias($this->basePath), '\\/') . '/';
        //文件保存目录路径
        $save_path = $base_path . rtrim($this->savePath, '\\/') . '/';
        //定义允许上传的文件扩展名
        $ext_arr = $this->extensions;
        //最大文件大小
        $max_size = $this->getMaxSize();
        // 新建文件夹
        $add_time = date("Ym", time());
        //$save_path = realpath($save_path) . '/';
        //PHP上传失败
        if (!empty($image['error'])) {
            switch ($image['error']) {
                case '1':
                    $error = '超过php.ini允许的大小。';
                    break;
                case '2':
                    $error = '超过表单允许的大小。';
                    break;
                case '3':
                    $error = '图片只有部分被上传。';
                    break;
                case '4':
                    $error = '请选择图片。';
                    break;
                case '6':
                    $error = '找不到临时目录。';
                    break;
                case '7':
                    $error = '写文件到硬盘出错。';
                    break;
                case '8':
                    $error = 'File upload stopped by extension。';
                    break;
                case '999':
                default:
                    $error = '未知错误。';
            }
            $this->alert($error);
        }
        //有上传文件时
        if (empty($image) === false) {
            //原文件名
            $file_name = $image['name'];
            //服务器上临时文件名
            $tmp_name = $image['tmp_name'];
            //文件大小
            $file_size = $image['size'];
            //检查文件名
            if (!$file_name) {
                $this->alert("请选择文件。");
            }
            //检查目录
            if (@is_dir($save_path) === false) {
                $this->alert("上传目录不存在。");
            }
            //检查目录写权限
            if (@is_writable($save_path) === false) {
                $this->alert("上传目录没有写权限。");
            }
            //检查是否已上传
            if (@is_uploaded_file($tmp_name) === false) {
                $this->alert("上传失败。");
            }
            //检查文件大小
            if ($file_size > $max_size) {
                $this->alert("上传文件大小超过限制。");
            }
            //获得文件扩展名
            $temp_arr = explode(".", $file_name);
            $file_ext = array_pop($temp_arr);
            $file_ext = trim($file_ext);
            $file_ext = strtolower($file_ext);
            //检查扩展名
            if (in_array($file_ext, $ext_arr['image']) === false) {
                $this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr['image']) . "格式。");
            }
            //新文件名
            $new_file_name = $this->generateUuid() . '.' . $file_ext;
            if (!file_exists($save_path.$add_time)) {
                mkdir($save_path.$add_time, 0777);
            }
            //移动文件
            $file_path = $save_path .$add_time. '/' . $new_file_name;
            if (move_uploaded_file($tmp_name, $file_path) === false) {
                $this->alert("上传文件失败。");
            }
            $file_url = '/'.$this->savePath. '/' .$add_time. '/' . $new_file_name;
            return $file_url;
        }
    }

    /**
     * 生成唯一UUID
     */
    protected function generateUuid()
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid  = substr($str,0,8);
        $uuid .= substr($str,8,4);
        $uuid .= substr($str,12,4);
        $uuid .= substr($str,16,4);
        $uuid .= substr($str,20,12);
        return $uuid;
    }

    /**
     * @param string $msg
     */
    protected function alert($msg)
    {
        header('Content-type: text/html; charset=UTF-8');
        echo json_encode(['error' => 1, 'message' => $msg]);
        exit;
    }
    /**
     * @return int
     */
    public function getMaxSize()
    {
        return $this->_maxSize;
    }
    /**
     * @param int $maxSize
     */
    public function setMaxSize($maxSize)
    {
        $this->_maxSize = intval($maxSize);
    }
}