<?php
use Lib\Response;
use Lib\Request;
if(!function_exists('set_header')){
    function set_header($key=null,$value=null){
        static $header=[];
        if($key)$header[$key]=$value;
        return $header;
    }
}
/**
 * Created by daniel
 * User: Daniel
 * Date: 2020/3/14
 * Time: 11:19
 */
Page::$need_view =false;
$r=Request::instance();
$wid=$r->param('wid',0);
$wid = $wid ? $wid : Session::get('wid');

if(!$wid){
    sendError("参数错误");
}
//获取代理商oss配置
$admin = get_user_agency();
$request = Request::instance();
$type = $request->param('type');
//默认的回调
$errCall=function ($msg = 'Error', $data = null, $exts = []){
    return Response::create(error($msg , $data , $exts),'json',200,set_header())->send();
};
$succCall=function ($msg = 'OK', $data = null, $exts = []){
    return Response::create(success($msg , $data , $exts),'json',200,set_header())->send();

};
//区分类型***这里根据前端不同type类型 返回不同的结构数据
switch ($type){
    case 'img':
        $field = 'img'; //上传字段
        $rules=['size' =>1024 * 1024*10 , 'ext' => "jpeg,jpg,png,bmp,gif", 'type' => getMimeTypeByExt('image')] ;
        $save_path = 'img/'.date('ym');

        break;
    case 'audio':
        $field = 'audio';
        $rules=['size' =>1024 * 1024*10 , 'ext' => "mp3", 'type' => getMimeTypeByExt('audio')] ;
        $save_path = 'audio/'.date('ym');
        break;
    case 'image/jpeg'://一般不会用到此类型除了前端的富文本编辑插件
        //这里按照前端约定重写返回函数
        $field = 'file'; //上传字段
        $rules=['size' =>1024 * 1024*2 , 'ext' => "jpeg,jpg,png,bmp,gif", 'type' => getMimeTypeByExt('image')] ;
        $save_path = 'img/product/'.date('ym');
        $errCall=function($msg = 'Error', $data = null, $exts = []){
            return myError($msg , $data , $exts);
        };
        $succCall=function($msg = 'OK', $data = null, $exts = []){
            return mySuccess($msg , $data , $exts);
        };
        break;

    default:
        $field = 'img';
        $rules=['size' =>1024 * 1024 , 'ext' => "jpeg,jpg,png,bmp,gif", 'type' => getMimeTypeByExt('image')] ;
        $save_path = 'img/'.date('ym');
        break;
}

$bucketName = $admin->bucket_name;

//本地上传
$file=$request->file($field);
if(!$file){
    return $errCall("上传文件不存在");
}
$tmp_name=$file->getInfo('tmp_name');

$md5 = md5_file($tmp_name);
//签名 进行是否存在验证
$save = (new \Model('imglib'))->find(['wid' => $wid, 'type' => $type, 'md5' => $md5]);

if($save->id){
    return $succCall('上传成功', ['file_url'=>$save->url]);
}

$check_re = $file->check($rules);
if (!$check_re) return $errCall('文件不合法:' . $file->getError());
$true_path = pub_path($save_path);
is_dir($true_path) or mkdir($true_path, 0751, true);
$info = $file->move($true_path);
if ($info) {
    $fileName=str_replace('\\','/',$info->getSaveName());

}else{
    return $errCall('上传失败:'.$file->getError());
}
// 判断是否需要对接阿里OSS
$filePath=$save_path.'/'.$fileName;
$imgTruePath=pub_path($filePath);
if (!$admin->oss_status && !$admin->qiniu_status) {
    $is_oss = 0;
    $is_qiniu = 0;
    $realUrl = get_host($filePath);
} else if ($admin->oss_status) {
    $is_oss = 1;
    $is_qiniu = 0;
    // 对接阿里OSS，本地文件上传到OSS，得到云地址
    require(app_path("/fun/aliyun-oss/autoload.php"));
    try {
        $ossClient = new \OSS\OssClient($admin->oss_id, $admin->oss_secret, $admin->oss_endpoint);
        // 判断存储空间是否存在
        if (!$ossClient->doesBucketExist($bucketName)) {
            $ossClient->createBucket($bucketName, \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ);
        } else {
            $ossClient->putBucketAcl($bucketName, \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ);
        }
        $uploadOssRes = $ossClient->uploadFile($bucketName, $fileName, $imgTruePath);
        $realUrl = $uploadOssRes['info']['url'];
        if (!$realUrl) {
            // 没获取到Url
            return $errCall('上传失败，请重试');
        }
    } catch (\OSS\Core\OssException $e) {
        return $errCall('上传到阿里云OSS失败，请联系代理商检查配置：' . $e->getMessage());
    }
} else if ($admin->qiniu_status) {
    $is_qiniu = 1;
    $is_oss = 0;
    require(app_path( "/fun/qiniu-oss/autoload.php"));
    $accessKey = $admin->qiniu_key;
    $secretKey = $admin->qiniu_secret;
    $auth = new \Qiniu\Auth($accessKey, $secretKey);
    $bucket = $admin->qiniu_bucket_name;
    $token = $auth->uploadToken($bucket);
    $filePath = $imgTruePath;
    $key = $fileName;
    $uploadMgr = new \Qiniu\Storage\UploadManager();
    list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
    if ($err !== null) {
        return $errCall('上传到七牛失败，请联系代理商检查配置');
    }
    $realUrl = 'http://' . $admin->qiniu_domain . '/' . $ret['key'];
}
// 存入数据库，把path返回到前端
if (!$save->id) {
    $save->wid = $wid;
    $save->is_oss = $is_oss;
    $save->is_qiniu = $is_qiniu;
    $save->type = $type;  // 商品图片
    $save->url = $realUrl;
    $save->md5 = $md5;
    $save->ctime = time();
    $save->save();
}
return $succCall('上传成功', ['file_url'=>$realUrl]);


/**
 * 商家后台普通图片上传
 * @param Request $request
 * @return array
 * @throws \Exception
 */
/**
 *给上传插件返回的错误信息
 * @param string $msg
 * @param null $data
 * @param array $exts
 * @return Response|Response\Html|Response\Json|array
 */
function  myError($msg = 'Error', $data = null, $exts = []){
    return  Response::create([
        'status' => 0,
        'msg' => $msg,
        'data' => $data,
    ],'json',200,set_header())->send();//这样是方便设置方便返回头部信息避免header send问题


}
/**
 * 给上传插件返回的成功信息
 * @param string $msg
 * @param null $data
 * @param array $exts
 * @return Response|Response\Html|Response\Json|array
 */
function mySuccess($msg = 'OK', $data = null, $exts = []){
    return  Response::create([
        'status' => 1,
        'msg' => $msg,
        'url'=>$data['url'],
        'data' => $data,
    ],'json',200,set_header())->send();//这样是方便设置方便返回头部信息避免header send问题
}

