<?php

use App\Base\Base;
use Helpers\Aes;
use Api\PhpUtils\Http\Request;
use Api\PhpUtils\Redis\RedisUtil;
use App\Models\demo\mongo\Test;
use Api\PhpUtils\Common\Rsa;
use Api\PhpServices\Session\SessionManager;
use Helpers\DebugLog;
use Api\PhpUtils\Kafka\KafkaUtil;
use Api\PhpUtils\Cache\ApcuUtil;
use Api\PhpUtils\Cache\CacheUtil;
use Api\PhpServices\Doc\DocDynamic;

class TttController extends Base
{
    /**
     * @var Api\PhpUtils\Cache\CacheUtil;
     */
    protected $cache;

    public function kafkaAction()
    {
        $topicName = 'topicA';
        $setConfDrMsgCb = function ($kafka, \RdKafka\Message $message) {
            echo '打印消息:' . "\n";
            var_export($message);
            echo "\n";
            if($message->err){
                //@todo 生产失败的逻辑处理
            } else{
                //@todo 生产成功的逻辑处理
            }
        };
        $setErrorCbCallback = function ($kafka, $err, $reason) {
            echo sprintf("setErrorCb (error_ori:%s)(error: %s) (reason: %s)", $err, rd_kafka_err2str($err), $reason);
        };
        // $kafka = KafkaUtil::getInstance('test', ['context' => ['contextArr']]);
        // $ret = $kafka->produce('eee');
        $brokers = '127.0.0.1:9092';
        $kafka = KafkaUtil::getInstance();
        $ret = $kafka->setBrokers($brokers)->setTopicName('topicA')->produce('ccc');
        var_dump($ret);
        var_dump($kafka);
        exit;
        //设置brokers-支持数组或者字符串
        $kafka->setBrokers($brokers)
            //设置topic
            ->setTopicName($topicName)
            //setConfDrMsgCb--设置生产消息失败与成功的回调,默认初始化时会调用该事件,如果自定义后就会覆盖底层的事件
            ->setConfDrMsgCb($setConfDrMsgCb)
            //setConfErrorCb--设置错误回调,如若不设置默认会走该逻辑进行:\RdKafkaSdk\Core\Conf::defaultInit
            ->setConfErrorCb($setErrorCbCallback)
            //支持连贯用法生产多条数据并且是不同的topic
            ->run('message111', $topicName);

/**
object(Api\PhpUtils\Kafka\KafkaUtil)#17 (12) {
  ["serverName":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  string(0) ""
  ["producer":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  object(RdKafka\Producer)#22 (2) {
    ["error_cb":"RdKafka":private]=>
    NULL
    ["dr_cb":"RdKafka":private]=>
    NULL
  }
  ["conf":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  object(RdKafka\Conf)#18 (0) {
  }
  ["confSet":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  array(8) {
    ["socket.timeout.ms"]=>
    int(50)
    ["socket.blocking.max.ms"]=>
    int(50)
    ["topic.metadata.refresh.sparse"]=>
    bool(true)
    ["topic.metadata.refresh.interval.ms"]=>
    int(600)
    ["socket.nagle.disable"]=>
    bool(true)
    ["message.timeout.ms"]=>
    int(50)
    ["log_level"]=>
    int(4)
    ["internal.termination.signal"]=>
    int(23)
  }
  ["confFunction":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  array(2) {
    ["setDrMsgCb"]=>
    object(Closure)#20 (3) {
      ["static"]=>
      array(1) {
        ["context"]=>
        array(0) {
        }
      }
      ["this"]=>
      *RECURSION*
      ["parameter"]=>
      array(2) {
        ["$kafka"]=>
        string(10) "<required>"
        ["$message"]=>
        string(10) "<required>"
      }
    }
    ["setErrorCb"]=>
    object(Closure)#21 (2) {
      ["this"]=>
      *RECURSION*
      ["parameter"]=>
      array(3) {
        ["$kafka"]=>
        string(10) "<required>"
        ["$err"]=>
        string(10) "<required>"
        ["$reason"]=>
        string(10) "<required>"
      }
    }
  }
  ["topicConf":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  object(RdKafka\TopicConf)#19 (0) {
  }
  ["topicConfSet":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  array(1) {
    ["request.required.acks"]=>
    int(1)
  }
  ["topicConfFunction":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  array(0) {
  }
  ["brokers":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  string(14) "127.0.0.1:9092"
  ["topicName":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  string(6) "topicA"
  ["context":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  array(0) {
  }
  ["config":"Api\PhpUtils\Kafka\KafkaUtil":private]=>
  array(3) {
    ["viewlog"]=>
    array(2) {
      ["topic"]=>
      string(16) "dw_metro_pb_view"
      ["broker_list"]=>
      array(15) {
        [0]=>
        string(32) "c1-e14-120-24-23.yidian.com:9092"
        [1]=>
        string(32) "c1-e14-120-24-24.yidian.com:9092"
        [2]=>
        string(32) "c1-e14-120-24-25.yidian.com:9092"
        [3]=>
        string(32) "c1-e14-120-24-26.yidian.com:9092"
        [4]=>
        string(32) "c1-e14-120-24-27.yidian.com:9092"
        [5]=>
        string(31) "c1-e15-120-25-6.yidian.com:9092"
        [6]=>
        string(31) "c1-e15-120-25-7.yidian.com:9092"
        [7]=>
        string(31) "c1-e15-120-25-8.yidian.com:9092"
        [8]=>
        string(31) "c1-e15-120-25-9.yidian.com:9092"
        [9]=>
        string(32) "c1-e16-120-25-10.yidian.com:9092"
        [10]=>
        string(32) "c1-e16-120-25-17.yidian.com:9092"
        [11]=>
        string(32) "c1-e16-120-25-18.yidian.com:9092"
        [12]=>
        string(32) "c1-e17-120-25-19.yidian.com:9092"
        [13]=>
        string(32) "c1-e17-120-25-20.yidian.com:9092"
        [14]=>
        string(32) "c1-e17-120-25-21.yidian.com:9092"
      }
    }
    ["subscribe"]=>
    array(2) {
      ["topic"]=>
      string(15) "dw_metro_pb_api"
      ["broker_list"]=>
      array(15) {
        [0]=>
        string(32) "c1-e14-120-24-23.yidian.com:9092"
        [1]=>
        string(32) "c1-e14-120-24-24.yidian.com:9092"
        [2]=>
        string(32) "c1-e14-120-24-25.yidian.com:9092"
        [3]=>
        string(32) "c1-e14-120-24-26.yidian.com:9092"
        [4]=>
        string(32) "c1-e14-120-24-27.yidian.com:9092"
        [5]=>
        string(31) "c1-e15-120-25-6.yidian.com:9092"
        [6]=>
        string(31) "c1-e15-120-25-7.yidian.com:9092"
        [7]=>
        string(31) "c1-e15-120-25-8.yidian.com:9092"
        [8]=>
        string(31) "c1-e15-120-25-9.yidian.com:9092"
        [9]=>
        string(32) "c1-e16-120-25-10.yidian.com:9092"
        [10]=>
        string(32) "c1-e16-120-25-17.yidian.com:9092"
        [11]=>
        string(32) "c1-e16-120-25-18.yidian.com:9092"
        [12]=>
        string(32) "c1-e17-120-25-19.yidian.com:9092"
        [13]=>
        string(32) "c1-e17-120-25-20.yidian.com:9092"
        [14]=>
        string(32) "c1-e17-120-25-21.yidian.com:9092"
      }
    }
    ["test"]=>
    array(2) {
      ["topic"]=>
      string(6) "topicA"
      ["broker_list"]=>
      array(1) {
        [0]=>
        string(14) "localhost:9092"
      }
    }
  }
}
*/
    }

    
    public function docAction() {
        $obj = new DocDynamic(true);
        $docs = array(
        '06No4hkp'=>array('like'=>1,'down'=>2),
        '06No4hk1'=>array('comment_count'=>3,'up'=>4,'comment_like'=>'7'));
        // $set = $obj->incrCommentCount('06No4hkp');
        $set = $obj->setThumbsdown('06No4hkp', 1);
        var_dump($set);
        // $ret = $obj->get('08yidV11');
        $ret = $obj->get('06No4hkp');
        // $ret = $obj->get('news_b428c553fcb900ba3624385a818f1368');
        // $ret = $obj->gets(['news_b428c553fcb900ba3624385a818f1368']);
        // var_dump($obj);
        var_dump($ret);
        exit;
    }
    public function apcuAction() {

        // $prefix_key = ApcuUtil::add_prefix('prefix', 'key1');
        // var_dump($prefix_key);
        // $ret = ApcuUtil::apcu_store_one('prefix', 'key1', 'value1', 10);
        // $set = ApcuUtil::apcu_add_one('prefix', 'key1', 'value1', 3);
        // $set = ApcuUtil::apcu_add_multi('prefix', ['key1' => 'value2', 'key2' => 'value3'], null, 10);
        $set = ApcuUtil::apcu_store_multi('prefix', ['key1' => 'value1', 'key2' => 'value2'], null, 10);
        // $del = ApcuUtil::apcu_delete('prefix', 'key2');
        $get = ApcuUtil::apcu_fetch('prefix', 'key3', $success);
        // $get = ApcuUtil::apcu_fetch('prefix', ['key1', 'key2'], $success);
        var_dump($set);
        // var_dump($del);
        var_dump($get);
        // var_dump($success);
        exit;
    }

