<?php
namespace SRVX\Utils;


use Qiniu\Storage\UploadManager;
use Qiniu\Auth;
use Phalcon\Di\Injectable;
use SRVX\Model\SysCfg;

class Image extends Injectable{


     /**
     * 七牛云 AK
     * @var [type]
     */
    private $accessKey;

    /**
     * 七牛云 SK
     * @var [type]
     */
    private $secretKey;

    /**
     * 七牛云 仓库名
     * @var [type]
     */
    private $bucketName;

    /**
     * 七牛云 域名，需要做cname解析
     * @var [type]
     */
    public $domain;

    public function __construct()
    {
        $qiniuRow = $this->s->GeneralSet()->getSet(['file_access_key', 'file_bucket', 'file_bucket_host', 'file_secret_key']);

        # 暂时没有集群，固定用嗨如意的七牛云测试
        $this->accessKey    = $qiniuRow['file_access_key'];
        $this->secretKey    = $qiniuRow['file_secret_key'];
        $this->bucketName   = $qiniuRow['file_bucket'];
        $this->domain       = $qiniuRow['file_bucket_host'];
    }

    public function getUploadToken($expires = 3600, $isCallBack = false, $args = [])
    {
        if (!empty($isCallBack)) {
            $args['time'] = time();
            $sign = $this->createSign($args);

            $callbackBody = [
                'key'        => '$(key)',
                'hash'       => '$(etag)',
                'fsize'      => '$(fsize)',
                'bucket'     => '$(bucket)',
                'name'       => '$(x:name)',
                'width'      => '$(imageInfo.width)',
                'height'     => '$(imageInfo.height)',
                'mime'       => '$(mimeType)',
                'fname'      => '$(fname)',
                'ext'        => '$(ext)',
                'uid'        => $args['uid'],
                // 'originName' => $args['originName'],
                'saveName'   => $args['saveName'],
                'showName'   => $args['showName'],
//                'fileId'     => $args['fileId'],
                'sign'       => $sign,
                'time'       => $args['time'],
            ];

            $host   = $this->request->getServer('HTTP_HOST');
            $scheme = $this->request->getScheme();

            $policy = [
                'callbackUrl'      => $scheme . '://' . $host . '/CallBack/uploadCallBack',
                'callbackBody'     => json_encode($callbackBody, JSON_UNESCAPED_UNICODE),
                'callbackBodyType' => 'application/json'
            ];
        }
        $auth           = new Auth($this->accessKey, $this->secretKey);
        $uploadToken    = $auth->uploadToken($this->bucketName, null, $expires, ($policy ?? null), true);

        return $uploadToken;
    }



    public function delFile($delList)
    {
        if (empty($delList)) {
            return ['status' => false, 'msg' => '删除内容为空'];
        }

        $auth          = new Auth($this->accessKey, $this->secretKey);
        $config        = new \Qiniu\Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);

        # 每次最多不能超过1000个
        # demo $delList = ['qiniu.mp4'];
        $ops = $bucketManager->buildBatchDelete($this->bucketName, $delList);
        list($ret, $err) = $bucketManager->batch($ops);

        if ($err) {
            return ['status' => false, 'msg' => $err->getResponse()->error];
        } else {
            # response success [0 => ['code' => '200']]
            return ['status' => true];
        }
    }



    public function uploadFile($localFile, $token = '', $fileName = '')
    {
        if (empty($token)) {
            $token = self::getUploadToken();
        }

        if (!empty($fileName)) {
            list($ret, $err) = (new UploadManager)->putFile($token, $fileName, $localFile);
        } else {
            list($ret, $err) = (new UploadManager)->putFile($token, null, $localFile);
        }
        if ($err !== null) {
            throw new \Exception(($err->getResponse())->error);
        } else {
            return $ret['key'];
        }
    }


    public function getHash()
    {
        $chars  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()+-';
        $random = $chars[mt_rand(0,73)].$chars[mt_rand(0,73)].$chars[mt_rand(0,73)].$chars[mt_rand(0,73)].$chars[mt_rand(0,73)];//Random 5 times
        $content = uniqid() . $random;
        return sha1($content); 
    }


    public function createSign($data)
    {
        $signData = [
            'accessKey'  => $this->accessKey,
            'secretKey'  => $this->secretKey,
            'time'       => $data['time'],
            'uid'        => $data['uid'],
            // 'originName' => $data['originName'],
            'saveName'   => $data['saveName'],
        ];

        ksort($signData);

        $sign = strtoupper(md5(http_build_query($signData)));

        return $sign;
    }

}