<?php
/**
软件统计报表
**/
class softAction extends baseAction
{
	private $comUser = [
		'18520063198'=>'彭自谦', 
		'15113816578'=>'陈华连',
		'18317003959'=>'陈华连(代理)',
		'18664982530'=>'陈华连(代理)',
		'15363006747'=>'陈华连(代理)',
		'15917351780'=>'赵丹',
		'18861343890'=>'赵丹(代理)',
		'18520054009'=>'刘丰',
		'18520646845'=>'刘丰',
		'19927601983'=>'肖婧怡',
		'15967651183'=>'朱毅',
		'13586169530'=>'朱毅(代理)',
		'13682276816'=>'杨颂英',
		'13422022011'=>'黄彬',
		'13430383465'=>'伊平川',
		'13650901881'=>'邵锦莲',
		'13560214237'=>'李旭',
		'18825195265'=>'罗伟俊',
		'13556677695'=>'谢泽锋',
		'13557732062'=>'全瑜',
		'18378292529'=>'陆彩霞',
		'13250715617'=>'张冬梅',
		'16620445225'=>'陈亮',
		'13533477092'=>'罗杰豪',
		'13824405163'=>'杨晓松',
		'13535324146'=>'肖菊华',
		'13533377623'=>'林纯跃',
		'18620087056'=>'胡自强',
		'13128258546'=>'黄加匡',
		'18665685760'=>'王海涛',
		'13726946124'=>'何志峰',
		'13692950067'=>'李子深',
		'13535309690'=>'欧昌宇',
		'15975301531'=>'宋贤栋',
		'18420016368'=>'李海',
		'13570241266'=>'施文彬',
		'18688442733'=>'文丰',
		'18968839398'=>'陈华连(代理吴文杰)',
		'18602020602'=>'李世俊(一级代理)',
	];

	function __construct()
	{
		parent::__construct();
		LibTpl::Set('comUser', $this->comUser);
	}