    public function redisAction() {

        // $arr = ['serverRegion'=> 'sh', 'serializer' => 'none', 'master'=> false];
        // var_dump('abc'.serialize($arr));
        // $str = 'abc'. json_encode($arr);
        // var_dump($str);
        // exit;



        $redis = RedisUtil::getInstance('api', ['serverRegion'=> 'sh', 'serializer' => 'none', 'master'=> true]);
        $redis = RedisUtil::getInstance('api', ['serverRegion'=> 'sh', 'serializer' => 'none', 'master'=> true]);
        // var_dump($redis);
        $get = $redis->hget('07IqF', 'Vcc');
        var_dump($get);
        exit;

        // echo 123456;exit;
        // codis 
        $redis = RedisUtil::getInstance('redis', ['serverRegion'=> 'wj', 'serializer' => 'none', 'master'=> true]);
        var_dump($redis);exit;
        $set = $redis->setex('ebbddse',20, 'value123');
        // $redis = RedisUtil::getInstance('redis', ['serverRegion'=> 'wj', 'serializer' => 'igbinary', 'master'=> false]);
        // $set = $redis->setex('ebbddse',200, ['value111', 'value222']);
        // $set = $redis->del('ebbddse');
        var_dump($set);
        $get = $redis->get('ebbddse');
        // $get = $redis->get('myAppName:ebbddse');
        var_dump($get);
         
        // Sentinel
        // $redis = RedisUtil::getInstance('sentinel', 'region2', true);
        // $ret = $redis->set('bbdadfsdd', 'sentinel');
        // $ret = $redis->get('bbdadfsdd');
        // $ret = $redis->get('myAppName:ebbddse');
        // var_dump($ret);

        // Redis
        // $redis = RedisUtil::getInstance('redis');
        // $ret = $redis->setex('sdddadfeasdfsdaf', 5, "a".'["redis1", "redis2"]');
        // $ret = $redis->set('sdddadfeasdfsdaf', 'redis');
        // $ret = $redis->get('sdddadfeasdfsdaf');
        // $ret = $redis->del('sdddadfeasdfsdaf');
        // $ret = $redis->get('myAppName:sdddadfeasdfsdaf');
        // var_dump($ret);

        // print_r($redis);
        // var_dump($redis);
        exit;
    }

