<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Debug extends MY_Controller {

    public $postData = array('frombg' => 1, 'lid' => 1, 'sid' => 1);
    private $_json = '';

    protected $page = 10;//分页

    protected $pageConfig = array(
        'first_tag_open' => '<li>',
        'first_tag_close' => '</li>',
        'last_tag_open' => '<li>',
        'last_tag_close' => '</li>',
        'next_tag_open' => '<li>',
        'next_tag_close' => '</li>',
        'prev_tag_open' => '<li>',
        'prev_tag_close' => '</li>',
        'cur_tag_open' => "<li class='active'><a hef='#'>",
        'cur_tag_close' => "</a></li>",
        'num_tag_open' => "<li>",
        'num_tag_close' => "</li>",
    );

    public function __construct()
    {
        parent::__construct();
        $this->load->library('curl');
        $this->load->library('pagination');
        $this->load->helper('cookie');
    }


    public function request()
    {
        $this->load->view('debug/request');
    }

    public function actionrequest()
    {

        $returnData = array('referer' => '', 'refresh' => false, 'state' => '', 'message' => '');
        $detailed = $this->input->post('detailed');
        if( empty($detailed) ){ //详细参数为空
            die(json_encode($returnData));
        }

        $sid = $this->input->post('sid');
        $lid = $this->input->post('lid');
        $reqenv = $this->input->post('reqenv');//环境
        $reqaddress = $this->input->post('reqaddress');//请求地址
        if( $reqaddress == 'gateway.php' ){
            $mod = $this->input->post('mod');
            $act = $this->input->post('act');
        }

        $detailed = trim($detailed);
        if( $this->isJson($detailed) ){//解析详细参数 JSON或者换行
            $msg = $this->_json;
        }else{
            $msg = $this->resolveStr($detailed);
        }

        if( empty($msg) ){
            $returnData[message] = '参数错误';
            die(json_encode($returnData));
        }

        //准备curl请求数据以及url
        $msg['sid'] = $sid;

        $msg['lid'] = $lid;
        isset($mod) && $msg['mod'] = $mod;
        isset($act) && $msg['act'] = $act;

        if($reqenv == 'local'){
            //$curlUrl = $this->_localUrl;
            $curlUrl = $this->config->item('localBaseUrl').'/api/';
            $msg['demo'] = 1;
        }else{
            //$curlUrl = $this->_officialUrl;
            $curlUrl = $this->config->item('officialBaseUrl').'/api/';
        }
        $curlUrl .= $reqaddress;

        $rs = $this->curl->req($curlUrl, $msg);
//        print_r($msg);
//        print_r($curlUrl);
//        print_r($rs);
//        exit();
        $returnData['state'] = 'success';
        $returnData['message'] = '查询成功';
        $returnData['retdata'] = $rs;
        die(json_encode($returnData));
    }

    protected function isJson($str){
        if( empty($str) ) return false;
        $val = json_decode($str, TRUE);
        if(json_last_error() == JSON_ERROR_NONE){
            $this->_json = $val;
        }
        return $this->_json;
    }

    protected function resolveStr($str){
        $arr = explode("\r\n", $str);
        $newarr = array();
        if( is_array($arr) ){
            foreach ($arr as $value) {
                list($k, $v) = explode('=', $value);
                $k = trim($k);
                $v = is_numeric($v) ? intval($v) : "'".trim($v)."'";
                $newarr[$k] = $v;
            }
        }
        return $newarr;
    }


    /**
     *	代码调试
     */
    public function evalphp()
    {
        $this->load->view('debug/evalphp');
    }

    public function error(){
        $param['key'] = $this->input->get('key');
		$id   = $this->input->post('id');
        $dir = PATH_DAT . "/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);
                    if($file == date("Ymd")){
                    	while ($f = readdir($sonFile) ){
	                    	//var_dump($f);
	                        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);
	                                }
	                                
	                                $returnData['state'] = 'success';
							        $returnData['message'] = '成功';
							        $returnData['retdata'] = ['str'=>$text];
							        die(json_encode($returnData));
	                            }
	
	                            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);
        }
        
        $retData = $this->ArraySortByKey($out,'name',true);
        $this->load->view('debug/error',['data'=>$retData,'key'=>$key]);
    }

    public function actionError(){
        
        $date = $this->input->post('date');
        
        if(isset($date)){
	        self::zips($date);
            $retData = ['path'=>"https://".$_SERVER['HTTP_HOST']."/deBUG/error/".$date.".zip"];
        }
        
        $returnData['state'] = 'success';
        $returnData['message'] = '成功';
        $returnData['retdata'] = $retData;
        die(json_encode($returnData));
    }

    public function chat(){
        $key = $this->input->get('key');
        if(!empty($key)){
            $this->postData['key'] = $key;
        }else{
            $key = '';
        }
        $this->postData['mod'] = 'Debug';
        $this->postData['act'] = 'getChat';
        $curlUrl = $this->config->item('officialUrl');
        $retData = $this->curl->req($curlUrl, $this->postData);
        $retData = json_decode($retData,true);
        $retData = $this->ArraySortByKey($retData,'name',true);
        $this->load->view('debug/chat',['data'=>$retData,'key'=>$key]);
    }

    public function actionChat(){
        $id = $this->input->post('id');
        $this->postData['mod'] = 'Debug';
        $this->postData['act'] = 'getChat';
        $this->postData['id'] = $id;
        $curlUrl = $this->config->item('officialUrl');
        $retData = $this->curl->req($curlUrl, $this->postData);
        $retData = json_decode($retData,true);
        $returnData['state'] = 'success';
        $returnData['message'] = '成功';
        $returnData['retdata'] = $retData;

        die(json_encode($returnData));
    }

    public function warn(){
        $key = $this->input->get('len');
        if(!is_null($key)){
            $this->postData['len'] = $key;
        }else{
            $key = 10;
        }
        $this->postData['mod'] = 'Debug';
        $this->postData['act'] = 'getWarning';
        $curlUrl = $this->config->item('officialUrl');
        $retData = $this->curl->req($curlUrl, $this->postData);
        $retData = json_decode($retData,true);
        $retData = $this->ArraySortByKey($retData,'time',true);
        $this->load->view('debug/warn',['data'=>$retData,'key'=>$key]);
    }

    /**
     *	代码处理接口
     */
    public function actionevalphp()
    {
        $returnData = array('referer' => '', 'refresh' => false, 'state' => '', 'message' => '');
        $detailed = $this->input->post('detailed');
        if( empty($detailed) ){ //详细参数为空
            die(json_encode($returnData));
        }
        $this->postData['detailed'] = $detailed; //代码内容

        $reqenv = $this->input->post('reqenv');//环境
        if( $reqenv == 'local' ){
            $curlUrl = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }else{
            $curlUrl = $this->config->item('officialUrl');
        }

        $this->postData['mod'] = 'Debug';
        $this->postData['act'] = 'evalphp';

        $retData = $this->curl->req($curlUrl, $this->postData);
        $returnData['state'] = 'success';
        $returnData['message'] = '成功';
        $returnData['retdata'] = $retData;
        die(json_encode($returnData));
    }

    public function ArraySortByKey($data,$key,$type = false){
        $len=count($data);
        //该层循环控制 需要冒泡的轮数
        for($i=1;$i<$len;$i++)
        { //该层循环用来控制每轮 冒出一个数 需要比较的次数
            for($k=0;$k<$len-$i;$k++)
            {
                if($data[$k][$key]>$data[$k+1][$key])
                {
                    $tmp=$data[$k+1];
                    $data[$k+1]=$data[$k];
                    $data[$k]=$tmp;
                }
            }
        }
        if($type){
            $data = array_reverse($data);
        }
        return $data;
    }

    public function warning($p = 1){
        if( $this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('useranomalymoney_stime') ){
            $data['stime'] = date('Y-m-d', $stime);
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.' 0:0:0');
        }else{
            $data['stime'] = date("Y-m-d");
            $dateArr['stime'] = strtotime(date('Y-m-d').' 0:0:0');
        }

        if($etime = get_cookie('useranomalymoney_etime') ){
            $data['etime'] = date('Y-m-d', $etime);
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.' 23:59:59');
        }else{
            $data['etime'] = date("Y-m-d");
            $dateArr['etime'] = strtotime(date('Y-m-d').' 23:59:59');
        }

        $this->postData['mod'] = 'Debug';
        $this->postData['act'] = 'getWarnings';
        $this->postData['page_size'] = 10;
        $this->postData['page'] = ($p==1)?1:$p/10;
        $this->postData['read'] = 1;
        if(!is_null(get_cookie('useranomalymoney_uid'))){
            $this->postData['type'] = get_cookie('useranomalymoney_uid');
            $data['type'] = get_cookie('useranomalymoney_uid');
        }
        $postData = array_merge($dateArr, $this->postData);
        $retData = $this->curl->req($url, $postData);
        $re = json_decode($retData, 1);
        if ($re){
            foreach ($re['data'] as $key=>$row){
                $re['data'][$key]['time'] = date('Y-m-d H:i:s',$row['time']);
            }
            $list = $re['data'];
            $total = $re['count'];
            $sum = $re['sum'];
            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#debug/warning');
            $pageConfig['total_rows'] = intval($total);
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $data['list'] = $list;
        $data['total'] = $total;
        $data['sum'] = $sum;
        $this->load->view('debug/warning', $data);
    }

    public function warningLine(){
        if( $this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('useranomalymoney_stime') ){
            $data['stime'] = date('Y-m-d', $stime);
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.' 0:0:0');
        }else{
            $data['stime'] = date("Y-m-d",strtotime("-7 days"));
            $dateArr['stime'] = strtotime($data['stime'].' 0:0:0');
        }

        if($etime = get_cookie('useranomalymoney_etime') ){
            $data['etime'] = date('Y-m-d', $etime);
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.' 23:59:59');
        }else{
            $data['etime'] = date("Y-m-d");
            $dateArr['etime'] = strtotime(date('Y-m-d').' 23:59:59');
        }

        $this->postData['mod'] = 'Debug';
        $this->postData['act'] = 'getWarningsLine';
        if(!is_null(get_cookie('useranomalymoney_uid'))){
            $this->postData['type'] = get_cookie('useranomalymoney_uid');
            $data['type'] = get_cookie('useranomalymoney_uid');
        }
        $postData = array_merge($dateArr, $this->postData);
        $retData = $this->curl->req($url, $postData);
        $ret = json_decode($retData, 1);

        foreach ($ret as $row){
            $date[] = $row['date'];
            $slot[] = $row['slotcount'];
            $rking[]= $row['rkingcount'];
        }
        $data['date']  = $date;
        $data['slot'] = $slot;
        $data['rking'] = $rking;

        $this->load->view('debug/warningLine', $data);
    }
	
	//客户端日记上报
    public function clientlog($page = 0){
    	if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
    	if( $this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if( $stime = get_cookie('useranomalymoney_stime') ){
            $data['stime'] = date('Y-m-d', $stime);
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.' 0:0:0');
        }else{
            $data['stime'] = date("Y-m-d",strtotime("-7 days"));
            $dateArr['stime'] = strtotime($data['stime'].' 0:0:0');
        }

        if($etime = get_cookie('useranomalymoney_etime') ){
            $data['etime'] = date('Y-m-d', $etime);
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.' 23:59:59');
        }else{
            $data['etime'] = date("Y-m-d");
            $dateArr['etime'] = strtotime(date('Y-m-d').' 23:59:59');
        }
        if(empty($dateArr['stime']) || $dateArr['stime'] > time()){
            $dateArr['stime'] = time();
        }
        if(empty($dateArr['etime']) || $dateArr['etime'] > time()){
            $dateArr['etime'] = time();
        }
        if($dateArr['stime']  > $dateArr['etime']){
            $dateArr['stime'] = $dateArr['etime'];
        }
