<?php
if (substr(PHP_SAPI_NAME(), 0, 3) !== 'cli') {
    die("The program runs only in CLI mode!");
}
$sid = $lid = 1;
include_once dirname(__FILE__) . "/crontab.inc.php";
include_once dirname(__FILE__) . "/../com.php";
set_time_limit(0);

//新登录记录
function writeNewLoginLog(){
    $td = date('Ymd');
    $query = "SHOW TABLES LIKE 'new_login_log_$td'";
    $tbInfo = oo::commonOprDb('api_log')->getOne($query,1);
    $res1 =true;
    if(empty($tbInfo)){
        $sql = oo::cfg('sql')['new_login_log'];
        $sql = str_replace('#table#', "new_login_log_{$td}", $sql);
        $res1 =oo::commonOprDb('api_log')->query($sql);
    }
    $fields =["uid","sid","lv","version","ip","deviceId","deviceInfos","ts","ab"];
    if($res1){
        $yd = date('Ymd',strtotime('-1 day'));
        $old_key = "API_LOGS:{$yd}-loginNew";
        if(oo::commonOprRedis('statistics')->exists($old_key)){//还存在昨天的
            $tb = "crazygod_api_log.new_login_log_{$yd}";
            $list = oo::commonOprRedis('statistics')->lGetRange($old_key,0,-1);
//            foreach($list as $k => $v){
//                $v = json_decode($v, true);
//                if(!is_array($v)){
//                    continue;
//                }
//                $v[] = getUserAbKey($v[0]);
//                $list[$k] = json_encode($v);
//            }

            $sql2 =funs::db_intsertArrSQL($tb,$fields,$list,1);
            $res2 = oo::commonOprDb('api_log')->query($sql2);
            if($res2){
                oo::commonOprRedis('statistics')->delete($old_key);
            }
        }
        $key = "API_LOGS:{$td}-loginNew";
        $len = oo::commonOprRedis('statistics')->lLen($key);
        if($len>0){
            if($len>5000){
                $len = 5000;
            }
            $tb = "crazygod_api_log.new_login_log_{$td}";
            $list = oo::commonOprRedis('statistics')->lGetRange($key,0,$len-1);

//            foreach($list as $k => $v){
//                $v = json_decode($v, true);
//                if(!is_array($v)){
//                    continue;
//                }
//                $v[] = getUserAbKey($v[0]);
//                $list[$k] = json_encode($v);
//            }

            $sql3 = funs::db_intsertArrSQL($tb,$fields,$list,1);
            $res3 = oo::commonOprDb('api_log')->query($sql3);
//            if($res3){
                oo::commonOprRedis('statistics')->lTrim($key,$len,-1);
//            }
        }
    }
}

function getUserAbKey($uid) {
    $abKey = oo::commonOprRedis('common')->hGet(okeys::UserAbTest(), $uid);
    if(empty($key) || $key < 1){
        $key = 'D';
    }elseif($key > 2){
        $key = 'C';
    }else{
        $key = $key == '1' ?  'A' : 'B';
    }
    return $key;
}



writeNewLoginLog();

//writeLoginLog();//过度清理
//writeConnectLog();//过度清理

