<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/22
 * Time: 11:07
 */

namespace app\lib;

use app\lib\GlobConfigs as GlobConfigs;
use \Swoole\Async ;

class Wlog
{
    private static $inCrVel = 0;
    private static $Instance = null;
    private $redis = null;
    private $redis_ctime = 0;

    public static function getInstance($cache = true)
    {
        if ($cache && self::$Instance) {
            return self::$Instance;
        }
        self::$Instance = new self();
        return self::$Instance;
    }

    public function GetRedis()
    {
        $now = time();
        if ($now - $this->redis_ctime > 60 * 15) {
            if ($this->redis) {
                $this->redis->close();
                $this->redis = false;
                $this->redis_ctime = 0 ;
            }
        }

        if ($this->redis) {
            return $this->redis;
        }

        echo "新建一个Wlog->Coroutine_redis ".date("Y-m-d H:i:s")."\n";
        $config = GlobConfigs::getKey('redis');
        $redis = new \Swoole\Coroutine\Redis();
        $ret = $redis->connect($config['host'], $config['port']);
        if ($ret) {
            $this->redis = $redis;
            $this->redis_ctime = time();
        } else {
            $this->redis = false;
        }
        return $redis;
    }

    public function WriteLog($msg, $type = 3, $worker_id = 0)
    {
        $mself= $this;
        go(function()use ($msg,$type,$worker_id,$mself){
            $msg = json_encode([date("Y-m-d H:i:s"), $msg], 256);

            if (in_array($type, [1, 2])) {
                $redis = $mself->GetRedis();
                if ($redis) {
                    if ($type == 1) {
                        $minit = date("i");
                        $ktype = RUN_LOGS_OVTIME_KEY . '_' . $minit;
                        $key = 'Log' . ":" . $worker_id . '_' . $this->IncrKey();
                        $otime = RUN_LOGS_OVTIME;
                        $redis->hset($ktype, $key, $msg);
                        $redis->expire($ktype, $otime);
                    } else {
                        $ktype = RUN_LOGS_OVTIME_KEY;
                        $redis->lpush($ktype, $msg);
                    }
                    return true;
                }
            }

            //redis 失败时，写到日志文件中
            $fileName = date("Y-m-d") . '.log';
            $fullName = LOG_PATH . DS . $fileName;
            //\swoole_async_writefile($fullName, $msg . "\r\n", null, FILE_APPEND);
            //\Swoole\Async::writeFile($fullName, $msg . "\r\n", null, FILE_APPEND);
            file_put_contents($fullName,$msg."\r\n",FILE_APPEND);
            return true;
        });

    }

    public function IncrKey()
    {
        self::$inCrVel++;
        if (self::$inCrVel >= 99999999) {
            self::$inCrVel = 1;
        }
        return self::$inCrVel;
    }


}