    public function cacheAction() {
       
        $this->cache = CacheUtil::getInstance('redis', ['serializer' => 'none']);
        $this->cache->get('07IqF', 'Vcc');

        $cache = CacheUtil::getInstance('redis', ['serializer' => 'none']);

        // var_dump($cache);exit;
        // $set = $cache->setex('ebbddse',200, 'value123');
        // $set = $cache->setex('ebbddse',20, ['value111', 'value222']);
        // $set = $cache->del('ebbddse');
        $set = $cache->sets(['k1' => 'v1', 'k2' => 'v2'], 100, 'p');
        var_dump($set);
        $get = $cache->get('ebbddse');
        $get = $cache->gets(['k1', 'k2', 'keykkk'], 'p');
        // $get = $cache->gets(['ebbddse','key1', 'keykkk']);
        // $get = $cache->get('myAppName:ebbddse');
        var_dump($get);

        exit;
    }

    public function debuglogAction() {

        $sessionData = ['id' => 123, 'name' => 'test'];
        print_r($sessionData);
        DebugLog::time('1.php, start page');
        sleep(1);
        DebugLog::time('2.php, start page');
        sleep(1);
        DebugLog::time('3.php, start page');
        DebugLog::log('log1', 'log1_info');
        exit;
    }


    public function IndexAction() {


        $ret = SessionManager::start(false,'yidian');
        // print_r($_SERVER);
        // print_r($_COOKIE);
        var_dump($ret);
        print_r($_SESSION);
        
        $url = $this->getBaseUri() . '/get-many-session';
        $query = ['sessionid' =>['YPZQISU1Tjxg3wJLFWJmVA', 'E4vo3R5EfaPS-pnyDzia3Q']];
        $result = (new Request())->get($url, ['query' => $query, 'timeout' => 1]);
        print_r($result);
        
        exit;


        // $validSessionIds[] = 'a';
        // $validSessionIds[] = 'b';
        // $validSessionIds[] = 'c';
        // echo $validSessionIds[rand(0, count($validSessionIds) - 1)];
        // exit;

        // todo 请求接口写redis
        $url = $this->getBaseUri() . '/set-session';
        $sessionData = ['id' => 123, 'name' => 'test'];
        $params = ['sessionid' => 'jssionidtest', 'data' => ($sessionData), 'expire' => 600, 'key' => 'c071f6e5923a648a5ef88f32b6f738e1'];
        $result = (new Request())->post($url, ['form_params' => $params, 'timeout' => 1]);
        print_r($result);
        // exit;
        $url = $this->getBaseUri() . '/get-many-session';
        $query = ['sessionid' =>['jssionidtest2', 'jssionidtest1']];
        $result = (new Request())->get($url, ['query' => $query, 'timeout' => 1]);
        print_r($result);

        exit;
        
        $url = $this->getBaseUri() . '/delete-session';
        $query = ['sessionid' => ['jssionidtest1', 'jssionidtest'], 'key' =>'c071f6e5923a648a5ef88f32b6f738e1'];
        $result = (new Request())->get($url, ['query' => $query, 'timeout' => 1]);
        print_r($result);
   
        $url = $this->getBaseUri() . '/get-session';
        $query = ['sessionid' => 'jssionidtest'];
        $result = (new Request())->get($url, ['query' => $query, 'timeout' => 1]);
        print_r($result);
        exit;
        if (isset($result['success']['code']) && $result['success']['code'] == 0 ) {
            return true;
        }
        return false;

        // // todo 请求接口读redis 
        // echo $url = $this->getBaseUri() . '/get-session1';
        // $query = ['sessionid' => 'jssionidtest'];
        // $result = (new Request())->get($url, ['query' => $query, 'timeout' => 1]);
        // if (isset($result['success']['code']) && $result['success']['code'] == 0 && isset($result['success']['result'])) {
        //     $data = $result['success']['result'];
        //     print_r($data);
        // }else {
        //     print_r($result);
        // }
        // exit;

        // $r = \Api\PhpUtils\Common\IP::find('114.114.114.114');
        // print_r($r);

        // exit;

        // $_SESSION['abc'] = 'ttt';
        // echo $_SESSION['abc'];
        // echo $_SESSION['abc'];
        // echo $_SESSION['abc'];
        // echo $_SESSION['abc'];
        // exit;
        
        // $abc = '123'. "\x7F" . 456;
        // var_dump($abc);exit;//string(7) "123456" 不可见字任作为分隔符
        // $a = base64_encode('6543211111dasfsdfasdf1111asdfasdfs1111');
        // var_dump($a);
        // var_dump(sha1($a));
        // var_dump(substr(sha1($a), -2));
        // $a = $a . substr(sha1($a), -2);
        // var_dump($a);
        // var_dump(substr($a, 0, -2));
        // $a = substr($a, 0, -2);
        // var_dump($a);
        // var_dump(sha1($a));
        // var_dump(substr(sha1($a), -2));
        // exit;
        // var_dump(strlen($a));
        // var_dump($a);exit;
        
        
        // var_dump($this->response);
        // var_dump(Yaf\Dispatcher::getInstance()->getResponse());
        // exit;
        
        // $data = ['appid'=> 'appid', 'verison'=>'023200', 'reqid'=>'11adddddddfasdfasdfasdfasdfdsafwerqwersfasfasdvasdfsdfffs1', 'platform'=>'1', 'ts' => ceil(microtime(true) * 1000)];
        // echo $sign = Aes::createSign($data);
        // exit;
        
        // $data = ['appid'=> 'appid', 'verison'=>'023200', 'reqid'=>'111', 'platform'=>'1'];
        // $data['sign'] = 'l4lBCE3B_v-ODFeuoxFksl0IUY9ehBnjN_FtU3ESdrn_bMPDsEIxA8IUw0pDJ_kX06P6OOw23in46acBucgceSBE2Vx3Ew52w3FfmRn8IhE';
        // $sign = Aes::checkSign($data);
        // var_dump($sign);
        // exit;
        
        // $obj = new App\Models\User();
        // print_r($obj->getUserData());//Array ( [name] => zhangsan [age] => 18 )
        // exit;
        // $http = $this->getRequest()->getRequest();
        // var_dump($http);
        // var_dump(file_get_contents("php://input"));
        // var_dump($this->requestAll());yaf
        // exit;
        $res = [
            "userid" => 'user',
            "code" => 0
        ];
        // print_r($this->failed(-1,'reason'));
        $this->success($res);
    }

