<?php
ini_set("display_errors", "On");//打开错误提示
ini_set("error_reporting",E_ALL);//显示所有错误
header('Access-Control-Allow-Origin:*');
defined('IN_WEB') or define('IN_WEB', true);
$_REQUEST['sid'] =$sid =1;
$_REQUEST['lid'] = $lid =1;
// include (dirname(__FILE__)."/api/protocols.php");//解码
include_once dirname(__FILE__)."/com.php";
require_once __DIR__ . '/vendor/autoload.php';
defined('PRODUCTION_SERVER') or define('PRODUCTION_SERVER', true);//是否产品
ini_set('max_execution_time', 3600);
if(strpos(php_sapi_name(), 'cli') !== false){

    define("IS_CLI",true);
}else{

    define("IS_CLI",false);
}



class Test {
    public function expPlus(){
        $aid=6106;
        $list = oo::commonOprRedis('common')->hGetAll(okeys::TrafficPermitCurNum($aid));
        $i=0;
        foreach ($list as $uid=>$exp){
            $exp = intval($exp);
            if(intval($uid)==0) continue;
            $newExp  = intval(oo::commonOprRedis('activity')->hGet(okeys::TrafficPermitUser($aid, $uid),'exp'));
            if($exp>$newExp){
                oo::commonOprRedis('activity')->hIncrBy(okeys::TrafficPermitUser($aid, $uid),'exp',$exp);
                $i++;
            }
        }
        echo $i;
    }

    public function t1(){
        $bool = true;
        var_dump(json_encode($bool));
        $str = 'true';
        var_dump(json_decode($str, true));
        return [1,2];
    }

    public function checkGoogleOrder(){
        $ret = oo::commonOprModel('paymentgoogle')->getGoogleOrderInfo('com.gworld.cc.gift01', 'pagjncigjclbkgokolgnkngo.AO-J1OxIne7Bn7kgaxkKPUwXSr0TX5dt6A5FLAB51JUCsd4qvw1ZeNcgSS6IrrLuTfMiOqLre0R25QQrptqq7iHIBXoFoTiJAA');
        var_dump($ret);
    }
    public function getfoxonline(){
        $timestamp = time();
        $onlineNum = oo::commonOprModel('recordonline')->getAliMonitor();
        oo::commonOprModel('recordonline')->saveFoxRealTimeOnline($timestamp, $onlineNum);
    }
    public function summaryCard($params = []){
        ini_set('memory_limit', -1);
        $beginTime = strtotime('2021-11-04');
        $endTime = strtotime('2021-11-05');
        $res = [];
        for($timestamp = $beginTime;$timestamp<$endTime;$timestamp+=86400){
            $date = date('Ymd', $timestamp);
            echo $date.PHP_EOL;
//            continue;
            $cardInfoTbl = otable::cardinfo_config();
            $cardInfo    = oo::commonOprDb('common')->getAll("select * from {$cardInfoTbl}",1);
            $cardInfo = array_column($cardInfo, null, 'ciid');
            $sql = "select * from (  ";
            for ($i = 0;$i<10;$i++){
                $table = otable::AssetslogNew($date, $i);
                $sql .= "select * from {$table} where type='card'  union all ";
            }
            $sql = rtrim($sql, 'union all ');
            $sql .= " ) t1 ";
//        $sql .= " ) t1 limit 1000";
            $result = oo::commonOprDb('statistics')->getAll($sql,1);
            $cardSummary = [
                '木质宝箱' => [
                    'count' => 0,
                    'total' => 0,
                    'rank1' => 0,
                    'rank2' => 0,
                    'rank3' => 0,
                    'rank4' => 0,
                    'rank5' => 0,
                    'golden' => 0,
                ],
                '白银宝箱' => [
                    'count' => 0,
                    'total' => 0,
                    'rank1' => 0,
                    'rank2' => 0,
                    'rank3' => 0,
                    'rank4' => 0,
                    'rank5' => 0,
                    'golden' => 0,
                ],
                '黄金宝箱' => [
                    'count' => 0,
                    'total' => 0,
                    'rank1' => 0,
                    'rank2' => 0,
                    'rank3' => 0,
                    'rank4' => 0,
                    'rank5' => 0,
                    'golden' => 0,
                ],
            ];
            foreach ($result as $k => $item){
                if(!strpos($item['reason'], ':'))continue;
                list($chest, $cardStrs) = explode(':', $item['reason']);
                if(empty($cardSummary[$chest]))continue;
                $cardsIds = explode(',', $cardStrs);
                $cardSummary[$chest]['count']++;
                foreach ($cardsIds as $ciid){
                    if(empty($cardInfo[$ciid]))continue;
                    $cardSummary[$chest]['total']++;
                    $cardSummary[$chest]['rank'.$cardInfo[$ciid]['ci_star_rank']]++;
                    if($cardInfo[$ciid]['grade'] == 2)$cardSummary[$chest]['golden']++;
                }
            }
            $data = json_encode($cardSummary, JSON_UNESCAPED_UNICODE);
            $tb = otable::cardAssertSummary();
            $type = 1;
            $sql = "INSERT INTO {$tb} (`date`, `game_version`, `data`)  VALUES('{$date}', '{$type}' ,'{$data}')";
            $res[$date] = oo::commonOprDb('statistics')->query($sql);
        }
        return [$res];
    }

