<?php
namespace Upload\Lib\Store;

use Dever;
Dever::apply('sdk/qiniu', 'upload');

class Qiniu extends Core implements Config
{
    public $yun = true;
    /**
     * 创建文件和目录
     * 
     * @return mixed
     */
    public function save()
    {
        $config = Dever::db('upload/yun')->one($this->config['yun']);
        $accessKey = $config['appkey'];
        $secretKey = $config['appsecret'];
        $this->host = $config['host'];
        $auth = new \Qiniu\Auth($accessKey, $secretKey);
        $bucket = $this->config['bucket'];

        $policy = array(
            'callbackUrl' => 'http://your.domain.com/upload_verify_callback.php',
            'callbackBody' => 'filename=$(fname)&filesize=$(fsize)'
        );

        // 生成上传Token
        $token = $auth->uploadToken($bucket, null, 3600);
        // 构建 UploadManager 对象
        $upload = new \Qiniu\Storage\UploadManager();

        $this->getName();

        $file = $this->file;
        if ($this->config['cover'] == 3) {
            $this->name($this->output['file'] . '_' . microtime() . '_' . rand(0,1000))->file();
            $file = $this->file;
        }

        if ($this->base64) {
            list($ret, $err) = $upload->put($token, $file, $this->data['file']['tmp_name'], $param = null);
        } else {
            list($ret, $err) = $upload->putFile($token, $file, $this->data['file']['tmp_name'], $param = null);
        }

        if (isset($ret['hash']) && isset($ret['key'])) {

            $this->file = $ret['key'];
            $file = Dever::load('upload/file-name', array('where_name' => $this->name, 'where_upload' => $this->data['key'], 'rand' => time()));
            
            if (!$this->limit) {
                $data = Dever::curl($this->output['url'] . '?imageInfo');
                if ($data) {
                    $data = json_decode($data, true);
                    if (isset($data['width'])) {
                        $this->limit = array($data['width'], $data['height']);
                        $this->size = $data['size'];
                        $this->ext = '.' . $data['format'];
                    }
                }
            }
            
            if (isset($file) && $file) {
                $this->update($file['id']);
                
            } else {
                $this->insert();
            }

            return $this->output['url'];
        }
    }

    public function file()
    {
        if ($this->base64) {
            $data = pathinfo($this->data['pic']);
            $data['dirname'] = str_replace($this->host, '', $data['dirname']);
            $this->file = $data['dirname'] . '/' . $data['basename'] . $this->name . $this->ext;
        } else {
            $this->file = $this->path . $this->name . $this->ext;
        }

        $this->output['file'] = $this->file;
        $this->output['url'] = $this->host . $this->file;
        return $this->output['file'];
    }
    
    /**
     * water
     * 
     * @return mixed
     */
    public function handle_w($id)
    {
        $config = Dever::load('upload/pic_water-one', $id);
        if ($config) {
            $this->name .= '_w' . $id;
            
            $water = array('water'=> $config['water'], 'position'=> ($config['water_position'] ? $config['water_position'] : 1));
            
            $this->img()->mark($this->output['file'], $water, true, $this->file());
        }
    }

    /**
     * compress
     * 
     * @return mixed
     */
    public function handle_p($num, $source = false, $dest = false)
    {
        if (!$source) {
            $source = $this->output['file'];
        }

        if (!$dest) {
            if (strpos($this->name, '_p') !== false) {
                $temp = explode('_p', $this->name);
                $this->name = $temp[0];
            }

            $file = $this->output['file'];
            $url = $this->output['url'];

            $this->name .= '_p' . $num;
            $dest = $this->file();

            $this->output['file'] = $file;
            $this->output['url'] = $url;
        }

        $this->img()->setType('im');
        $this->img()->compress($source, $num, $dest);
    }
    
    /**
     * webp
     * 
     * @return mixed
     */
    public function handle_wp($num, $source = false, $dest = false)
    {
        if (!$source) {
            $source = $this->output['file'];
        }


        if (!$dest) {
            if (strpos($this->name, '_wp') !== false) {
                $temp = explode('_wp', $this->name);
                $this->name = $temp[0];
            }

            $file = $this->output['file'];
            $url = $this->output['url'];

            $this->ext = '.webp';
            $this->name .= '_wp' . $num;
            $dest = $this->file();

            $this->output['file'] = $file;
            $this->output['url'] = $url;
        }

        $this->img()->setType('im');
        $this->img()->webp($source, $num, $dest);
    }

    /**
     * thumb
     * 
     * @return mixed
     */
    public function handle_t($id, $source = false, $dest = false, $path = '')
    {
        $config = Dever::load('upload/pic_thumb-one', $id);
        if ($config) {

            if (!$source) {
                $source = $this->output['file'];
            }

            $dest = $source . '?imageView2/2/w/'.$config['width'].'/h/'.$config['height'];

            if (isset($config['compress']) && $config['compress'] > 0) {
                $dest = $dest . '/q/' . $config['compress'];
            }
        }
        return $dest;
    }
    
    /**
     * crop
     * 
     * @return mixed
     */
    public function handle_c($id, $source = false, $dest = false)
    {
        $config = Dever::load('upload/pic_crop-one', $id);
        
        if ($config) {

            if (!$source) {
                $source = $this->output['file'];
            }

            if (!$dest) {
                if (strpos($this->name, '_c') !== false) {
                    $temp = explode('_c', $this->name);
                    $this->name = $temp[0];
                }
                $this->name .= '_c' . $id;
                $dest = $this->file();
            }
            
            $size = $config['width'] . '_' . $config['height'] . '_2';

            $this->img()->crop($source, $size, false, true, $dest);
        }
    }
}