<?php
class oo extends CI_Model
{
	static $oo = array();
	static $objDb = array();
	static $config = array();
	static $objModel = array();
	static $objCache = array();
	static $objRedis = array();
	static $load = [
	    'base'  => [
	        'okeys',
	        'otable',
        ],
        'redis' =>['default','games','statistics'],
    ];
	/**
     * 初始化
     */
    public function __construct() {
    	parent::__construct();
    	$this->ci = get_instance();
		$this->ci->load->config('redis');
        self::$config['dbindex'] = 'crazygod_';
        self::$config['dbindex2'] = 'crazyGod_';
        foreach (self::$load['redis'] as $row){
            self::$config['redis_'.$row] = $this->ci->config->item('redis_'.$row);
        }
        foreach (self::$load['base'] as $row){
            $this->load->model($row);
        }
        $this->load->model("common");
        $this->load->model("funs");
        foreach (self::getModels() as $row){
            $this->load->model($row);
        }

        $this->load->driver('cache');
        self::$objCache['default'] = $this->cache->memcached;
        $this->load->library('functions');
    }

    static public function getModels(){
        $path = APPPATH . "models";
        $fileName = scandir($path);
        $models   = [];
        foreach($fileName as $k=>$v){
            if($v=="." || $v==".." || strpos($v,"Model") === false){
                continue;
            }else{
                $models[] = str_replace('.php','',$v);
            }
        }
        return $models;
    }

    /**
	 * 设置全局配置变量
	 */
	static function setConfig($config){
		self::$config = $config;
	}
    
	/**
	 * 操作库
	 * @param $table string 表名兼配置文件名称
     * @return muDB
	 */
	static public function commonOprDb($table = ''){
		if( !$table ) return -1;
		$table = strtolower($table);
        if (!is_object(self::$objDb[$table] ?? null)) {
			$file_path = APPPATH.'config/database.php';
			include($file_path);
			$temp = [];
            $port = empty($db[$table]['port']) ? 3306 : $db[$table]['port'];
			$temp[] = $db[$table]['hostname'].":{$port}";
			$temp[] = $db[$table]['username'];
			$temp[] = $db[$table]['password'];
			$temp[] = $db[$table]['database'];
			include_once BASEPATH . '/libraries/class.db.php';
			self::$objDb[$table] = new muDB([$temp]);
		}
		
		return self::$objDb[$table];
	}
	
	/**
     * 通用操作Model方法
     * @param string $modelname
     * @return object|int
     */
	static public function commonOprModel($modelname = ''){
	    if( !$modelname ) return -1;
	    $modelname = strtolower($modelname);
	    if(!in_array($modelname,['okeys','oo','otable','common'])){
	    	$modelname = $modelname."model";
	    }
        if ( empty(self::$objModel[$modelname]) || !is_object( self::$objModel[$modelname])) {
            self::$objModel[$modelname] = new $modelname;
        }

        return self::$objModel[$modelname];
    }
    
    /**
     * 通用memcache缓存
     * @param string $keyname
     * @return mucache
     */
    static public function commonOprCache($configname = ''){
        if( !$configname ) return -1;
        $configname = strtolower($configname);
        if ( empty(self::$objCache[$configname]) || !is_object( self::$objCache[$configname])) {
            //self::$objCache[$configname] = $this->cache->memcached;
            $configname = 'default';
        }
        return self::$objCache[$configname];
    }
    
    /**
	 * 通用操作redis
	 * @param $configname string key名称
     * @return muredis
	 */
	static public function commonOprRedis($configname = '')
	{
		if( !$configname ) return -1;
        $configname = strtolower($configname);
        if (!is_object(self::$objRedis[$configname] ?? null)) {
			include_once BASEPATH . '/libraries/muredis.php';
			self::$objRedis[$configname] = new muredis(self::$config['redis_'.$configname]);

		}
		return self::$objRedis[$configname];
	}
	
	/**
	 * 获取配置通用接口
	 * @param string $key
	 * @return array
	 */
	public static function cfg($key) {
		$cacheKey = 'CFG_'.$key;
		if (!isset(self::$oo[$cacheKey])) {
			$file = APPPATH . "config/" . sprintf("config.%s.php", $key);
			if (!file_exists($file)) {
				$file = APPPATH . "config/" . sprintf("%s.php", $key);
				if (!file_exists($file)) return array();
			}
			self::$oo[$cacheKey] = include_once($file);
		}
		return self::$oo[$cacheKey];
	}
    
    /**
	 * @return functions
	 */
	static function functions(){
		if ( empty(self::$oo['functions']) || !is_object( self::$oo['functions'])) {
			self::$oo['functions'] = new Functions();
		}
		return self::$oo['functions'];
	}
	
	/**
	 * @return LogsModel
	 */
	public static function logs(){
        if (!is_object(self::$oo['logs'] ?? null)) {
			include_once APPPATH.'/models/LogsModel.php';
			self::$oo['logs'] = new LogsModel();
		}
		return self::$oo['logs'];
	}

	/**
     *
     * @param $code
     * @param $data
     * @param $msg
     * @return string
     */
    public static function response($code,$data = [],$msg = ''){
        die(json_encode([
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ],JSON_NUMERIC_CHECK));
    }

    /**
     * 获取指定日期段内每一天的日期
     * @param $start
     * @param $end
     * @return array
     * Created by: Owen
     * Created on: 2020/11/7 16:03
     */
    public static function getDateRange($start, $end) {
        $stime = strtotime($start);
        $etime = strtotime($end);
        $datearr = [];
        while ($stime <= $etime) {
            $datearr[] = date('Y-m-d', $stime);//得到dataarr的日期数组。
            $stime = $stime + 86400;
        }
        return $datearr;
    }
    public static function getDateRange2($start, $end) {
        $stime = strtotime($start);
        $etime = strtotime($end);
        $datearr = [];
        while ($stime <= $etime) {
            $datearr[] = date('Ymd', $stime);//得到dataarr的日期数组。
            $stime = $stime + 86400;
        }
        return $datearr;
    }
    /**
     * 本周剩余时间 -- 周日第一天
     * @return false|int
     * Created by: Owen
     * Created on: 2019/11/30 12:17
     */
    public static function weekDeadline(){
        return mktime(23,59,59,date('m'),date('d')-date('w')+6,date('Y')) - time();
    }

    /**
     * 判断是否是post
     * @return bool
     * Created by: Owen
     * Created on: 2020/12/2 16:35
     */
    public static function isPost(){
        return $_SERVER['REQUEST_METHOD'] == 'POST';
    }

    /**
     * 今天过去分钟数
     * @param $time
     * @return false|float|int|string
     * Created by: Owen
     * Created on: 2020/4/24 19:50
     */
    public static function todaySecond($time = null){
        if($time == null){
            $time = time();
        }
        $hour   = date('G', $time) * 60;
        return $hour + date('i', $time);
    }

    /**
     * redis过期时间添加一个随机值
     * @param int $time
     * @return int
     */
    public static function redisRandomExpire($time = 0) {
        return $time + rand(0, 600); //10分钟内的随机值
    }
    /**
     * Notes:获取毫秒时间搓
     * User: wsc
     * Time: 2019/12/28 11:52
     * @return float
     */
    public  static function getMsectime() {
        list($msec, $sec) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    }
}