    public function crontabT(){
        $beginTime = strtotime('2021-11-09');
        $endTime = strtotime('2021-11-10');
        $res = [];
        for($timestamp = $beginTime;$timestamp<=$endTime;$timestamp+=86400) {

            $types = [1, 2];
            foreach ($types as $type){
                $res[date('Ymd', $timestamp). '-'.$type] = oo::commonOprModel('recordonline')->cardAssertSummary($timestamp, $type);
            }
        }
        return $res;
    }
    public function iniGet(){
        $memory_limit = ini_get('memory_limit');
        return $memory_limit;
    }

    public function queryReloginUsers(){
        $file = './txts/t3';
        $f = fopen($file, 'r+');
        $uids = [];
        while(!feof($f)){
            $line = fgets($f);
            $uid = trim($line, "\r\n");
            $uid = trim($uid, "\n");
            $uids[] = $uid;
        }
        $uids = array_filter($uids);
        fclose($f);
        echo 'all users cnt:'.count($uids) . PHP_EOL;
        $userTbl = otable::userinfo();
//        $uidsArr = array_chunk($uids, 6000);
        $loginCnt = 0;
//        foreach ($uidsArr as $uids){
            $uidStr = implode(',', $uids);
            $sql = "select uid from {$userTbl} where  lasttime >=1635379200 and uid in ({$uidStr}) ";
            $users = oo::commonOprDb('userinfo')->getAll($sql, 1);
            $loginCnt += count($users);
//        }
        echo 'login users cnt:' . $loginCnt . PHP_EOL;
        echo $sql . PHP_EOL;
    }

    public function getSigninConf()
    {
        $conf = [
            'daily' => array_values(oo::commonOprModel('config')->signInConfByUserGroup(533896, 0, true)),
            'progress' => array_values(oo::commonOprModel('config')->userSignInProgressConf(533896))
        ];

        return $conf;
    }

    public function getFriends(){
        $uid = 2535914;
        $friends = oo::commonOprModel('friend')->getUserAllFriend($uid);
        return $friends;
    }

    public function ggorder(){
        $table = otable::vipPaymentLog();
        $sql = "select * from {$table} where datetime > 1636574400 and datetime<1636581600";
        $records = oo::commonOprDb('api_log')->getAll($sql, 1);
        foreach ($records as $record){
            $json = json_decode($record['data'], true);

        }
    }

    public function getPro(){
        $arr = [
            '打' =>60,
            '偷' =>25,
            '体力' =>1,
            '盾' =>40,
            '钱1' =>183,
            '钱2' =>120,
            '钱3' =>80,
            '钱4' =>161,
            '钱5' =>100,
            '钱6' =>60,
            '空' =>30,
            '收集1' =>240,
            '收集2' =>120,
            '收集3' =>30,
        ];
        $proArr = [];
        $sum = array_sum($arr);
        foreach ($arr as $k => $item){
            $proArr[$k] = number_format($item/$sum*100, 2).'%';
        }
        echo json_encode($proArr);
    }

    public function getLang(){
        $uid = 2595564;
        $lang = oo::commonOprModel('member')->getUserLang($uid);
        return $lang;
    }
    public function getMsg(){
        $uid = 2595564;
        $sid = 1;
        if(empty($uid)){
            return oo::response(-1);
        }
        $ret = oo::commonOprModel('message')->getSysMailMsgByUid($uid, $sid);
        return $ret;
    }

