<?php


namespace common\util;

use common\components\AjaxException;

class Upload
{
    public static function dealWithEventSourceDataFile($accident_id)
    {
        //******先存储图片，返回完整路径******//
        $dir = "../web/uploads/case/" . $accident_id; //设定存储上传文件的文件夹
        if (!is_dir($dir)) {
            mkdir($dir, 0777, TRUE); //如果文件夹目录不存在则创建
        }
        $fileName = $_FILES["file"]["name"]; //得到上传文件的名字
        $oldPath = $dir . "/" . $fileName; // 路径+旧文件名
        if ($_FILES['file']['size'] > 1073741824) {
            throw new AjaxException("文件大小{$_FILES['file']['size']}已超出1G限制！"); //通知前端图片大小非法
        }
        //生成文件名
        $path = "/uploads/case/" . $accident_id . "/" . rawurlencode($fileName);
        //完成上传
        move_uploaded_file($_FILES['file']['tmp_name'], $oldPath); // 上传
        //文件转码
        $env = require __DIR__ . '/../config/env/currentEnv.php';
        if (in_array($env, ["product"])) {
            /**
             * ffmpeg -i 111.wmv -c:v libx264 2.mp4
             * ffmpeg -i input.file -codec:a libmp3lame output.mp3
             */
            $type = explode(".", $fileName);
            if (strtolower($type[count($type) - 1]) == "avi" || strtolower($type[count($type) - 1]) == "wmv" || strtolower($type[count($type) - 1]) == "mkv") {
                $newFileName = "";
                foreach ($type as $typeValue) {
                    if ($typeValue != $type[count($type) - 1]) {
                        $newFileName .= $typeValue . ".";
                    }
                }
                $newFileName .= "mp4";
                $oriPath = __DIR__ . "/../../frontend/web/uploads/case/" . $accident_id . "/" . $fileName;
                $newPath = __DIR__ . "/../../frontend/web/uploads/case/" . $accident_id . "/" . $newFileName;
                $result = shell_exec("/usr/local/ffmpeg/bin/ffmpeg -i '$oriPath' -c:v libx264 '$newPath' 2>&1");
                $pathNew = "/uploads/case/" . $accident_id . "/" . rawurlencode($newFileName);
                return [$newFileName, $pathNew];
            } else if (strtolower($type[count($type) - 1]) == "wav") {
                $newFileName = "";
                foreach ($type as $typeValue) {
                    if ($typeValue != $type[count($type) - 1]) {
                        $newFileName .= $typeValue . ".";
                    }
                }
                $newFileName .= "mp3";
                $oriPath = __DIR__ . "/../../frontend/web/uploads/case/" . $accident_id . "/" . $fileName;
                $newPath = __DIR__ . "/../../frontend/web/uploads/case/" . $accident_id . "/" . $newFileName;
                $result = shell_exec("/usr/local/ffmpeg/bin/ffmpeg -i '$oriPath' -codec:a libmp3lame '$newPath' 2>&1");
                $pathNew = "/uploads/case/" . $accident_id . "/" . rawurlencode($newFileName);
                return [$newFileName, $pathNew];
            }
        }
        //返回数据
        return [$fileName, $path];
    }
}