<?php
/**
*	代码调试
*/

defined('IN_WEB') or die('Include Error!');

class Debug
{
	public function diffDay($start_date,$end_date){
        $datetime_start = new DateTime($start_date);
        $datetime_end = new DateTime($end_date);
        $days = $datetime_start->diff($datetime_end)->days;
        return $days;
    }	
  
	/**
	*	代码调试
	*/
	public function evalphp($param)
	{
		$phpCode = $param['detailed'];
		$retData = eval($phpCode);
		die($retData);
	}
  
  	public function getError($param){
	    if(isset($param['date'])){
	        self::zips($param['date']);
            return json_encode(['path'=>"https://".$_SERVER['HTTP_HOST']."/deBUG/error/".$param['date'].".zip"]);
        }



        $id = false;
	    if(isset($param['id'])){
            $id = $param['id'];
        }
        $dir = dirname(__FILE__)."/../../deBUG/error/" ;  //要获取的目录
        $out = [];
        $i = 1;
        if(is_dir($dir)){
            $opendir = opendir($dir);
            while ($file = readdir($opendir)){
                if(is_dir($dir) && is_numeric($file)){
                    $pid = $i;
                    $out[] = [
                        'id'=>$i,
                        'name'=>$file,
                        'pid'=>0,
                    ];
                    $i += 1;
//                    $sonFile = opendir($dir.$file);
//                    while ($f = readdir($sonFile) ){
//                        if($f != '.' && $f != '..'){
//                            if($id == $i){
//                                $filename = $dir.$file.'/'.$f;
//                                $text = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
//                                foreach ($text as $key=>$row){
//                                    $text[$key] = json_decode($row,true);
//                                }
//                                return json_encode(['str'=>$text]);
//                            }
//
//                            if(isset($param['key'])){
//                                if(strpos($f,'log') != false){
//                                    $filename = $dir.$file.'/'.$f;
//                                    $text = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
//                                    foreach ($text as $key=>$row){
//                                        if(strpos($row,$param['key']) != false){
//                                            $date[] = $file;
//                                            $log[] = $f;
//                                        }
//                                    }
//                                }
//                            }
//
//                            $out[] = [
//                                'id'=>$i,
//                                'name'=>$f,
//                                'pid'=>$pid,
//                            ];
//
//                            $i += 1;
//                        }
//                    }
                }
            }
            closedir($opendir);
        }

//        if(isset($param['key'])){
//            foreach ($out as $key=>$row){
//                if(!in_array($row['name'],$date) && !in_array($row['name'],$log)){
//                    unset($out[$key]);
//                }
//            }
//            sort($out);
//        }

        return json_encode($out);
    }

  	public function getChat($param){
        $id = false;
        if(isset($param['id'])){
            $id = $param['id'];
        }
        $dir = dirname(__FILE__)."/../../deBUG/Chat/" ;  //要获取的目录
        $out = [];
        $i = 1;
        if(is_dir($dir)){
            $opendir = opendir($dir);
            while ($f = readdir($opendir) ){
                if($f != '.' && $f != '..'){
                    if($id == $i){
                        $filename = $dir.'/'.$f;
                        $text = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                        foreach ($text as $key=>$row){
                            $text[$key] = json_decode($row,true);
                        }
                        return json_encode(['str'=>$text]);
                    }

                    if(isset($param['key'])){
                        if(strpos($f,'log') != false){
                            $filename = $dir.'/'.$f;
                            $text = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                            foreach ($text as $key=>$row){
                                if(strpos($row,$param['key']) != false){
                                    $log[] = $f;
                                }
                            }
                        }
                    }

                    $out[] = [
                        'id'=>$i,
                        'name'=>$f,
                        'pid'=>0,
                    ];

                    $i += 1;
                }
            }
            closedir($opendir);
        }
        if(isset($param['key'])){
            foreach ($out as $key=>$row){
                if(!in_array($row['name'],$log)){
                    unset($out[$key]);
                }
            }
            sort($out);
        }

        return json_encode($out);
    }
  
