<?php
/**
 * +------------------------------------------------------------
 * | 七牛云
 * +------------------------------------------------------------
 * | @author: zhx (10630650@qq.com)
 * | @create_time: 2018-03-09 22:58:06
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: zhx
 * | @last_modified_time: 2018-03-09 22:58:06
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\files\controller;

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Http\Client;
use Qiniu\Storage\UploadManager;

class Qiniu extends Module
{

    private $path;
    private $file_name;

    function __construct($path, $file_name, $file)
    {
        $this->path = $path ?: '';
        $this->file_name = $file_name;
        $this->file = $file;
        $this->ak = config('files.qiniu')['ak'];
        $this->sk = config('files.qiniu')['sk'];
        $this->bucket = config('files.qiniu')['bucket'];
        $this->domain = config('files.qiniu')['domain'];
    }

    /**
     * 上传文件
     */
    function upload()
    {
        $upManager = new UploadManager();
        $auth = new Auth($this->ak, $this->sk);
        $policy = [
            'key' => '$(key)',
            'hash' => '$(etag)'
        ];
        $token = $auth->uploadToken($this->bucket, $this->file_name, 3600, $policy, false);
        list($ret, $error) = $upManager->putFile($token, $this->file_name, $this->path);
        if (empty($error)) {
            $rs = [
                'name' => $ret['key'],
                'path' => $ret['key'],
                'url' => $this->domain . '/' . $ret['key'],
                'md5' => $ret['hash'],
                'size' => $this->file->getSize()
            ];
        } else {
            $rs = 0;
        }
        return $rs;
    }

    /**
     * 创建空间
     */
    function built_bucket($bucket = '')
    {
        if (empty($bucket)) {
            return json(['code' => 1, 'msg' => '空间名称不能为空']);
        }
        //$result = Client::post($url, $body, $header);
    }

    /**
     * 删除空间
     */
    function del_bucket($bucket = '')
    {
        if (empty($bucket)) {
            return json(['code' => 1, 'msg' => '空间名称不能为空']);
        }
        //$result = Client::post($url, $body, $header);
    }

}