	//每日基本统计
	function tjAny()
    {
		LibRule::Check('SF01');
		$this->initBaseDbTj();

		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$BaseDb = new BaseDb(mvc::$cfg['DB']['SOFTS']);
		$where = '';
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and taa_date >= %d and taa_date <= %d", date('Ymd', strtotime($t[0])), date('Ymd', strtotime($t[1])));
				break;
				case 'taa_status':
					$where .= sprintf(" and taa_status = %d", $v);
				break;
            }
        }
		$table = 'tj_any_date';
		$res = $BaseDb->get($table, ['count(*) as count'], $where, true);
		$Page = LibPage::Show($res['data']['count'], $perPage);
		LibTpl::Set('Page', $Page);
		$res = $BaseDb->get($table, ['*'], sprintf("%s order by taa_date desc limit %d,%d", $where, ($nowPage-1)*$perPage, $perPage));
		$lists = $res['data'];
		LibTpl::Set('lists', $lists);
		
		$file = [
			'sum(taa_user_add) as taa_user_add',
			'sum(taa_tuijian_add) as taa_tuijian_add',
			'sum(taa_money_add) as taa_money_add',
			'sum(taa_search_add) as taa_search_add',
			'sum(taa_imgsearch_add) as taa_imgsearch_add',
		];
		$res = $BaseDb->get('tj_any_date', $file, $where, true);
		LibTpl::Set('total', $res['data']);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '基本统计');
		LibTpl::Put();
    }
	


	//推广统计
	function tgTj()
	{
		LibRule::Check('SF02');
		$Params = mvc::$URL_PARAMS;
		$BaseDb = new BaseDb(mvc::$cfg['DB']['SOFTS']);
		$where = " and InviteCode != '' and InviteCode is not null ";
		$btime = 0;
		$etime = time();
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$btime = strtotime($t[0]);
					$etime = strtotime($t[1])+3600*24-1;
					//$where .= sprintf(" and UNIX_TIMESTAMP(CreationTime) >= %d and UNIX_TIMESTAMP(CreationTime) <= %d", $btime, $etime);
				break;
				case 'InviteCode':
					$where .= sprintf(" and %s like '%%%s%%'", $k, LibFc::Escape($v));
				break;
				case 'th_status':
					if($v == 1)
						$where .= sprintf(" and InviteCode in ('%s')", implode("','", array_keys($this->comUser)));
					else if($v == 1)
						$where .= sprintf(" and InviteCode not in ('%s')", implode("','", array_keys($this->comUser)));
				break;
            }
        }
		
		$mtgArr = [];
		$twhere = sprintf(' and MemberId in (select Id from m_member where 1 %s) and STATUS =2 and  UNIX_TIMESTAMP(PayTime) >= %d and  UNIX_TIMESTAMP(PayTime) <= %d group by MemberId', $where, $btime, $etime);
		$res = $BaseDb->get('m_order', ['MemberId as u_id, sum(BonusAmount) as tg_money'], $twhere );
		foreach($res['data'] as $v)
		{
			$mtgArr[$v['u_id']] = $v;
		}
		$res = $BaseDb->get('m_member', ['InviteCode as tg_mobile, group_concat(Id) tg_uids,count(*) as tg_count, 0 as tg_money'], $where.' group by InviteCode order by count(*) desc');
		$lists = array_column($res['data'], null, 'InviteCode');
		foreach($lists as $k=>$v)
		{
			foreach(explode(',', $v['tg_uids']) as $uid) 
			{
				if(!empty($mtgArr[$uid]))
				{
					//$lists[$k]['tg_money'] += sprintf('%.2f', $mtgArr[$uid]['tg_money']*0.5);
					$lists[$k]['tg_money'] += sprintf('%.2f', $mtgArr[$uid]['tg_money']);
				}
			}
		}

		/*
		//首单50%
		$mtgArr = [];
		$res = $BaseDb->get('m_order', ['MemberId as u_id, UNIX_TIMESTAMP(PayTime) as pay_time, Money as tg_money'], sprintf(' and MemberId in (select Id from m_member where 1 %s) and STATUS =2 ORDER BY PayTime', $where));
		foreach($res['data'] as $v)
		{
			if(empty($mtgArr[$v['u_id']])) $mtgArr[$v['u_id']] = $v;
		}

		$res = $BaseDb->get('m_member', ['InviteCode as tg_mobile, group_concat(Id) tg_uids,count(*) as tg_count, 0 as tg_money'], $where.' group by InviteCode order by count(*) desc');
		$lists = array_column($res['data'], null, 'InviteCode');
		foreach($lists as $k=>$v)
		{
			//A邀请 B、C两个用户，B、C两人的首单金额*50%作为提成，B、C后面的订单不参与提成
			foreach(explode(',', $v['tg_uids']) as $uid) 
			{
				if(!empty($mtgArr[$uid]) && $mtgArr[$uid]['pay_time'] >= $btime && $mtgArr[$uid]['pay_time'] <= $etime)
				{
					$lists[$k]['tg_money'] += sprintf('%.2f', $mtgArr[$uid]['tg_money']*0.5);
				}
			}
		}
		*/
		$total = [];
		foreach($lists as $k=>$v)
		{
			$total['tg_count'] += $v['tg_count'];
			$total['tg_money'] += $v['tg_money'];
		}
		LibTpl::Set('lists', $lists);
		LibTpl::Set('total', $total);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '推广统计');
		LibTpl::Put();
	}


	//跑街令基本统计
	private function initBaseDbTj()
	{
		set_time_limit(0);
		$lockFile = mvc::$cfg['PATH_ROOT'].'cache/Lock_initBaseDbTj.txt';
		if(file_exists($lockFile) && (time() - filemtime($lockFile)) < 3600) return true;
		file_put_contents($lockFile, 'lock');
		$BaseDb = new BaseDb(mvc::$cfg['DB']['SOFTS']);
		
		$bdate = '20190813';

		$res = $BaseDb->get('tj_any_date', ['max(taa_date) as taa_date'], ' and taa_status=1 limit 1', true);
		if(!empty($res['data']['taa_date'])) $bdate = $res['data']['taa_date'];
		
		//上一次的统计记录，累计数用到
		$res = $BaseDb->get('tj_any_date', ['*'], sprintf(" and taa_date=%d", date('Ymd', strtotime($bdate)-3600*24)), true);
		$lastDateData = $res['data'];
	
		$edate = date('Ymd');
		$allTjArr = [];

		while(1)
		{
			$t = empty($t) ? $bdate: date('Ymd', strtotime($t)+3600*24);
			if($t > $edate) break;
			$allTjArr[$t] = ['taa_status'=>1, 'taa_date'=>$t];
		}

		//用户
		$where = sprintf(" and UNIX_TIMESTAMP(CreationTime) >=%d and UNIX_TIMESTAMP(CreationTime) <=%d group by FROM_UNIXTIME(UNIX_TIMESTAMP(CreationTime), '%%Y-%%m-%%d')", strtotime($bdate), strtotime($edate)+3600*24);
		$res = $BaseDb->get('m_member', ["FROM_UNIXTIME(UNIX_TIMESTAMP(CreationTime), '%Y%m%d') as add_date, count(*) as add_count"], $where);
		foreach($res['data'] as $v)
		{
			$allTjArr[$v['add_date']]['taa_user_add'] = $v['add_count'];
		}


		//邀请
		$where = sprintf(" and InviteCode != '' and InviteCode is not null and UNIX_TIMESTAMP(CreationTime) >=%d and UNIX_TIMESTAMP(CreationTime) <=%d group by FROM_UNIXTIME(UNIX_TIMESTAMP(CreationTime), '%%Y-%%m-%%d')", strtotime($bdate), strtotime($edate)+3600*24);
		$res = $BaseDb->get('m_member', ["FROM_UNIXTIME(UNIX_TIMESTAMP(CreationTime), '%Y%m%d') as add_date, count(*) as add_count"], $where);
		foreach($res['data'] as $v)
		{
			$allTjArr[$v['add_date']]['taa_tuijian_add'] = $v['add_count'];
		}
	
		//订单
		$where = sprintf(" and Status = 2 and UNIX_TIMESTAMP(PayTime) >=%d and UNIX_TIMESTAMP(PayTime) <=%d group by FROM_UNIXTIME(UNIX_TIMESTAMP(PayTime), '%%Y-%%m-%%d')", strtotime($bdate), strtotime($edate)+3600*24);
		$res = $BaseDb->get('m_order', ["FROM_UNIXTIME(UNIX_TIMESTAMP(PayTime), '%Y%m%d') as add_date, sum(Money) as add_count"], $where);
		foreach($res['data'] as $v)
		{
			$allTjArr[$v['add_date']]['taa_money_add'] = $v['add_count'];
		}

		//查询
		$where = sprintf(" and Type = 1 and UNIX_TIMESTAMP(Time) >=%d and UNIX_TIMESTAMP(Time) <=%d group by FROM_UNIXTIME(UNIX_TIMESTAMP(Time), '%%Y-%%m-%%d')", strtotime($bdate), strtotime($edate)+3600*24);
		$res = $BaseDb->get('userbehavior.number_search_log', ["FROM_UNIXTIME(UNIX_TIMESTAMP(Time), '%Y%m%d') as add_date, count(*) as add_count"], $where);
		foreach($res['data'] as $v)
		{
			$allTjArr[$v['add_date']]['taa_search_add'] = $v['add_count'];
		}

		$where = sprintf(" and Type = 2 and UNIX_TIMESTAMP(Time) >=%d and UNIX_TIMESTAMP(Time) <=%d group by FROM_UNIXTIME(UNIX_TIMESTAMP(Time), '%%Y-%%m-%%d')", strtotime($bdate), strtotime($edate)+3600*24);
		$res = $BaseDb->get('userbehavior.number_search_log', ["FROM_UNIXTIME(UNIX_TIMESTAMP(Time), '%Y%m%d') as add_date, count(*) as add_count"], $where);
		foreach($res['data'] as $v)
		{
			$allTjArr[$v['add_date']]['taa_imgsearch_add'] = $v['add_count'];
		}
		
		foreach($allTjArr as $d=>$v)
		{
			$ld = date('Ymd', strtotime($d)-3600*24);
			if($d == $bdate)
			{
				$v['taa_user'] = (int) ($v['taa_user_add'] + $lastDateData['taa_user']);
				$v['taa_tuijian'] = (int) ($v['taa_tuijian_add'] + $lastDateData['taa_tuijian']);
				$v['taa_search'] = (int) ($v['taa_search_add'] + $lastDateData['taa_search']);
				$v['taa_imgsearch'] = (int) ($v['taa_imgsearch_add'] + $lastDateData['taa_imgsearch']);
				$v['taa_money'] = sprintf('%.2f', $v['taa_money_add'] + $lastDateData['taa_money']);
			}
			else
			{
				$v['taa_user'] = (int) ($allTjArr[$ld]['taa_user'] + $v['taa_user_add']);
				$v['taa_tuijian'] = (int) ($allTjArr[$ld]['taa_tuijian'] + $v['taa_tuijian_add']);
				$v['taa_search'] = (int) ($allTjArr[$ld]['taa_search'] + $v['taa_search_add']);
				$v['taa_imgsearch'] = (int) ($allTjArr[$ld]['taa_imgsearch'] + $v['taa_imgsearch_add']);
				$v['taa_money'] = sprintf('%.2f', $allTjArr[$ld]['taa_money'] + $v['taa_money_add']);
			}
			$allTjArr[$d] = $v;
		}
		
		$res = $BaseDb->get('tj_any_date', ['taa_date'], sprintf(" and taa_date>=%d and taa_date<=%d", $bdate, $edate));
		$hasDate = array_column($res['data'], 'taa_date');
		foreach($allTjArr as $d=>$v)
		{
			$v['taa_status'] = $d == date('Ymd')? 0: $v['taa_status'];
			if(in_array($d, $hasDate))
			{
				$BaseDb->set('tj_any_date', $v, sprintf(" and taa_date=%d", $d));
			}
			else
			{
				$BaseDb->add('tj_any_date', $v);
			}
		}

		//清除历史记录表30天前数据
		$BaseDb->del('userbehavior.number_search_log', sprintf(" and UNIX_TIMESTAMP(Time) < %d", time()-30*24*3600));
		@unlink($lockFile);
	}
}