<?php

use OSS\OssClient;
//公用model
class common extends CI_Model
{
    public $n =0;
    public $fileArr =[];
    public function __construct(){
        parent::__construct();
        $this->load->database();
        $this->load->library('OssCommon');
        $this->load->library('CdnRefresh');
    }

    public function test(){
        return '这是一个测试共用model fun';
    }

    public $createTemplateSql =[
        'newLoginLog' => " CREATE TABLE `#table#` (`uid` int(11) NOT NULL COMMENT '用户id',`sid`  tinyint(1) DEFAULT NULL COMMENT '操作系统' ,`country`  varchar(8) DEFAULT NULL COMMENT '国家' ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;",
        'registerLog' => " CREATE TABLE `#table#` (`uid` int(11) NOT NULL COMMENT '用户id',`date` varchar(16) DEFAULT NULL COMMENT '注册时间' ,`country` varchar(8) DEFAULT NULL COMMENT '国家' ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;",
    ] ;

    /**
     * 当前秒转化成时分秒表达式
     * @param int $num
     * @return string
     */
    public function timeuse($num = 0) {
        $str = '';
        $hour = floor($num/3600);
        $str = $hour ? $hour.'小时' : '';
        $minute = floor(($num-3600*$hour)/60);
        $str .= $minute ? $minute.'分' : '';
        $second = floor((($num-3600*$hour)-60*$minute)%60);
        $str .= $second ? $second.'秒' : '';
        return $str;
    }

    /**
     * Notes:上传到阿里云oss
     * User: wsc
     * Time: 2020/6/17 18:43
     * @param $file_name -oss上记录的位置及文件名
     * @param $file_path -本地需要上传的文件名（完整路径）
     * @return bool
     * @throws \OSS\Core\OssException
     */
    public function upToOss($file_name,$file_path){
        $oos_debug = $this->config->item('oos_debug');
        $bucket =  OssCommon::getBucketName();
        $endpoint = "";
        if($oos_debug){
            return true;
            $bucket = "crazycoin-test";
            $endpoint = "oss-cn-shenzhen.aliyuncs.com";
        }

        $ossClient =  OssCommon::getOssClient($endpoint);
        if (is_null($ossClient)) exit(1);
        try {
            $res =$ossClient->uploadFile($bucket, $file_name, $file_path);
        }catch (OSS\Core\OssException $e){
            logMessage('debug',$e);
            return false;
        }
        return true;
    }

    /**
     * Notes:从阿里云oss下载到本地
     * User: richard
     * Time: 2021/2/05 09:37
     * @param $file_name -oss上记录的位置及文件名
     * @param $file_path -下载到本地目录
     * @return bool
     * @throws \OSS\Core\OssException
     */
    public function downloadFromOss($file_name,$file_path){
        $oos_debug = $this->config->item('oos_debug');
        $bucket =  OssCommon::getBucketName();
        $endpoint = "";
        if($oos_debug){
            $bucket = "crazycoin-test";
            $endpoint = "oss-cn-shenzhen.aliyuncs.com";
        }

        $ossClient =  OssCommon::getOssClient($endpoint);
        if (is_null($ossClient)) exit(1);
        try {
            $res =$ossClient->getObject($bucket, $file_name, [OssClient::OSS_FILE_DOWNLOAD => $file_path]);
        }catch (OSS\Core\OssException $e){
            logMessage('debug',$e);
            return false;
        }
        return true;
    }

    /**
     * Notes:刷新cdn目录 ，已填写部分路径public/game/
     * User: wsc
     * Time: 2020/8/20 12:27
     * @param $dir  -格式例如 'test/'
     * @return bool
     */
    public function CdnRefreshDir($dir){
        $oos_debug = $this->config->item('oos_debug');
        if($oos_debug){
            $res =  true;
        }else{
            $res = true;
            $failedDomains = [];
            $rut =  CdnRefresh::refreshDir($dir);
            foreach ($rut as $domain => $items){
                if(empty($items['RequestId'])){
                    $res = false;
                    $failedDomains[] = $domain;
                }
            }
        }
       return $res ? $res : $failedDomains;
    }

