<?php

namespace app\tencent\controller;

use fastphp\base\Controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use app\tencent\model\Agreement as AgreementModel;


class Index extends Controller
{
    private $accessKey = 'AfRhvJoAKL24ftGcHMor1WwSpVdular7L7X97JNY';
    private $secretKey = 'OyyU-6M45oDZAlVsf8fH0RFALGxTNHAT-yR6cmtU';
    private $bucket = 'zip9';
    public function upload()
    {
        $username = $this->userinfo['LoginName'];
        $userid = $this->userinfo['UserId'];
        $data = $_POST;
        $agreement_model = new AgreementModel;
        
        $agreement_data = [
            'user_id' => $userid,
            'username' => $username,
            'describe' => $data['describe'],
        ];

        $xieyi = $_FILES['xieyi'];
        
        $size_limit = 30 * 1024 * 1024;
        if ($xieyi['size']>$size_limit) {
            echo json_encode(['code' => -1,'msg'=>'文件过大，仅限30M']);
            die;
        }
        
        $auth = new Auth($this->accessKey, $this->secretKey);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 需要填写你的 Access Key 和 Secret Key
        // 构建鉴权对象
        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);
        // 要上传文件的本地路径
        $xieyi_filePath = $xieyi['tmp_name'];
        // 上传到存储后保存的文件名
        $xieyi_key = $username.'-'.time().'.png';
        if (isset($_FILES['yewu'])){
            $yewu = $_FILES['yewu'];
            if ($yewu['size']>$size_limit) {
                echo json_encode(['code' => -1,'msg'=>'文件过大，仅限30M']);
                die;
            }
            // 要上传文件的本地路径
            $filePath = $yewu['tmp_name'];
            // 上传到存储后保存的文件名
            $yewu_key = $username.'-'.time().'.mp4';
            // 调用 UploadManager 的 putFile 方法进行文件的上传。
            list($ret, $err) = $uploadMgr->putFile($token, $yewu_key, $filePath, null, 'application/octet-stream', true, null, 'v2');
            $agreement_data['yewu'] = 'http://zip.juip.com/'.$yewu_key;
        }
        
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $xieyi_key, $xieyi_filePath, null, 'application/octet-stream', true, null, 'v2');
        $agreement_data['xieyi'] = 'http://zip.juip.com/'.$xieyi_key;

        $agreement_model->add($agreement_data);
        
        if ($err !== null) {
            echo json_encode(['code' => -1,'msg'=>'上传失败']);
        } else {
            echo json_encode(['code' => 1,'msg'=>'上传成功']);
        }
    }
}