    public function MongoAction() 
    {
        $ret = [];
        $obj = Test::getInstance();
        $cursor = $obj->findOne(["_id" => 8], ['projection' => ['name' => 1, '_id' => 0]]);
        print_r($cursor);
        $ret = $obj->insertOne(["_id" => 8, "mobile" => "17701340008"]);
        $ret = $obj->insertMany([["_id" => 9, "mobile" => "17701340008"], ["_id" => 8, "mobile" => "17701340009"]]);
        $ret = $obj->insertOne(["_id" => 8, "mobile" => "17701340008"]);
        $ret = $obj->updateOne(["_id" => 8], [ '$set' => ["mobile" => "177013400081"]]);
        $ret = $obj->updateMany(["_id" => 8], [ '$set' => ["mobile" => "177013400081"]]);
        $ret = $obj->findOneAndUpdate(["_id" => 8], [ '$set' => ["mobile" => "177013400081"]]);
        $ret = $obj->findOneAndDelete(["_id" => 9]);
        $ret = $obj->deleteMany(["_id" => 9]);
        echo $ret->getDeletedCount();
        echo $ret->getInsertedCount();
        echo $ret->getInsertedId();
        print_r($ret->getInsertedIds());
        echo $ret->getMatchedCount();
        echo $ret->getModifiedCount();
        echo $ret->getUpsertedCount();
        echo $ret->getUpsertedId();
        $cursor = $obj->find();
        foreach ($cursor as $k => $document) {
            // var_dump($document);exit;
            $ret[$k] = $document;
        }
        $ret = $obj->countDocuments();
        print_r($ret);
        exit;
    }