    /**
     * Notes:刷新cdn根目录
     * User: xwy
     * Time: 2021/11/1 10:50
     * @return bool
     */
    public function CdnRefreshAll(){
        $oos_debug = $this->config->item('oos_debug');
        if($oos_debug){
            $res =  true;
        }else{
            $res = true;
            $failedDomains = [];
            $rut =  CdnRefresh::refreshDir('');
            foreach ($rut as $domain => $items){
                if(empty($items['RequestId'])){
                    $res = false;
                    $failedDomains[] = $domain;
                }
            }
        }
       return $res ? $res : $failedDomains;
    }

    /**
     * Notes:刷新cdn URL
     * User: wsc
     * Time: 2020/8/20 12:28
     * @param $url https://god.superant.cc/public/game/test/01.jpg
     * @return bool
     */
    public function CdnRefreshUrl($url){
        $oos_debug = $this->config->item('oos_debug');
        if($oos_debug){
            $res =  true;
        }else{
            $rut =  CdnRefresh::refreshUrl($url);
            $res = false;
            if(isset($rut['RequestId'])&&!empty($rut['RequestId'])){
                $res =true;
            }
        }
        return $res;
    }

    /**
     * 预热cdn URL
     * @param $url
     * @return bool
     * Created by: Owen
     * Created on: 2021/3/13 17:13
     */
    public function CdnPushUrl($url){
        $oos_debug = $this->config->item('oos_debug');
        $url = CdnRefresh::AliyunCdnUrl . "/public/game/".ltrim($url, '/');
        if($oos_debug){
            $res =  true;
        }else{
            $rut =  CdnRefresh::PushUrl($url);
            $res = false;
            if(isset($rut['RequestId'])&&!empty($rut['RequestId'])){
                $res =true;
            }
        }
        return $res;
    }

    /**
     * Notes:判断文件是否存在
     * User: wsc
     * Time: 2020/6/18 15:09
     * @param $file
     * @return bool
     */
    public function getInfoFromOss($file){
        $bucket =  OssCommon::getBucketName();
        $ossClient =  OssCommon::getOssClient();
        try{
            $exist =$ossClient->doesObjectExist($bucket,$file);
        }catch (OSS\Core\OssException $e){
            logMessage('debug',$e);
        }
        return $exist;
    }
    /**
     * Notes:查找文件
     * User: wsc
     * Time: 2020/6/18 14:20
     * @param $dir
     * @return array
     */
    public function scan($dir){
        static $d=0;
        $dirArr = scandir($dir);
        foreach($dirArr as $v){

            if($v!='.' && $v!='..'){
                $dirname = $dir.'/'.$v;  //子文件夹的目录地址
                if(is_dir($dirname)){
                    $count['dir'] = ++$d;
                    $this->scan($dirname);
                }else{
                    $this->fileArr[$this->n] = $dirname;
                    $this->n++;
                }
            }

        }
        return $this->fileArr;
    }


    public function CurlApi($param){
        $posts = ['frombg' => 1, 'lid' => 1, 'sid' => 1];
        $posts = array_merge($posts,$param);
        $url  = $this->config->item('officialUrl');
        return $this->curl->req($url, $posts);
    }


    public function getDbInstance($tb,$timestamp){
        if($tb == otable::Assetslog()){
            if(time() - $timestamp >= 8 * 24 * 3600){
                $database = 'log2';
            }else{
                $database = 'log';
            }
            return $database;
        }
    }



    public function createTable($tableName = '', $dbCoon = '', $createdTemplate = ''){
        if($this->checkTableExist($tableName, $dbCoon) || empty($this->createTemplateSql[$createdTemplate])){
            return true;
        }
        list($dbName, $tableName) = explode('.',$tableName);
        if(empty($tableName)){
            $tableName = $dbName;
        }
        $sql = str_replace('#table#', $tableName, $this->createTemplateSql[$createdTemplate]);
//        echo $sql;die;
        $result  =oo::commonOprDb($dbCoon)->query($sql);
        return $result;
    }

    public function checkTableExist($tableName = '', $dbCoon = ''){
        if(empty($tableName) || empty($dbCoon))return true;
        list($dbName, $tableName) = explode('.',$tableName);
        if(empty($tableName)){
            $tableName = $dbName;
        }else{
            oo::commonOprDb($dbCoon)->connect()->select_db($dbName);
        }
        $query = "SHOW TABLES LIKE '{$tableName}'";
//        $query = "select * from  {$tableName} limit 1";
        $tbInfo = oo::commonOprDb($dbCoon)->getOne($query,1);
        if(empty($tbInfo)){
            return false;
        }
        return true;
    }
}