//		$this->postData['page'] = $page/10;
//        $this->postData['page_size'] = 10;
//        $this->postData['mod'] = 'Debug';
//        $this->postData['act'] = 'clientlog';
        $sqlUid ="";
        if(!is_null(get_cookie('useranomalymoney_uid'))){
//            $this->postData['uid'] = get_cookie('useranomalymoney_uid');
            $sUid = get_cookie('useranomalymoney_uid');
            $sqlUid="AND uid = {$sUid}";
            $data['uid'] = get_cookie('useranomalymoney_uid');
        }
//        $postData = array_merge($dateArr, $this->postData);
//        $retData = $this->curl->req($url, $postData);
//        $ret = json_decode($retData, 1);
//
        $start = ($page/10-1)*10;

        $monthRange = $this->monthRange(date("Y-m-d H:i:s",$dateArr['stime']),date("Y-m-d H:i:s", $dateArr['etime']));
        $out = [];
        $total = 0;
        foreach($monthRange as $k => $v){
            $month = $v;
            $tb = otable::clientlog($month);
            $sql = "SELECT * FROM {$tb} WHERE time > {$dateArr['stime']} AND time < {$dateArr['etime']} {$sqlUid} ORDER BY time DESC LIMIT {$start},10";
            $ret = oo::commonOprDb('statistics')->getAll($sql,1);
            $sql = "SELECT count(*) as count FROM {$tb} WHERE time > {$dateArr['stime']} AND time < $etime {$sqlUid}";
            $retCount = oo::commonOprDb('statistics')->getOne($sql,1);
            $total += $retCount['count'];
            foreach($ret as $ret_k => $ret_v){
                $ret_v['showText'] = file_get_contents(PATH_DAT."clientLog/".date("Ymd",$ret_v['time'])."/".$ret_v['uid']."/".$ret_v['filename']);
                $ret_v['download_url'] = "../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;
            }
        }
        $data['data'] = $out;