    public function onlineFox(){
        $timestamp = empty($timestamp) ? time() : $timestamp ;
        $start = $timestamp - 5400;
        $onlineCntArr = oo::commonOprRedis('common')->zRangeByScore(okeys::foxRealTimeOnlineKey(),$start, $timestamp,['withscores'=>true]);
        $onlineData = [];
        foreach ($onlineCntArr as $uid => $timestamp){
            $dateHi = date('YmdHi', $timestamp);
            $onlineData[$dateHi] = $onlineData[$dateHi] ?? 0;
            $onlineData[$dateHi]++;
        }
        return json_encode($onlineData);
    }
    public function onlineFoxTopday(){
        $timestamp = empty($timestamp) ? time() : $timestamp ;
//        $ret = oo::commonOprRedis('statistics')->hGetAll(okeys::onlineCountLog(date('Ymd', $timestamp)));
        $ret = oo::commonOprRedis('statistics')->hGetAll(okeys::onlineCountLog());
        ksort($ret);
        $onlineArr = [];
        foreach ($ret as $time => $item){
            $hi = date('H:i', $time);
            $onlineArr[$hi] = $item;
        }
        return $onlineArr;
    }

    public function getAliMonitor(){
        return oo::commonOprModel('recordonline')->getAliMonitor();//每分钟在线用户统计
    }

    public function exportPayedUsers($argvs = []){
        $time = time();
        $datetime = date('YmdHis');
        $year = $argvs[0] ?? date('Y', $time);
        $begin = strtotime($year.'-01-01');
        $year++;
        $end = strtotime($year.'-01-01');
        $summaryTbl = otable::summarylist();
        $userTbl = otable::userinfo();
        $userAddressTbl = otable::useraddress();

        $sql = "select sl_uid, sum(sl_pusd) as payedTotal, count(1) as payedCnt from {$summaryTbl} where sl_pay_time>={$begin} and sl_pay_time <={$end} and sl_status=2 group by sl_uid";
        echo $sql . PHP_EOL;
        $userPayedResult = oo::commonOprDb('slave')->getAll($sql, 1);
        $userArrs = array_chunk($userPayedResult, 2000);
        $results = [];

        $file = __DIR__ . "/deBUG/csvs/{$year}PayedUsers.csv";
        if(is_file($file))unlink($file);
        $f = fopen($file, 'w');
        $header = [
            'uid', '昵称', 'FN', 'LN', 'Email', '性别', '国家',  '注册时间', '最后登陆时间',"付费金额({$year})","付费次数({$year})"
        ];
        fputcsv($f, $header);
        $cnt = 0;
        foreach ($userArrs as $userArr){
            $uids = array_map(function($v){return $v['sl_uid'];}, $userArr);
            $uids[] = 0;
            $uidStr = implode(',',$uids);
            $sql = "select * from {$userTbl} tu inner join {$userAddressTbl} ta on ta.uid=tu.uid  where tu.uid in ({$uidStr})";
            $userInfos = oo::commonOprDb('slave')->getAll($sql, 1);
            $userInfos = array_column($userInfos, null, 'uid');
            foreach ($userArr as $user){
                $user = array_merge($user, (array)$userInfos[$user['sl_uid']]);
                list($fn, $ln) = $this->divideName($user['nick']);
                $lineData = [
                    $user['uid'], $user['nick'], $fn, $ln, $user['email'], $user['sex'], $user['country_code'], date('Y-m-d H:i:s', $user['createtime']), $user['payedTotal'], $user['payedCnt']
                ];
                fputcsv($f, $lineData);
                $cnt++;
            }
        }

        return [count($results), $cnt];
    }
    private function divideName($name){
        $nameArr = explode(' ', $name);
        $firstName = array_shift($nameArr);
        return [$firstName, implode(' ', $nameArr)];
    }

    public function sendRank2(){
        $aid = 8496;
        $res = oo::commonOprModel('activitynew')->checkRankRewardRobotNoPro($aid);
        var_dump($res);
    }
}

echo 'config path:'.PATH_CFG . PHP_EOL;
echo 'begin:'.microtime() . PHP_EOL;
if(IS_CLI){
    if(empty($argv[1])){
        exit('params error!' . PHP_EOL);
    }
    $method = $argv[1];
    $obj = new Test();
    if(!method_exists($obj, $method))exit('method not found:'.$method);
    unset($argv[0],$argv[1]);

    $response = $obj->$method(array_values($argv));
    if(!is_scalar($response))$response = json_encode($response) ;
    echo $response . PHP_EOL;
}else{
    echo json_encode($_REQUEST) . PHP_EOL;
}
echo 'end:'.microtime() . PHP_EOL;
//=====================================
//$etime = microtime();
//echo "<hr>";
//echo "耗时：".($etime-$stime)."<br>";
//echo "<hr>";
//echo '长度:'.(is_array($list)?count($list):strlen($list))."<br>";
//echo "<pre>";
//print_r($list);
//=====================================