    public function HttpAction() 
    {
        $http = $this->getRequest()->getRequest();
        var_dump($http);
        var_dump(file_get_contents("php://input"));
        var_dump($this->requestAll());
        exit;
    }

    public function IpAction() 
    {
        $r = \Api\PhpUtils\Common\IP::find('123.100.1.111');
        print_r($r);
        // exit;
        $r = \Api\PhpUtils\Common\IP::find('121.103.40.115');
        print_r($r);
        $r = \Api\PhpUtils\Common\IP::find('122.103.40.115');
        print_r($r);
        $r = \Api\PhpUtils\Common\IP::find('123.103.8.115');
        print_r($r);
        exit;
    }

    public function RsaAction() 
    {
        $r = \Api\PhpUtils\Common\IP::find('114.114.114.114');
        print_r($r);
        exit;
    }

    public function AesAction() 
    {
        $data['sign'] = "Fcz71y9zBf4cYEHcg52ZzvfY3qIrv_6ydx08WTOQfg0xj-HepuW9v277GV72zFi-uJXg5YVgVbdxbi0QEUpL5g";
        $sign = Aes::checkSign($data);
        var_dump($sign);
        exit;

        $data = ['appid'=> 'appid', 'verison'=>'023200', 'reqid'=>'11adddddddfasdfasdfasdfasdfdsafwerqwersfasfasdvasdfsdfffs1', 'platform'=>'1', 'ts' => ceil(microtime(true) * 1000)];
        echo $sign = Aes::createSign($data);
        exit;
        
        $data = ['appid'=> 'appid', 'verison'=>'023200', 'reqid'=>'111', 'platform'=>'1'];
        $data['sign'] = 'l4lBCE3B_v-ODFeuoxFksl0IUY9ehBnjN_FtU3ESdrn_bMPDsEIxA8IUw0pDJ_kX06P6OOw23in46acBucgceSBE2Vx3Ew52w3FfmRn8IhE';
        $sign = Aes::checkSign($data);
        var_dump($sign);
        exit;
    }

    /**
     * get url
     * @return string
     */
    public function getBaseUri()
    {
        $env = \Yaf\Application::app()->environ() ?? "dev";
        if ($env == 'product') {
            $this->baseUri = 'http://a4.go2yd.com/Website/session';
        }elseif ($env == 'dev') { 
            $this->baseUri = 'http://127.0.0.1/Website/session';
        }else {
            $this->baseUri = 'http://a4-1.go2yd.com/Website/session';
        }
        return $this->baseUri;
    }
}