//		var_dump($data);
		//分页
        $data['total'] = $total;
        $data['page'] = 1;
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#debug/clientlog');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;

        $this->load->view('debug/clientlog', $data);
    }
    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;
    }
    public function fileUpload(){
        $posts = $this->postData;
        $posts['mod'] = 'Debug';
        $posts['act'] = 'getResources';
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);
        $retData = json_decode($retData,true);
        $this->load->view('debug/file',['action' => array_reverse($retData)]);
    }

    public function unzip(){
        $input = $this->input->post();
        $zipPath = dirname(__FILE__)."/../../public/game/newAssets/";
        $configPath = dirname(__FILE__)."/../../public/game/config/";
        $zip = new ZipArchive;
        if ($zip->open($zipPath.$input['filename']) === TRUE) {
            $zip->extractTo($zipPath);
            $zip->close();
            $newName = 'RemoteAssets'.time().'.json';
            if(rename($zipPath.'RemoteAssets.json',$configPath.$newName)){
                $posts = $this->postData;
                $posts['mod'] = 'Debug';
                $posts['act'] = 'saveResources';
                $posts['filename'] = $newName;
                $posts['data'] = json_encode([
                    'filename'  =>$newName,
                    'zipPath'   =>$input['filename'],
                    'createTime'=>time(),
                    'uploader'  =>get_cookie('username'),
                ]);
                $retData = $this->curl->req($this->config->item('officialUrl'), $posts);
                if($retData == 0){
                    return $this->response(1, '操作失败');
                }else{
                    return $this->response(0, '操作成功');
                }
            }
        }
        return $this->response(1, '操作失败');
    }

    public function actionFileUpload($name){
        $config = array(
            'savePath' => 'public/game/AssetsUpload',
            'maxSize'  => 1024*5000,
            'allowFiles' => array('.json')
        );
        $unzipPath = 'public/game/config/';
        $this->load->library('uploader', $config);
        $file = $this->uploader->getFileInfo();
        if($file['state'] != "SUCCESS"){
            return $this->response(1, $file['state']);
        }
        if(strpos(strtolower($file['originalName']),strtolower($name)) === false){
            return $this->response(1, "上传资源名称异常");
        }
        $newName = $name.time().'.json';
        rename($file['url'],$unzipPath.$newName);
        $posts = $this->postData;
        $posts['mod'] = 'Debug';
        $posts['act'] = 'saveResources';
        $posts['filename'] = $newName;
        $posts['data'] = json_encode([
            'config'    =>$name,
            'filename'  =>$newName,
            'zipPath'   =>$file['originalName'],
            'createTime'=>time(),
            'uploader'  =>get_cookie('username'),
        ]);
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);
        if($retData == 0){
            return $this->response(1, '操作失败',[$retData]);
        }else{
            $file_path = str_replace("\\","/",FCPATH . $unzipPath.$newName);
            oo::commonOprModel('common')->upToOss($unzipPath.$newName,$file_path);
            return $this->response(0, '操作成功');
        }
    }
    
    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;
    }

    public function dev(){
        $data = [];
//        $data['hotupdate'] = json_decode(oo::commonOprModel('config')->getSysCon("Game","hotupdate"),true)??[];
        $this->load->view('debug/dev',$data);
    }

    public function hotupdate(){
        $input = $this->input->post();
        oo::commonOprModel('config')->setSysCon("Game","hotupdate",json_encode($input,JSON_NUMERIC_CHECK));
        return $this->response(0, '操作成功');
    }

    public function spineMd5(){
        oo::commonOprModel('Filemd5')->makeSpineMd5();
    }

    public function file($user = "dev",$pwd = "a9d5de7d15a202a7"){
        echo '<script language="javascript" type="text/javascript">window.open("/filemanager.php?fm_usr='.$user.'&fm_pwd='.$pwd.'&userName='.get_cookie('chinesename').'");</script>';
    }

    public function refreshResImageMd5(){
        oo::commonOprModel('Filemd5')->makeMd5("resImage","/image/resImage");
        return $this->response(0, '操作成功');
    }