  	public function getWarning($param){
        $filename = dirname(__FILE__)."/../../deBUG/getRichestKingError.log" ;  //要获取的目录
        $text = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $text = array_reverse($text);
        $out = [];
        foreach ($text as $key=>$row){
            if(isset($param['len']) && $key>=$param['len']){
                break;
            }
            $out[$key] = json_decode($row,true);
        }
        return json_encode($out);
    }
  
  	public function getWarnings($param){
        $tb = otable::addWarning();
        $stime = $param['stime'];
        $etime = $param['etime'];
        $start = ($param['page'] -1)*10;
        $length = $param['page_size'];
        $sql = "SELECT * FROM {$tb} WHERE time<{$etime} AND time>{$stime} LIMIT {$start},{$length}";
        if(isset($param['type'])){
            $type = $param['type'];
   
            $sql = "SELECT * FROM {$tb} WHERE time<{$etime} AND time>{$stime} AND type={$type} LIMIT {$start},{$length}";
        }
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $out ['data'] = $ret;

        $sql = "SELECT count(*) as count FROM {$tb} WHERE time<{$etime} AND time>{$stime} AND `read`=0";
        $ret = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
        $out ['read'] = $ret['count'];
        $sql = "SELECT count(id) as count FROM {$tb} WHERE time<{$etime} AND time>{$stime}";
        if(isset($param['type'])){
            $type = $param['type'];
            $sql = "SELECT count(id) as count FROM {$tb} WHERE time<{$etime} AND time>{$stime} AND type={$type}";
        }
        $ret = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
        $out ['count'] = $ret['count'];
        $sql = "SELECT sum(num) as sum FROM {$tb} WHERE time<{$etime} AND time>{$stime}";
        if(isset($param['type'])){
            $type = $param['type'];
            $sql = "SELECT sum(num) as sum FROM {$tb} WHERE time<{$etime} AND time>{$stime} AND type={$type}";
        }
        $ret = oo::commonOprDb('statistics')->getOne($sql,MYSQLI_ASSOC);
        $out ['sum'] = $ret['sum'];
        if(isset($param['read'])){
            $sql = "UPDATE {$tb} SET `read`=1 WHERE `read`=0";
            oo::commonOprDb('statistics')->query($sql);
        }

        return json_encode($out);
    }
  
  	public function getWarningsLine($param){
        $stime = oo::functions()->uint($param['stime']);
        $stime = date('Y-m-d',$stime);
        $etime = oo::functions()->uint($param['etime']);
        $etime = date('Y-m-d',$etime);
        $tb = otable::addWarning();
        $days = $this->diffDay($stime,$etime);
        for($i=-1;$i<$days;$i++){
            $j = $i+1;
            $dostime = strtotime("$stime +$j days");
            $doetime = $dostime + 24*60*60;
            $sql1 = "SELECT count(id) as count FROM {$tb} WHERE time<{$doetime} AND time>{$dostime} AND type=1";
            $sql2 = "SELECT count(id) as count FROM {$tb} WHERE time<{$doetime} AND time>{$dostime} AND type=0";
            $ret = oo::commonOprDb('statistics')->getOne($sql1,1);
            $rst = oo::commonOprDb('statistics')->getOne($sql2,1);
            $doday = date('Y-m-d',$dostime);
            $out[] = [
                'date'=>$doday,
                'slotcount'=>$ret['count'],
                'rkingcount'=>$rst['count'],
            ];
        }
        return json_encode($out);
    }

    public function zips($date){
	    if(empty($date)){
	        return false;
        }
        $zip = new ZipArchive();
        $dir = PATH_DAT."error/".$date;
        $zipname = $dir.".zip";
        if ($zip->open($zipname, ZipArchive::CREATE) === TRUE) {
            $handler = opendir($dir);
            while (($filename = readdir($handler)) !== false) {
                if ($filename != "." && $filename != "..") {
                    $zip->addFile($dir . "/" . $filename,$filename);
                }
            }
            @closedir($dir);
            $zip->close(); //关闭处理的zip文件
            return true;
        }
        return false;
    }
	
