<?php
declare (strict_types=1);
namespace library\utils;
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-31 15:18
// +----------------------------------------------------------------------

use Qiniu\Storage\UploadManager;

class Qiniu {

    private $qiniu = null;

    public $config = array();

    private $error = null;


    /**
     * 基本配置
     * @param type $conf
     * <p>
     * array(
     * 'accessKeyId'     => '',
     * 'accessKeySecret' => '',
     * 'endpoint'        => '',
     * 'bucket'          => ''
    );
     * </p>
     */
    public function __construct($conf = array()) {
        $c = config('qiniu');
        foreach($c as $k=>$v){
            if(isset($conf[$k])){
                $this->config[$k] = $conf[$k];
            } else {
                $this->config[$k] = $v;
            }
        }

        try {
            $this->qiniu = new \Qiniu\Auth($this->config['accessKeyId'],
                $this->config['accessKeySecret']);

        } catch (Exception $ex) {
            $this->error = $ex->getMessage();
            $this->log_result($ex->getMessage(), $this->daatadir.'error');
        }

    }


    /**
     * 获取qiuniu信息
     * @global \OSS\OssClient $_A
     */
    public  function getqiniu() {
        return $this->qiniu;
    }

    /**
     * 获取bucket信息
     * @return type
     */
    public function getBucketName(){
        return $this->config['bucket'];
    }


    /*
* 获取预地址
**/
    public function getYuFile($path,$exp = 'jpg'){
        $object = $this->mk_str().'.'.$exp;
        $os_path = $path.DIRECTORY_SEPARATOR.date('Y').DIRECTORY_SEPARATOR.date('m').DIRECTORY_SEPARATOR.date('d').DIRECTORY_SEPARATOR;
        return $os_path.$object;
    }


    /**
     * 发送短信
     * @param $template_id
     * @param $mobiles
     * @param null $parameters
     */
    public function sendSms($mobiles,$template_id,$parameters = null){
        $sms = new \Qiniu\Sms\Sms($this->qiniu);
        $rAr = [];
        try {
            $d = $sms->sendMessage($template_id, [$mobiles], $parameters);
            if($d[1] instanceof Qiniu\Http\Error) {
                $dObj = $d[1];
                $rAr['Code'] = 'error';
                $rAr['Message'] = $dObj->message();
            } else {
                $rAr['Code'] = 'OK';
                $rAr['Message'] = '';
            }
        }catch (\Exception $e) {
            $rAr['Code'] = 'error';
            $rAr['Message'] = $e;
        }
        return $rAr;
    }

    /**
     * 上传文件 | 内容写入
     * @param type $path 目录
     * @param type $content 内容
     * @param type $type 后缀
     */
    public function updateFileContent($path,$content,$type = 'jpg',$file = ''){
        $type = strtolower($type);
        if($type == 'jpeg') $type = 'jpg';
        $object = '';
        if(empty($file)) {
            $object = $this->mk_str().'.'.$type;
            $os_path = $path.'/'.date('Y').'/'.date('m').'/'.date('d').'/';
        } else {
            $os_path = $path.'/' . $file;
        }



        $token = $this->qiniu->uploadToken($this->config['bucket']);

        $uploadMgr = new \Qiniu\Storage\UploadManager();

        list($ret, $err) = $uploadMgr->put($token, $os_path.$object, $content);


        $r['status'] = 0;
        if ($err !== null) {
            $r['status'] = 0;
            $this->error = $err;
        } else{
            $r['status'] = 1;
            $r['url'] = $this->config['endpoint'].$ret['key'];
        }
        return $r;
    }

    /**
     * 上传文件
     * @param type $path 目录
     * @param type $name 上传文件名称【后缀记录】
     * @param type $files 上传实际文件
     * @param type $ext 限制后缀名
     * @return boolean
     */
    public function updateFile($path,$name,$files,$ext = array('jpg','png','gif')) {
        if (empty($files)) {
            $this->error = '没有上传的文件！';
            return false;
        }

        $file['ext']    = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        if($file['ext'] == 'jpeg'){
            $file['ext'] = 'jpg';
        }


        if(!in_array($file['ext'], $ext)){
            $this->error = '上传格式发生错误！';
            return false;
        }

        if(!file_exists($files)){
            $this->error = '上传文件不存在！';
            return false;
        }



        $object = $this->mk_str().'.'.$file['ext'];

        $os_path = $path.'/'.date('Y').'/'.date('m').'/'.date('d').'/';

        $token = $this->qiniu->uploadToken($this->config['bucket']);

        $uploadMgr = new \Qiniu\Storage\UploadManager();

        list($ret, $err) = $uploadMgr->putFile($token, $os_path.$object, $files);


        $r['status'] = 0;
        if ($err !== null) {
            $r['status'] = 0;
            $this->error = $err;
        } else{
            $r['status'] = 1;
            $r['url'] = $this->config['endpoint'].$ret['key'];
        }
        return $r;
    }