//============================================
   //获取设置客户端日志采集记录
    public function clickLogUidList(){
        $data = [];
        $k1 = okeys::userLogStatusList();
        $list = oo::commonOprRedis('games')->hGetAll($k1);
        foreach ($list as $uid=>$status){
            $k2 = okeys::userLogStatus($uid);
            $ret = oo::commonOprRedis('games')->exists($k2);
            if(!$ret){
                unset($list[$uid]);
                oo::commonOprRedis('games')->hDel($k1,$uid);
            }
        }
        $data['list'] = $list;
//        var_dump($data['list']);
        $this->load->view('click/clickLogUidList',$data);
    }

    public function SetClickLogUid(){
        $uid =  $this->input->post('uid');
        if($uid<1){
            return $this->response(1, 'uid 不为空');
        }
        $k1 = okeys::userLogStatusList();
        oo::commonOprRedis('games')->hSet($k1,$uid,time());
        $k2 = okeys::userLogStatus($uid);
        oo::commonOprRedis('games')->setex($k2,1,86400*3);
        return $this->response(0, '操作成功');
    }

//===================GM工具====================
    public $apiArr=[
        "loginLog"=>[
            "name"=>"查询登录日志",
            "act"=>"loginLog",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
                "date"=>["title"=>"日期:","tips"=>"如：20210101"],
            ]
        ]
        ,
        "addFriend"=>[
            "name"=>"添加好友",
            "act"=>"addFriend",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"A添加发起人uid*:","tips"=>""],
                "toUid"=>["title"=>"B被添加的人uid:","tips"=>"(若C填写则此处不填)"],
                "num"=>["title"=>"C添加几个:","tips"=>"(若B处填则此处不填)"],
            ]
        ]
        , "incubatePet"=>[
            "name"=>"激活宠物",
            "act"=>"incubatePet",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
                "petId"=>["title"=>"宠物Id*:","tips"=>""],
            ]
        ]
        , "deleteInviteRewardLog"=>[
            "name"=>"删除邀请领奖记录",
            "act"=>"deleteInviteRewardLog",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
            ]
        ]
        , "delSignIn"=>[
            "name"=>"删除7天签到",
            "act"=>"delSignIn",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
                "isDelToday"=>["title"=>"是否删除今天签到(1删除):","tips"=>""],
            ]
        ]
        , "delSignInProgress"=>[
            "name"=>"修改签到进度",
            "act"=>"delSignInProgress",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
                "signInDay"=>["title"=>"签到进度:","tips"=>""],
                "rewardDay"=>["title"=>"已领奖天数:","tips"=>""],
                "isDelReward"=>["title"=>"是否领取:","tips"=>"0否1是"],
            ]
        ]
        , "setOldAdjustUser"=>[
            "name"=>"7天流失玩家邀请",
            "act"=>"setOldAdjustUser",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
                "toUid"=>["title"=>"被邀请者id*:","tips"=>""],
                "gid"=>["title"=>"设备*:","tips"=>"(1:android，2：ios)"],
                "deviceId"=>["title"=>"设备Id*:","tips"=>""],
            ]
        ]
        , "setInviteGiftStageNum"=>[
            "name"=>"设置邀请成功的数量接口",
            "act"=>"setInviteGiftStageNum",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
                "num"=>["title"=>"邀请成功数量*:","tips"=>""],
            ]
        ]
        , "setAdjustCallBack"=>[
            "name"=>"设置adjust回调",
            "act"=>"setAdjustCallBack",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"被邀请人uid*:","tips"=>""],
                "label"=>["title"=>"邀请人id*:","tips"=>""],
                "device"=>["title"=>"被邀请人设备ID*:","tips"=>""],
            ]
        ]
        , "run"=>[
            "name"=>"外部接口测试",
            "act"=>"run",
            "mod"=>"Test",
            "args"=>[
            ]
        ]
        , "setAttackInfo"=>[
            "name"=>"设置攻击对象",
            "act"=>"setAttackInfo",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
                "toUid"=>["title"=>"被攻击对象uid*:","tips"=>""],
            ]
        ]
        , "setStealInfo"=>[
            "name"=>"设置偷对象",
            "act"=>"setStealInfo",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
                "toUid"=>["title"=>"被偷对象uid*:","tips"=>""],
                "levelId"=>["title"=>"设定等级:","tips"=>""],
                "money"=>["title"=>"设定金币:","tips"=>""],
            ]
        ]
        , "delShare"=>[
            "name"=>"删除分享记录",
            "act"=>"delShare",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
            ]
        ]
        , "sendMessage"=>[
            "name"=>"发送消息",
            "act"=>"sendMessage",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
            ]
        ]
        , "assumeBindFb"=>[
            "name"=>"邀請假定绑定FB",
            "act"=>"assumeBindFb",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid*:","tips"=>""],
            ]
        ]
        , "InviteePush"=>[
            "name"=>"邀请领奖触发额外奖励",
            "act"=>"InviteePush",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"发出邀请方Uid*:","tips"=>""],
                "toUid"=>["title"=>"被邀请Uid*:","tips"=>""],
            ]
        ]
        , "refreshInvite"=>[
            "name"=>"添加邀请",
            "act"=>"refreshInvite",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"发出邀请方Uid*:","tips"=>""],
                "toUid"=>["title"=>"被邀请Uid*:","tips"=>""],
            ]
        ]
        , "delDailyChestActExpire"=>[
            "name"=>"删除每日宝箱购买时间",
            "act"=>"delDailyChestActExpire",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delDailyChestAct"=>[
            "name"=>"删除每日宝箱数据",
            "act"=>"delDailyChestAct",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delSignInUserGroup"=>[
            "name"=>"删除签到分组绑定",
            "act"=>"delSignInUserGroup",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delfund"=>[
            "name"=>"删除基金活动",
            "act"=>"delfund",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
                "delPay"=>["title"=>"删除支付*:","tips"=>""],
                "delStatus"=>["title"=>"删除状态:","tips"=>""],
                "delAct"=>["title"=>"删除活动绑定:","tips"=>""],
                "delReissue"=>["title"=>"删除补签记录:","tips"=>""],
            ]
        ]
        , "delInvite"=>[
            "name"=>"删除邀请记录",
            "act"=>"delInviterInfo",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "setCard"=>[
            "name"=>"设置卡片数量",
            "act"=>"setCard",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
                "ciid"=>["title"=>"卡片ID*:","tips"=>""],
                "num"=>["title"=>"卡片数量，0删除*:","tips"=>""],
            ]
        ]
        , "setCardNum"=>[
            "name"=>"设置卡片数量--除每组卡第一张全8张",
            "act"=>"setCardNum",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delJokerCard"=>[
            "name"=>"删除小丑卡",
            "act"=>"delJokerCard",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delAllCard"=>[
            "name"=>"删除所有卡片",
            "act"=>"delAllCard",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "safeBoxLimit"=>[
            "name"=>"触发保险柜限时奖励",
            "act"=>"safeBoxLimit",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "addSafeBox"=>[
            "name"=>"设置保险柜数值",
            "act"=>"addSafeBox",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
                "num"=>["title"=>"	数量*:","tips"=>""],
            ]
        ]
        , "delSafeBox"=>[
            "name"=>"删除保险柜",
            "act"=>"delSafeBox",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "setVip"=>[
            "name"=>"设置vip",
            "act"=>"setVip",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
                "point"=>["title"=>"vip积分*:","tips"=>""],
            ]
        ]
        , "delVip"=>[
            "name"=>"删除vip",
            "act"=>"delVip",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delVipDailyReward"=>[
            "name"=>"删除vip奖励领取记录",
            "act"=>"delVipDailyReward",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delLuckyDraw"=>[
            "name"=>"删除夺宝",
            "act"=>"delLuckyDraw",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delTrafficPermit"=>[
            "name"=>"删除通行证",
            "act"=>"delTrafficPermit",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "pushTrafficPermit"=>[
            "name"=>"通行证广播",
            "act"=>"pushTrafficPermit",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delete"=>[
            "name"=>"删除好友",
            "act"=>"delete",
            "mod"=>"Friend",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
                "toUid"=>["title"=>"对方用户ID*:","tips"=>""],
            ]
        ]
        , "delLimitGift"=>[
            "name"=>"删除限定礼包",
            "act"=>"delLimitGift",
            "mod"=>"Friend",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delSerialPack"=>[
            "name"=>"删除连环礼包",
            "act"=>"delSerialPack",
            "mod"=>"Friend",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delFirstPay"=>[
            "name"=>"删除首冲",
            "act"=>"delFirstPay",
            "mod"=>"Friend",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
                "gid"=>["title"=>"	首冲商品ID*:","tips"=>""],
            ]
        ]
        , "deletePet"=>[
            "name"=>"删除宠物",
            "act"=>"deletePet",
            "mod"=>"Friend",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delStarExchange"=>[
            "name"=>"删除兑换星星转态",
            "act"=>"delStarExchange",
            "mod"=>"Friend",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delFriendGift"=>[
            "name"=>"删除好友礼物",
            "act"=>"delFriendGift",
            "mod"=>"Friend",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delMingGame"=>[
            "name"=>"删除邀请矿工小游戏",
            "act"=>"delMingGame",
            "mod"=>"Friend",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        , "delFirstSlot"=>[
            "name"=>"删除当日首次老虎机概率状态",
            "act"=>"delFirstSlot",
            "mod"=>"Friend",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
            ]
        ]
        ,"setFruitGameInfo"=>[
            "name"=>"设置用户水果机信息",
            "act"=>"setFruitGameInfo",
            "mod"=>"this",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
                "freeTime"=>["title"=>"免费倒计时(单位/秒):","tips"=>"可选,0表示立即重置"],
                "paylimit"=>["title"=>"付费次数:","tips"=>"可选"],
            ]
        ]
        ,"addInviteActNum"=>[
            "name"=>"添加限时邀请记录",
            "act"=>"addInviteActNum",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>""],
                "fid"=>["title"=>"好友uid:","tips"=>"可选"],
                "num"=>["title"=>"批量人数:","tips"=>"可选"],
            ]
        ]
        , "setRankActivityNum"=>[
            "name"=>"设置锦标赛积分",
            "act"=>"setRankActivityNum",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
                "rankNum"=>["title"=>"指定积分值:","tips"=>"必选,需用户进入房间"],
            ]
        ]
        ,"setCollectJigswInfo"=>[
            "name"=>"设置用户拼图信息",
            "act"=>"setCollectJigswInfo",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
                "stage"=>["title"=>"指定阶段:","tips"=>"必选"],
                "sumNum"=>["title"=>"指定收集总数:","tips"=>"必选"],
            ]
        ]
        ,"changePetFeedTime"=>[
            "name"=>"清除宠物喂养时间",
            "act"=>"changePetFeedTime",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
                "petId"=>["title"=>"宠物id:","tips"=>"必选"],
            ]
        ],"clearAdInfo"=>[
            "name"=>"清除广告次数",
            "act"=>"clearAdInfo",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
            ]
        ]
        ,"getUserDayLimit"=>[
            "name"=>"获取用户每日数据",
            "act"=>"getUserDayLimit",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
            ]
        ],"reSetUserDayLimit"=>[
            "name"=>"重置用户每日数据",
            "act"=>"reSetUserDayLimit",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
            ]
        ]
        ,"setShushuGroups"=>[
            "name"=>"设置用户数数分组",
            "act"=>"setShushuGroups",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
                "groups"=>["title"=>"数数分组id:","tips"=>"必选，逗号分割"],
            ]
        ],"setPetLv"=>[
            "name"=>"设置用户宠物等级",
            "act"=>"setPetLv",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
                "petId"=>["title"=>"宠物id:","tips"=>"必选，可选值1，2，3"],
                "lv"=>["title"=>"宠物等级:","tips"=>"必选，整数"],
            ]
        ]
        ,"setUserCreatetime"=>[
            "name"=>"设置用户注册时间",
            "act"=>"setUserCreatetime",
            "mod"=>"this",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
                "createtime"=>["title"=>"时间戳:","tips"=>"必填，时间戳"],
            ]
        ]
        ,"setUserLasttime"=>[
            "name"=>"设置用户最后登录时间",
            "act"=>"setUserLasttime",
            "mod"=>"this",
            "args"=>[
                "uid"=>["title"=>"玩家Uid*:","tips"=>"必选"],
                "lasttime"=>["title"=>"日期:","tips"=>"如：20210101"],
            ]
        ]
        ,"delRedisKey"=>[
            "name"=>"删除redis key",
            "act"=>"delRedisKey",
            "mod"=>"this",
            "args"=>[
                "key"=>["title"=>"redis Key:","tips"=>"必选  多个key','分割"]
            ]
        ]
        ,"actBindAids"=>[
            "name"=>"查询用户绑定活动ID列表",
            "act"=>"actBindAids",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid:","tips"=>"必填"],
            ]
        ]
        ,"unbindAct"=>[
            "name"=>"用户解绑活动类型",
            "act"=>"unbindAct",
            "mod"=>"Test",
            "args"=>[
                "uid"=>["title"=>"用户uid:","tips"=>"必填"],
                "actType"=>["title"=>"活动类型:","tips"=>"必填"],
            ]
        ]
        ,"addRankRobot"=>[
            "name"=>"锦标赛加机器人",
            "act"=>"addRankRobot",
            "mod"=>"this",
            "args"=>[
                "uid"=>["title"=>"用户uid:","tips"=>"必填"],
                "actType"=>["title"=>"活动类型:","tips"=>"必填（rank(有进度) 或者 rank2(无进度) ）"],
                "num"=>["title"=>"加机器人数:","tips"=>"必填"],
            ]
        ]
        ,"newUserCollectDataClear"=>[
            "name"=>"新手收集用户进度清理",
            "act"=>"newUserCollectDataClear",
            "mod"=>"this",
            "args"=>[
                "uid"=>["title"=>"用户uid:","tips"=>"必填"],
            ]
        ]

    ];
    public function apiResponse($code, $msg, $data = []){
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];
        return json_encode($result);
    }
    public function tool(){
        $oos_debug = $this->config->item('oos_debug');
        if(!$oos_debug)$this->apiArr = [];
        $this->load->view('gm/tool',['data' => $this->apiArr]);
    }
    public function sendRequest(){
        $oos_debug = $this->config->item('oos_debug');
        if(!$oos_debug) return $this->response(0, '非法操作');
        $input = $this->input->post();
        $info=$this->apiArr[$input['type']];
        $data["sid"]=1;
        $data["lid"]=1;
        $data["service"]=1;
        $data["act"]=$info["act"];
        $data["mod"]=$info["mod"];
        foreach ($info['args'] as $k=>$v){
            $data[$k] = $input[$k];
        }
        if($data['mod'] == 'this'){
            if(!method_exists($this, $info["act"] ))$this->response(-1, '方法不存在:'.$info["act"] );
            $rs = $this->{$info["act"]}($data);
        }
        else
            $rs = $this->curl->req($this->config->item('officialUrl'), $data);
//        var_dump($rs);
        return $this->response(0, '发送请求成功',json_decode($rs,true));
    }

    private function setUserCreatetime($input){
        $uid = max(intval($input['uid']), 0);
        if(empty($uid))return $this->apiResponse(-1,'uid不能为空');
        if(empty($input['createtime']))return $this->apiResponse(-1,'createtime不能为空');
        $cacheKey = okeys::t_userinfoNew($uid);
        $table = otable::userinfo();
        $res = oo::commonOprDb('games')->query("update {$table} set `createtime`='{$input['createtime']}' where `uid`={$uid}");
        if(!$res)return $this->apiResponse(-1 * __LINE__,'设置失败');
        $res1 = oo::commonOprRedis('games')->hSet($cacheKey, 'createtime', $input['createtime']);
        return $this->apiResponse(__LINE__,'设置成功',[$input, $res, $res1]);
    }

    private function setUserLasttime($input){
        $uid = max(intval($input['uid']), 0);
        if(empty($uid))return $this->apiResponse(-1,'uid不能为空');
        if(empty($input['lasttime']))return $this->apiResponse(-1,'lasttime不能为空');
        $lasttime = strtotime($input['lasttime'])+60*5;
        $cacheKey = okeys::t_userinfoNew($uid);
        $table = otable::userinfo();
        $res = oo::commonOprDb('games')->query("update {$table} set `lasttime`='{$lasttime}' where `uid`={$uid}");
        if(!$res)return $this->apiResponse(-1 * __LINE__,'设置失败');
        $res1 = oo::commonOprRedis('games')->hSet($cacheKey, 'lasttime', $lasttime);
        return $this->apiResponse(__LINE__,'设置成功',[$input, $res, $res1]);
    }
    private function delRedisKey($input){
        $key = $input['key'];
        if(empty($key))return $this->apiResponse(-1,'key不能为空');
        if(strpos($key, '*') !== false)return $this->apiResponse(-1,'key不能包含‘*’');
        $keys = explode(',', $key);
        $keys = array_map(function($v){return trim($v);}, $keys);
        $res = oo::commonOprRedis('games')->delete($keys);
        if(!$res)return $this->apiResponse(-1 * __LINE__,'操作失败');
        return $this->apiResponse(__LINE__,'操作成功',[$input, $res]);
    }
    private function setFruitGameInfo($input){
        if($input['freeTime']){
            oo::commonOprRedis('games')->expire(okeys::UserFruitFreeTime($input['uid']),$input['freeTime']);
//            oo::commonOprRedis('games')->delete(okeys::UserFruitFreeTime($input['uid']));
        }
        if(isset($input['paylimit'])){
            oo::commonOprRedis('games')->set(okeys::UserFruitPayLimit($input['uid']),intval($input['paylimit']));
        }
        $ts =oo::commonOprRedis('games')->ttl(okeys::UserFruitFreeTime($input['uid']));
        $ret =[
            "freeLimitTimes"=>$ts<0?0:$ts,
            "paylimit"=>oo::commonOprRedis('games')->get(okeys::UserFruitPayLimit($input['uid'])),
        ];
        return $this->apiResponse(__LINE__,'操作成功',[$input, $ret]);
    }
    private function addRankRobot($input){
        $uid = $input['uid'];
        $type = $input['actType'];
        $limit = $input['num'];
        $bindKey = okeys::userBindActivity($type, $uid);
        $aid = oo::commonOprRedis('games')->get($bindKey);
        if($aid<1){
            oo::response(-1,['info' => '操作失败,未找到活动' ],'操作失败,未找到活动');
        }
        $roomId = oo::commonOprRedis('games')->hGet(okeys::activityUserRankBindRoomId($aid),$uid);
        if($roomId<1){
            oo::response(-1,['info' => '操作失败,未加入锦标赛房间' ],'操作失败,未加入锦标赛房间');
        }
        $robotList = oo::commonOprModel('member')->getAllRobot();
//    $key =  okeys::activityUserRankBindRoomId($aid);
//    $uidRoomList =  oo::commonOprRedis('activity')->hGetAll($key);
        $key = okeys::activityUserRankList($aid,$roomId);
        $i = 0;
        foreach ($robotList as $ruid){
            oo::commonOprRedis('games')->hSet(okeys::activityRoomUserList($aid,$roomId),$ruid,1);//房间内加人
            $num = mt_rand(8,500);
            oo::commonOprRedis('games')->zAdd($key,$num,$ruid);
            $i++;
            if($i>=$limit){
                break;
            }
        }
        oo::response(1,['info' => '操作成功' ],'操作成功');
    }

    private function newUserCollectDataClear($input)
    {
        $uid = $input['uid'];
        $key = okeys::NewPlayerCollectUserData($uid);

        $res = oo::commonOprRedis('games')->hMset($key, ["stage" => 1, "rate" => 0]);
        if (!$res) return $this->apiResponse(-1 * __LINE__, '操作失败');
        return $this->apiResponse(__LINE__, '操作成功', [$input, $res]);
    }
}