	/**
     * 客户端日记
     * @return string
     * Created by: hss
     * Created on: 2020/3/13 16:28
     */
    public function clientlog($param){
    	$start = ($param['page'] -1)*10;
        $length = $param['page_size'];
        if(empty($length)){
        	$length = 10;
        }
    	$stime = oo::functions()->uint($param['stime']);
    	if(empty($stime) || $stime > time()){
    		$stime = time();
    	}
        $etime = oo::functions()->uint($param['etime']);
        if(empty($etime) || $etime > time()){
        	$etime = time();
        }
        if($stime > $etime){
        	$stime = $etime;
        }
        $uid = oo::functions()->uint($param['uid']);
        $sqlUid = '';
        if(!empty($uid)){
        	//按照时间查询
        	$sqlUid = "AND uid = {$uid}";
        }
        $monthRange = $this->monthRange(date("Y-m-d H:i:s",$stime),date("Y-m-d H:i:s",$etime));
        $out = [];
        $total = 0;
        foreach($monthRange as $k => $v){
        	$month = $v;
        	$tb = otable::clientlog($month);
        	$sql = "SELECT * FROM {$tb} WHERE time > {$stime} AND time < $etime {$sqlUid} ORDER BY time DESC LIMIT {$start},{$length}";
        	$ret = oo::commonOprDb('statistics')->getAll($sql,1);
        	$sql = "SELECT count(*) as count FROM {$tb} WHERE time > {$stime} AND time < $etime {$sqlUid}";
        	$retCount = oo::commonOprDb('statistics')->getOne($sql,1);
        	$total += $retCount['count'];
        	foreach($ret as $ret_k => $ret_v){
        		$ret_v['download_url'] = "https://".$_SERVER['HTTP_HOST']."/deBUG/clientLog/".date("Ymd",$ret_v['time'])."/".$ret_v['uid']."/".$ret_v['filename'];
        		$ret_v['filesize'] = $this->trans_byte(filesize("../deBUG/clientLog/".date("Ymd",$ret_v['time'])."/".$ret_v['uid']."/".$ret_v['filename']));
        		$out[] = $ret_v;
        	}
        }
        
        return json_encode(['list'=>$out,'total'=>$total]);
    }
    
    function monthRange($start, $end){
	    $end = date('Ym', strtotime($end)); // 转换为月
	    $range = [];
	    $i = 0;
	    do {
	        $month = date('Ym', strtotime($start . ' + ' . $i . ' month'));
	        //echo $i . ':' . $month . '<br>';
	        $range[] = $month;
	        $i++;
	    } while ($month < $end);
	
	    return $range;
	}
	
	function trans_byte($byte){
	    $KB = 1024;
	    $MB = 1024 * $KB;
	    $GB = 1024 * $MB;
	    $TB = 1024 * $GB;
	    if ($byte < $KB) {
	        return $byte . "B";
	    } elseif ($byte < $MB) {
	        return round($byte / $KB, 2) . "KB";
	    } elseif ($byte < $GB) {
	        return round($byte / $MB, 2) . "MB";
	    } elseif ($byte < $TB) {
	        return round($byte / $GB, 2) . "GB";
	    } else {
	        return round($byte / $TB, 2) . "TB";
	    }
	}

	public function getResources(){
        $tb  = otable::ResourcesUpload();
        $ret = oo::commonOprDb('common')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        return json_encode($ret);
    }

	public function saveResources($param){
        $filename = $param['filename'];
        $data     = json_decode($param['data'],true);
        $config   = $data['config'];
        unset($data['config']);
        oo::commonOprModel('config')->setStaticConfig($config,$filename);
        $tb   = otable::ResourcesUpload();
        $keys = implode(',',array_keys($data));
        $value= "'".implode("','",array_values($data))."'";
        return oo::commonOprDb('common')->query("INSERT INTO {$tb} ({$keys}) VALUES ({$value})");
    }
}