    /**
     * 上传文件[带压缩]
     * @param $path 保存带头前缀
     * @param $name 文件名
     * @param $files 上传文件
     * @param int $type 压缩情况
     * @param array $ext 上传后缀
     */
    public function updateFileThum($path,$name,$files,$type = 0,$ext = array('jpg','png','gif','zip','mp4')){
        $thum = array(
            0 => '320',
            1 => '100',
            2 => '800'
        );

        if (empty($files)) {
            $this->error = '没有上传的文件！';
            return false;
        }

        $file['ext']    = strtolower(pathinfo($name, PATHINFO_EXTENSION));


        if(!in_array($file['ext'], $ext)){
            $this->error = '上传格式发生错误！';
            return false;
        }

        if(!file_exists($files)){
            $this->error = '上传文件不存在！';
            return false;
        }
        //文件名
        $file_str = $this->mk_str();

        $object = $file_str.'.'.$file['ext'];

        $thum_obj = $file_str .'_' . $thum[$type] . '.'.$file['ext'];

        $os_path = $path.'/'.date('Y').'/'.date('m').'/'.date('d').'/';

        $token = $this->qiniu->uploadToken($this->config['bucket']);

        $uploadMgr = new UploadManager();

        list($ret, $err) = $uploadMgr->putFile($token, $os_path.$object, $files);

        if (empty($err)) {
            $jh_ar = array('jpg','png','gif');
            if(in_array($file['ext'], $jh_ar)) {
                //进行持久化操作
                $this->Fop($os_path . $object, $os_path . $thum_obj, $thum[$type]);
            }
            $r['status'] = 1;
            $r['url'] = $this->config['endpoint'] . $ret['key'];
        } else{
            $r['status'] = 0;
            $this->error = $err;
        }

        return $r;
    }

    /**
     * 上传文件【】
     **/
    public function TupdateFile($newFile,$name,$files){
        if (empty($files)) {
            $this->error = '没有上传的文件！';
            return false;
        }

        $token = $this->qiniu->uploadToken($this->config['bucket']);
        $uploadMgr = new \Qiniu\Storage\UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $newFile, $files);

        $r['status'] = 0;
        if ($err !== null) {
            $r['status'] = 0;
            $this->error = $err;
        } else{
            $r['status'] = 1;
            $r['url'] = $this->config['domain'].$ret['key'];
        }
        return $r;
    }


    /**
     * 持久化操作
     * @param $key
     * @param $savekey
     * @param $daima
     */
    public function Fop($key,$savekey,$type = 320){

        if($type == 320){
            $daima = 'imageView2/1/w/320/h/320/q/100|imageslim';
        }
        $pipeline = 'mg_51';
        $pfop = new \Qiniu\Processing\PersistentFop($this->qiniu,$this->config['bucket'],$pipeline,"http://www.mmgg.com/api", false);
        $fops = $daima."|saveas/" . \Qiniu\base64_urlSafeEncode($this->config['bucket'] . ":".$savekey);
        list($id, $err) = $pfop->execute($key, $fops);
    }

    /**
     * @param $obj
     */
    public function watermark($obj){
        $jh_ar = array('jpg','png','gif');
        $expAr = explode('.',$obj);
        $img = '';
        $exp = end($expAr);
        if(in_array($exp, $jh_ar)) {
            $fileAr = explode('/',$obj);
            $fileName = end($fileAr);
            $imgPath = str_replace($fileName,'',$obj);
            $img = md5('watermark'.$fileName).'.'.$exp;
            //进行持久化操作
            $this->FopSyin($obj, $imgPath.$img);
        }
        return $imgPath.$img;
    }

    //

    /**
     * 持久化操作
     * @param $key
     * @param $savekey
     * @param $daima
     */
    public function FopSyin($key,$savekey){
        $daima = "imageView2/0/interlace/1/q/100|watermark/1/image/aHR0cHM6Ly9pbWcuZ3VhaW1laWRhLmNvbS9zeWluX2xvZ2luLnBuZw==/dissolve/64/gravity/SouthEast/dx/10/dy/10|imageslim";
        $pipeline = 'task0013';
        $pfop = new \Qiniu\Processing\PersistentFop($this->qiniu,$this->config['bucket'],$pipeline,"http://www.guaimeida.com/", false);
        $fops = $daima."|saveas/" . \Qiniu\base64_urlSafeEncode($this->config['bucket'] . ":".$savekey);
        list($id, $err) = $pfop->execute($key, $fops);
        var_dump($err);
    }


    private function mk_str(){
        $d = sha1((string)uniqid((string)mt_rand(),true));
        $str = '';
        for($i = 0;$i<strlen($d);$i++){
            $v = $d[$i];
            if(ctype_alpha($d)){
                $rnd_true = rand(0, 1);

                if($rnd_true){
                    $v = strtolower($d[$i]);
                } else {
                    $v = strtoupper($d[$i]);
                }
            }
            $str .= $v;
        }
        //防止内存加载不变
        $time = substr((string)time(),0,-6);
        $tarray = array('A','B','C','D','E','F','G','H','M','T');
        $vstr = '';
        for($i = 0;$i<strlen($time);$i++){
            if($time[$i]  % 2 == 0){
                $vstr .= 'X';
            } else {
                $vstr .= $tarray[rand(0, 9)];
            }
        }

        $str .= '-'.$vstr;

        return $str;
    }


    /**
     * 获取错误
     * @return type
     */
    public function getError(){
        return $this->error;
    }


    /**
     * 写入日志
     * @param type $word
     * @param type $name
     */
    private function log_result($word, $name) {

        $fp = fopen($name . "_log.txt", "a");
        flock($fp, LOCK_EX);
        fwrite($fp, $word . "\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }

}