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

/*
* 定时器
*/
class Crontab extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		
		//防止http访问
		if(!$this->is_cli()){
			die("ip error");
		}
		
		$this->load->model('oo');
	}

    //从正式数据库拉去上一天的登录注册用户信息
    public function pullLoginRegLog(){
        set_time_limit(0);
        date_default_timezone_set("UTC");
        $i = 1;
        $date = date('Ymd', time() - ( 86400 * $i ));

//        for($i = 2;$i < 105; $i++){
//            $date = date('Ymd', time() - ( 86400 * $i ));
//            echo "------{$date}--------". PHP_EOL;
//            oo::commonOprModel('crontab')->pullLoginRegLog($date);
//        }

        echo "------{$date}--------". PHP_EOL;
        oo::commonOprModel('crontab')->pullLoginRegLog($date);
    }

    public function foxRealTimeOnline($timestamp = 0){
        $timestamp = empty($timestamp) ? time() : $timestamp ;
        oo::commonOprModel('Crontab')->foxRealTimeOnline($timestamp); // 读fox实时在线
    }

    public function exportLostUser($year = 2021){
        set_time_limit(0);
        date_default_timezone_set("UTC");
        ini_set('memory_limit', -1);
        $userTbl = otable::userinfo();
        $userAddressTbl = otable::useraddress();
        $gameinfoTbl = otable::gh_gameserver();
        $dynamicTbl = otable::UserDynamicsData();
        $friendTbl = otable::userfriends(1);
        $paymentTbl = otable::order();

        $timestamp = time();
        $date = date('Y-m-d',$timestamp);
        $datetime = date('YmdHi', $timestamp);
//        if($year == date('Y', $timestamp)){
//            $lastLoginTimeBegin = strtotime($year.'-01-01');
//            $lastLoginTimeEnd   = strtotime($date) - 7 * 86400;
//        }else{
//            $lastLoginTimeBegin = strtotime($year.'-01-01');
//            $lastLoginTimeEnd   = strtotime('+1 year', $lastLoginTimeBegin);
//        }

        $where = ' 1';
        $lastLoginTimeBegin   = strtotime($date) - 90 * 86400;
        $lastLoginTimeEnd   = strtotime($date) - 7 * 86400;
        $where .= " and tu.lasttime <= {$lastLoginTimeEnd}  and tu.lasttime > {$lastLoginTimeBegin}";
        $countryArr = ['TH'];
        if(!empty($countryArr)){
            $countryStr = implode("','", $countryArr);
            $where .= " and  ta.country_code in ('{$countryStr}') ";
        }
        $where .= " and tu.isFb=1 ";
        $file = __DIR__ . "/../../deBUG/csvs/{$datetime}lostUsers.csv";
        $f = fopen($file, 'w');
        $header = [
            'uid', '昵称', 'FN', 'LN', 'Email', '性别', '国家', '金额', '注册时间', '最后登陆时间','流失时等级','流失时好友数','流失时体力数','流失时金币数','流失时星星数','累计活跃天数'
        ];
        fputcsv($f, $header);

        $page = 1;
        $limit = 1000;
        $processedCnt = 0;
        while(true){
            $offset = ($page - 1) * $limit;
            $sql = "select * from {$userTbl} tu inner join {$userAddressTbl} ta on ta.uid=tu.uid  where {$where}  limit {$offset},{$limit} ";
//        $sql = "select * from {$userTbl} tu inner join {$userAddressTbl} ta on ta.uid=tu.uid  where tu.lasttime <= {$lastLoginTimeEnd}  and tu.lasttime > {$lastLoginTimeBegin}  and  ta.country_code in ('FR', 'DE') limit 20";
            $result = oo::commonOprDb('gameslave')->getAll($sql, 1);
            $page++;

            $uids = array_map(function($v){return $v['uid'];}, $result);
            $uidStr = implode(',', $uids);

            $userGameInfos = oo::commonOprDb('gameslave')->getAll("select * from {$gameinfoTbl} where mid in ({$uidStr}) ", 1);
            $userGameInfos = array_column($userGameInfos, null, 'mid');

            $dynamicInfos = oo::commonOprDb('gameslave')->getAll("select * from {$dynamicTbl} where uid in ({$uidStr}) ", 1);
            $dynamicInfos = array_column($dynamicInfos, null, 'uid');

            $friendsInfos = oo::commonOprDb('gameslave')->getAll("select * from {$friendTbl} where uid in ({$uidStr}) ", 1);
            $friendsInfos = array_column($friendsInfos, null, 'uid');

            $paymentInfos = oo::commonOprDb('gameslave')->getAll("select sum(price) as money ,uid from {$paymentTbl} where uid in ({$uidStr})  and  status=4 group by uid", 1);
            $paymentInfos = array_column($paymentInfos, 'money', 'uid');

            foreach ($result as $k => $user){
                $processedCnt++;
                $uid = $user['uid'];
                $regTime = date('Y-m-d H:i:s', $user['createtime']);
                $payedMoney = empty($paymentInfos[$uid]) ? 0.00 : $paymentInfos[$uid];
                $lastLoginTime = date('Y-m-d H:i:s', $user['lasttime']);
                list($fn, $ln) = $this->divideName($user['nick']);

                $gameInfo = empty($userGameInfos[$uid]) ? oo::commonOprDb('gameslave')->getOne("select * from {$gameinfoTbl} where mid='{$uid}'", 1) : $userGameInfos[$uid];
                $level = $gameInfo['levelId'];
                $spins= $gameInfo['spins'];
                $coins= $gameInfo['money'];
                $stars= $gameInfo['star'];

                $dynamicInfo = empty($dynamicInfos[$uid]) ? oo::commonOprDb('gameslave')->getOne("select * from {$dynamicTbl} where uid='{$uid}'", 1) : $dynamicInfos[$uid];
                $actDays= intval($dynamicInfo['activeDay']);

                $friendsInfo = empty($friendsInfos[$uid]) ? oo::commonOprDb('gameslave')->getOne("select * from {$friendTbl} where uid='{$uid}'", 1) : $friendsInfos[$uid];
                $friends = empty($friendsInfo['game_list']) ? [] : explode(',', $friendsInfo['game_list']);
                $friendCnt= count($friends);

                $line = [
                    $user['uid'], $user['nick'], $fn, $ln, $user['email'], $user['sex'],$user['country_code'], $payedMoney, $regTime, $lastLoginTime, $level, $friendCnt, $spins, $coins, $stars, $actDays
                ];
                fputcsv($f, $line);
                echo $processedCnt . PHP_EOL;
            }

            if(count($result) < $limit)
                break;
        }

        echo $datetime . PHP_EOL;
        fclose($f);
        echo 'ok';
	}
    private function divideName($name){
        $nameArr = explode(' ', $name);
        $firstName = array_shift($nameArr);
        return [$firstName, implode(' ', $nameArr)];
    }

	//触发php index.php Crontab crontab
	public function crontab(){
		set_time_limit(0);
		// G(小时，24 小时格式，没有前导零，0 到 23), i(有前导零的分钟数，00 到 59>)
		$now = time();
		$time = date('Gi', $now);
		$day = date("j"); // 月份中的第几天，没有前导零(1到31)
		$week = date('w');//星期中的星期几 周日是0 周一是1 依次排下去
		
		$minute = date('i');




        /**
         * 更新用戶分組 --- start
         */
        oo::commonOprModel('member')->updateUserGroup();
        oo::commonOprModel('member')->updateUserGroup2();
        oo::commonOprModel('member')->updateUserGroupByUid();
        if($time == '030'){
            //广告组删除移除用户数据
            oo::commonOprModel('member')->delUserGroupAction();
        }
        /**
         * 更新用戶分組 --- end
         */


        oo::commonOprModel('push')->crontabPush();// 定时推送

        if($time == "045"){ //上午9点自动刷新一次cdn md5，防止程序开发上传后忘记刷新
            oo::commonOprModel('Filemd5')->makeActivityMd5();
        }

        if($time == "2350"){
            //登陆事件上报 保存到数据库
            oo::commonOprModel('statistics')->saveLoginEventSta();
            oo::commonOprModel('Crontab')->coinsValue();
        }
        if($time == "2355"){
            //当天人均通关数（当天通关数 / 当天登陆用户数） 保存到数据库
            oo::commonOprModel('statistics')->saveTodayUpLvelSta();
        }
		if($time == "2358"){
			//事件统计
			oo::commonOprModel('statistics')->newGuideLost();
			//新手步骤统计 保存到数据库
		    oo::commonOprModel('statistics')->saveNoviceStepsSta();
		}
		
		if($time == "2357"){
			//关卡分布统计 保存到数据库
			oo::commonOprModel('statistics')->levelSta();
		}
		
		if($time == '001') {
			//广告事件上报
		  	oo::commonOprModel('statistics')->advertisement();
		  	//网络重连上报统计 保存到数据库
		  	oo::commonOprModel('statistics')->saveNetworkReportSta();
		  	//分享事件上报 保存到数据库
            oo::commonOprModel('statistics')->shareEventSta();
		}
		
		if($time == "002"){
			//adJust 統計
			oo::commonOprModel('statistics')->adJustSta();
		}
		
		if($time == '003'){
			//支付上报 保存到数据库
		    oo::commonOprModel('statistics')->savePayReportSta();
		    //每日金币、体力、盾牌存量统计 保存到数据库
		    oo::commonOprModel('statistics')->todayStockSta();
		    //商城促销统计 保存到数据库
		    oo::commonOprModel('statistics')->shopDiscountSta();
		}
		
		if($time == '004'){
			//金币体力发放消耗统计
		    oo::commonOprModel('statistics')->savePropertyStatistics();
		}
		
		if($time == '005'){
			//老虎机统计
		    oo::commonOprModel('statistics')->slotStatistics();
		    oo::commonOprModel('Crontab')->loginCountAndTime();
		}
		
		if($time == '006'){
			//打概率统计 击中率（损毁建筑） & 摧毁率（岛被打光）& 打到盾概率
		    oo::commonOprModel('statistics')->attackChanceSta();
		}
		
		if($time == '007'){
			//当天用户分组人数
		    oo::commonOprModel('statistics')->todayUserGroupSta();
		}
		
		if($time%5 == 0){
			//创建流水表
            oo::commonOprModel('currency')->cronCreatAssessTable();
//            oo::commonOprModel('currency')->cronCreatActAssessTable();
            //创建体力记录表
//            oo::commonOprModel('currency')->cronCreatSpinsAddLowTable();
		}
		
		if($time == '008'){
			//FB留存
		    oo::commonOprModel('statistics')->recordDataFB();
		}
		if($time == '009'){
			//体力分布统计 每天
			oo::commonOprModel('statistics')->todaySpinsSta();
		}
		if($time == '010'){
			//老虎机关卡概率统计
//		    oo::commonOprModel('statistics')->slotLevelStatistics('',1);
		}
		
		if($time == '015'){
			//宝藏探索数据统计
		    oo::commonOprModel('statistics')->treasureSlotSta();
		}
		
		if($time == '016'){
			//规则礼包统计 保存到数据库
		    oo::commonOprModel('statistics')->GiftEventSta();
		}
		
		if($time == '017'){
			//邀请事件上报 保存到数据库
		    oo::commonOprModel('statistics')->inviteEventSta();
		}
		
		if($time == '018'){
			//宝藏探索关卡统计 保存到数据库
		    oo::commonOprModel('statistics')->treasureSlotLevelSta();
		}
		
		if($time == '019'){
			//小丑卡统计 保存到数据库
		    oo::commonOprModel('statistics')->jokerCardSta();
		}

        if($time == '020'){
            //邮件统计
//            oo::commonOprModel('statistics')->sendMailSta();
        }
        if($time == '121'){
            //每日体力盈亏统计 保存到数据库
            oo::commonOprModel('statistics')->todaySpinsAddLowSta2();
        }
        if($time == '022'){
            //好友召回统计 保存到数据库
            oo::commonOprModel('statistics')->friendRecallSta();
        }
        if($time == '023'){
            ////统计特殊收集活动的特殊道具概率 保存到数据库
            //oo::commonOprModel('statistics')->superCollectSta();
        }
        //--------fox没存-wsc 2.24-----
        if($time == '024'){
            //redis 这一分钟可多设置几个定时器
            //后台增加老虎机体力统计/老虎机体力关卡概率统计
            oo::commonOprModel('statistics')->slotSpinsSta();
        }
        //--------fox没存-wsc 2.24-----
        if($time == '025'){//每日小丑宝箱1-10
            oo::commonOprModel('statistics')->saveDailyChest();
        }
        if($time == "035"){ //小游戏参与率统计
            ////////////////////////////////////////////////////////
            //小游戏统计暂时关闭,需要时再打开
            //oo::commonOprModel('statistics')->saveParticipation();
            ////////////////////////////////////////////////////////
        }
        if($time == "045"){
            //每日好友邀请进度奖励统计
            oo::commonOprModel('statistics')->saveInviteStageReward();
        }

        if($time == "055"){ //tradeplus分组统计
            oo::commonOprModel('tradeplus')->loopApiData();
        }

        if($time == '101'){
            //每日卡片发放产出统计 保存到数据库
            oo::commonOprModel('statistics')->cardGrantSta();
        }
        if($time == '102'){
            //好友召回留存统计
            oo::commonOprModel('statistics')->friendRecallremainSta();
        }
		
		oo::commonOprModel('report')->clientlog();

		logMessage('crontab',"crontab ".date("Ymd H:i:s"));
	}

    public function chmods()
    {
        $resourceRootPath = '/mnt/www/crazy_god_CMS/public/game/';
        $refreshList = [
            'image/activity_2/',
            'crazycoin/activity/Android/',
            'crazycoin/activity/iOS/',
            'crazycoin/version/Android/',
            'crazycoin/version/iOS/',
        ];
        foreach ($refreshList as $path){
            $resourcePath = $resourceRootPath . $path;
            if(is_dir($resourcePath)){
                echo $resourcePath . ' is dir' . PHP_EOL;
            }
            else{
                echo $resourcePath . ' is not dir' . PHP_EOL;
            }
            $dirHandle = opendir($resourcePath);
            while($file = readdir($dirHandle)){
                if(in_array($file, ['.', '..']))continue;
                $filePath = $resourcePath . $file ;
                $permit = substr(base_convert(fileperms($filePath), 10, 8), 2);
                if($permit == 777){
                    continue;
                }
                $cmd = 'sudo  chmod 777 -R ' . $filePath;
                echo 'cmd: '.$cmd . PHP_EOL;
//                exec($cmd, $result, $returns);
//                echo ' result:' . var_export($result) . ' returns:'.var_export($returns). PHP_EOL;

                $res = chmod($filePath, 0777);
                echo ' result:' . var_export($res) . PHP_EOL;
            }
        }

    }

	public function sendEmail(){
        oo::commonOprModel('Email')->verifyEmail(3); // 邮件验证
    }
    public function sendCallBackEmail(){
        oo::commonOprModel('Email')->callBackEmail(); //召回邮件
    }
    //转储到oos
    public function dbToOos($sql = '') {
        ini_set('max_execution_time', 3600);
        if(empty($sql)){
            exit("sql file error");
        }
        $res = oo::commonOprModel('common')->upToOss("database/{$sql}","/mnt2/database/{$sql}");
        if(!$res){
            exit("upload {$sql} data error");
        }
        exit("ok");
    }

    /**
     * 从oss下载到本地
     */
    public function ossToLocal($sql = '') {
        ini_set('max_execution_time', 3600);
        if(empty($sql)){
            exit("sql file error");
        }
        if(strrpos($sql, '.sql') === false){
            $sql = $sql.'.sql';
        }
        $res = oo::commonOprModel('common')->downloadFromOss("database/{$sql}","/mnt2/database/{$sql}");
        if(!$res){
            exit("upload {$sql} data error");
        }
        exit("ok");
    }

    public function assetsToCircle() {
        return;
        $date = date("Ymd");
        //$date = date("Ymd", time() - 86400);
        for($i = 0; $i < 10; $i++){
            $sql = 'INSERT INTO '.otable::Assetslog($date, $i).' (uid,type,num,crease,reason,time,last_num,rid,levelId)';
            $sql .= ' SELECT uid,type,num,crease,reason,time,last_num,rid,levelId FROM '.otable::Assetslog($date, -1) . ' WHERE uid % 10 = '.$i;
            oo::commonOprDb('log')->query($sql);
        }
    }

	//2号定时器
	public function crontablog(){
		set_time_limit(0);
        $random = mt_rand(1,100000);
		if(oo::commonOprRedis('Statistics')->setnxex(okeys::CrontabLock('crontablog'),$random,300)){
            //转盘流水落地
            oo::commonOprModel('asynclog')->cacheIntoDb();
            //先判断随机数，是同一个则删除锁
            if (oo::commonOprRedis('Statistics')->get(okeys::CrontabLock('crontablog')) == $random) {
                oo::commonOprRedis('Statistics')->delete(okeys::CrontabLock('crontablog'));
            }
        }else{
		    echo 'lock';
        }
		logMessage('crontab',"crontablog ".date("Ymd H:i:s"));
	}
	
	//3号定时器
	public function crontabPoint(){
		set_time_limit(0);
        $random = mt_rand(1,100000);
        if(oo::commonOprRedis('Statistics')->setnxex(okeys::CrontabLock('crontabPoint'),$random,300)){
            //埋点数据落地
            oo::commonOprModel('asynclog')->cacheIntoPointDb();
            //先判断随机数，是同一个则删除锁
            if (oo::commonOprRedis('Statistics')->get(okeys::CrontabLock('crontabPoint')) == $random) {
                oo::commonOprRedis('Statistics')->delete(okeys::CrontabLock('crontabPoint'));
            }
        }else{
            echo 'lock';
        }
		logMessage('crontab',"crontabPoint ".date("Ymd H:i:s"));
	}

	//4号定时器
    public function crontabActlog(){
        date_default_timezone_set("UTC");
        set_time_limit(0);
        $random = mt_rand(1,100000);
        if(oo::commonOprRedis('Statistics')->setnxex(okeys::CrontabLock('crontabActlog'),$random,300)){
            //活动流水落地
            oo::commonOprModel('asynclog')->actCacheInfoDb();
            //先判断随机数，是同一个则删除锁
            if (oo::commonOprRedis('Statistics')->get(okeys::CrontabLock('crontabActlog')) == $random) {
                oo::commonOprRedis('Statistics')->delete(okeys::CrontabLock('crontabActlog'));
            }
        }else{
            echo 'lock';
        }
        logMessage('crontab',"crontabActlog ".date("Ymd H:i:s"));
    }

	//删除数据
    function delLog($date = ''){
        oo::commonOprModel('currency')->delLog($date);
    }

    //锦标赛 + 超级收集活动 统计 统计保存到数据库
    function rankCollectSta(){
        return ;
        set_time_limit(0);
        $random = mt_rand(1,100000);
        if(oo::commonOprRedis('Statistics')->setnxex(okeys::CrontabLock('rankCollectSta'),$random,600)){
            //埋点数据落地
            oo::commonOprModel('statistics')->rankCollectSaveSta();
            //先判断随机数，是同一个则删除锁
            if (oo::commonOprRedis('Statistics')->get(okeys::CrontabLock('rankCollectSta')) == $random) {
                oo::commonOprRedis('Statistics')->delete(okeys::CrontabLock('rankCollectSta'));
            }
        }else{
            echo 'lock';
        }
        logMessage('crontab',"rankCollectSta ".date("Ymd H:i:s"));
    }

    //重数数获取各分组的用户列表
    function getUserListFromSS(){
        oo::commonOprModel('member')->getUserListFromSS();
    }

	function is_cli(){
	    return preg_match("/cli/i", php_sapi_name()) ? true : false;
	}
}
