<?php
namespace app\admin\controller;

use think\Controller;

use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

use app\common\model\Picture as PictureModel;

class Upload extends Controller
{
    public $accessKey;
    public $secretKey;
    public $domain;
    public $auth;
    public $bucket;
    public $token;
    public $UploadMgr;

    public function _initialize()
    {
        parent::_initialize();
        $this->accessKey = config('qiniu.accessKey');
        $this->secretKey = config('qiniu.secretKey');
        $this->domain = config('qiniu.domain');
        $this->bucket = config('qiniu.bucket');
        $this->auth = new Auth($this->accessKey, $this->secretKey);
        $this->token = $this->auth->uploadToken($this->bucket);
        $this->uploadMgr = new UploadManager();
    }

    public function single()
    {
        $file = request()->file('file');
        // 要上传文件的本地路径
        $filePath = $file->getRealPath();
        //后缀
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()), 0, 5).date('YmdHis').rand(0, 9999).'.'.$ext;
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $this->uploadMgr->putFile($this->token, $key, $filePath);
        if ($err !== null) {
            return json_encode(['error'=>1, 'msg'=>'上传失败', 'result'=>$err]);
        } else {
            $result['url'] = $this->domain.'/'.$ret['key'];
            return json_encode(['error'=>0, 'msg'=>'上传成功', 'result'=>$result]);
        }
    }


    /**
     * 保存文件到七牛云
     * @param  string $file [description]
     * @return [type]       [description]
     */
    public function sava($file='')
    {
        $result['error'] = 1;
        $result['msg'] = '上传文件到远程失败';
        $result['result'] = null;

        // 要上传文件的本地路径
        $filePath = $file->getRealPath();
        //后缀
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()), 0, 5).date('YmdHis').rand(0, 9999).'.'.$ext;
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $this->uploadMgr->putFile($this->token, $key, $filePath);
        if ($err !== null) {
            $result['result'] = $err;
            return $result;
        } else {
            $resource_model = model('resource');
            $resource_model->isUpdate(false)->data([
                'name' => $ret['key'],
                'ext' => $ext,
                'address' => $this->domain.'/'.$ret['key'],
                'use_num' => 1
            ])->save();
            $result['error'] = 0;
            $result['msg'] = '成功上传文件到远程';
            $result['result']['url'] = $this->domain.'/'.$ret['key'];
            return $result;
        }
    }
    public function savaAsync()
    {
        $name = input('post.name');
        $file =  input('file.')[$name];

        $result['result'] = null;

        // 要上传文件的本地路径
        $filePath = $file->getRealPath();
        $fileName = $file->getInfo('name');
        //后缀
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()), 0, 5).date('YmdHis').rand(0, 9999).'.'.$ext;
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $this->uploadMgr->putFile($this->token, $key, $filePath);
        if ($err !== null) {
            $result['error'] = $fileName.'上传到远程失败';
            $result['result'] = $err;
            return $result;
        } else {
            $resource_model = model('Resource');
            $server_id = $resource_model -> insertGetId(array(
                'name' => $ret['key'],
                'ext' => $ext,
                'address' => $this->domain.'/'.$ret['key'],
                'use_num' => 1
            ));
            $result['success'] = $fileName.'上传成功';
            $result['result']['server_id'] = $server_id;
            $result['result']['url'] = $this->domain.'/'.$ret['key'];
            return $result;
        }
    }
    public function deleteAsync()
    {
        $id = input('post.id');
        $res = model('Resource')->where("id", $id)-> delete();
        if ($res) {
          return array('code'=>0);
        }
        return array('code'=>0);
    }
    /**
     * 删除图片
     * @return [type] [description]
     */
    public function delete()
    {
        $picture = PictureModel::get(trim(input('post.key')));
        if ($picture) {
            if ($picture->delete()) {
                $pictures = PictureModel::where(['type'=>trim(input('param.type')), 'oid'=>trim(input('param.id'))])->select();
                $pics = array();
                foreach ($pictures as $k => $pic) {
                    $pics[$k]['id'] = intval($pic->id);
                    $pics[$k]['url'] = $pic->url;
                }
                return json_encode(['error'=>0, 'msg'=>'删除成功', 'pics'=>$pics]);
            }else{
                return json_encode(['error'=>1, 'msg'=>'删除失败']);
            }
        }else{
            return json_encode(['error'=>1, 'msg'=>'该图片不存在']);
        }
    }

    /**
     * 七牛云上传凭证
     * @return [type] [description]
     */
    public function uptoken()
    {
        $result['error'] = 0;
        $result['msg'] = '获取成功';

        // $policy = array(
        //     'callbackUrl' => 'http://your.domain.com/callback.php',
        //     'callbackBody' => 'filename=$(fname)&filesize=$(fsize)'
        // );
        // $uptoken = $auth->uploadToken($bucket, null, 3600, $policy);

        $auth = new Auth($this->accessKey, $this->secretKey);
        $upToken = $auth->uploadToken($this->bucket);
        $result['uptoken'] = $upToken;
        return json_encode($result);
    }
}
