<?php
class pjlSysAction extends baseAction
{
	function apiCount()
	{
		LibRule::Check('AP00');
		$Params = mvc::$URL_PARAMS;
		$from=[
			'PJL'=>'PJL',
			'PJLAND'=>'安卓',
			'PJLIOS'=>'苹果',
			'PJLH5'=>'H5',
			'PJLSOFT'=>'软件',
			'WXROBOT'=>'WXROBOT',
		];
		$LibYpApi=new LibYpApi();
		//今天
		$time=strtotime(date('Y-m-d',time()));
		$where=sprintf(" and tj_time>=%d",$time);
		$where.=' group by tj_from';
		$fields=['tj_from','count(1) as tj_pv,count(distinct tj_ip) as tj_ip,count(distinct tj_devcode) as tj_devcode,count(distinct tj_uid) as tj_uid'];
		$res = $LibYpApi->Get('pjl/getDayTj',[],['where'=>$where,'fields'=>$fields,'oneRow'=>false]);
		$today=$res['data'];
		// print_r($today);
		LibTpl::Set('today', $today);
		$today = array_column($today,null, 'tj_from');
		//昨天统计
		$time=date('Ymd',strtotime('-1 day',strtotime(date('Y-m-d',time()))));
		$where=sprintf(" and da_date='%s'",$time);
		$res = $LibYpApi->Get('pjl/getApiDateTj',[],['where'=>$where,'oneRow'=>false]);
		$yesterday=$res['data'];
		LibTpl::Set('yesterday', $yesterday);
		//最近七天
		$time=date('Ymd',strtotime('-6 day',strtotime(date('Y-m-d',time()))));
		$where=sprintf(" and da_date>='%s'",$time);
		$where.=' group by da_from';
		$fields=['da_from','sum(da_pv) as da_pv,sum(da_ip) as da_ip,sum(da_devcode) as da_devcode,sum(da_user) as da_user'];
		$res = $LibYpApi->Get('pjl/getApiDateTj',[],['where'=>$where,'fields'=>$fields,'oneRow'=>false]);
		$sevenDay=$res['data'];
		if(!empty($sevenDay))
		{
			
			foreach ($sevenDay as $k=> $v) 
			{
				$v['da_pv']+=$today[$v['da_from']]['tj_pv'];
				$v['da_ip']+=$today[$v['da_from']]['tj_ip'];
				$v['da_devcode']+=$today[$v['da_from']]['tj_devcode'];
				$v['da_user']+=$today[$v['da_from']]['tj_uid'];
				$sevenDay[$k]=$v;
			}
		}
		LibTpl::Set('sevenDay', $sevenDay);
		//当月
		$time=date('Ymd',strtotime(date('Y-m',time())));
		$where=sprintf(" and da_date>='%s' ",$time);
		$where.=' group by da_from';
		$fields=['da_from','sum(da_pv) as da_pv,sum(da_ip) as da_ip,sum(da_devcode) as da_devcode,sum(da_user) as da_user'];
		$res = $LibYpApi->Get('pjl/getApiDateTj',[],['where'=>$where,'fields'=>$fields,'oneRow'=>false]);
		$monDay=$res['data'];
		if(!empty($monDay))
		{
			
			foreach ($monDay as $k=> $v) 
			{
				$v['da_pv']+=$today[$v['da_from']]['tj_pv'];
				$v['da_ip']+=$today[$v['da_from']]['tj_ip'];
				$v['da_devcode']+=$today[$v['da_from']]['tj_devcode'];
				$v['da_user']+=$today[$v['da_from']]['tj_uid'];
				$monDay[$k]=$v;
			}
		}
		LibTpl::Set('monDay', $monDay);
		//今年
		$time=date('Y',time()).'0101';
		$where=sprintf(" and da_date>='%s'",$time);
		$where.=' group by da_from';
		$fields=['da_from','sum(da_pv) as da_pv,sum(da_ip) as da_ip,sum(da_devcode) as da_devcode,sum(da_user) as da_user'];
		$res = $LibYpApi->Get('pjl/getApiDateTj',[],['where'=>$where,'fields'=>$fields,'oneRow'=>false]);
		$year=$res['data'];
		if(!empty($year))
		{
			
			foreach ($year as $k=> $v) 
			{
				$v['da_pv']+=$today[$v['da_from']]['tj_pv'];
				$v['da_ip']+=$today[$v['da_from']]['tj_ip'];
				$v['da_devcode']+=$today[$v['da_from']]['tj_devcode'];
				$v['da_user']+=$today[$v['da_from']]['tj_uid'];
				$year[$k]=$v;
			}
		}
		LibTpl::Set('year', $year);
		//总访问量
		$where='';
		$where.=' group by da_from';
		$fields=['da_from','sum(da_pv) as da_pv,sum(da_ip) as da_ip,sum(da_devcode) as da_devcode,sum(da_user) as da_user'];
		$res = $LibYpApi->Get('pjl/getApiDateTj',[],['where'=>$where,'fields'=>$fields,'oneRow'=>false]);
		$all=$res['data'];
		if(!empty($all))
		{
			
			foreach ($all as $k=> $v) 
			{
				$v['da_pv']+=$today[$v['da_from']]['tj_pv'];
				$v['da_ip']+=$today[$v['da_from']]['tj_ip'];
				$v['da_devcode']+=$today[$v['da_from']]['tj_devcode'];
				$v['da_user']+=$today[$v['da_from']]['tj_uid'];
				$all[$k]=$v;
			}
		}
		LibTpl::Set('all', $all);
		/**
		//历史最高
		$where='';
		$where.=' group by da_from';
		$fields=['da_from','da_date','max(da_pv) as da_pv,max(da_ip) as da_ip,max(da_devcode) as da_devcode,max(da_user) as da_user'];
		$res = $LibYpApi->Get('pjl/getApiDateTj',[],['where'=>$where,'fields'=>$fields,'oneRow'=>false]);
		$top=$res['data'];
		LibTpl::Set('top', $top);
		**/
		LibTpl::Set('from', $from);
		LibTpl::Set('title','API调用统计-跑街令');
		LibTpl::Put();
	}

	 /**
     * 每日统计列表页
     */
    function apiDailyCount()
    {
		LibRule::Check('AP00');
        $params = mvc::$URL_PARAMS;
        $BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);
        $page = !empty($params['page']) ? (int)$params['page'] : 1;
        $perPage = !empty($_COOKIE['perPage']) ? (int)$_COOKIE['perPage'] : 25;
		$where = '';
		$field = ['*'];
        if(!empty($params['from']))
        {
          $where .= sprintf(" and td_from='%s'", $params['from']);
		}
		
		if(!empty($params['action']) && $params['action'] != 'all')
		{
           $where .= sprintf(" and td_act = '%s'", $params['action']);
		}
		
		if(!empty($params['td_site']))
		{
			$where .= sprintf(" and td_site='%s'", $params['td_site']);
		}

		if(!empty($params['group']) && $params['group'] != 'all')
		{
			$where .= sprintf( " and td_act in (select tr_act from at_tongji_reg where tr_act_group='%s' group by tr_act)",$params['group']);
			$where .= sprintf(" group by td_date");
			$field = ['td_date','group_concat(td_site) as td_site','group_concat(td_act) as td_act','td_from','sum(td_ip_count) as td_ip_count,sum(td_devcode_count),sum(td_devcode_count) as td_devcode_count','sum(td_pv_count) as td_pv_count','sum(td_uid_count) as td_uid_count'];
		}

        /**
         * 筛分时间
         */
        if (!empty($params['time']))
        {
            $temp = explode(' - ', $params['time']);
            $where .= sprintf(" and td_date >= '%d' and td_date <= '%s'", LibFc::Escape(date('Ymd', strtotime($temp['0']))), LibFc::Escape(date('Ymd', strtotime($temp['1']))));
		}

		if($field['0'] == '*'){
			$res = $BaseDb->get('at_tongji_date', ['count(*) count'], $where, true);
		}else{
			$res = $BaseDb->get(sprintf("(select count(*) from at_tongji_date where 1=1 %s) as tt",$where),['count(*) as count'],'',true);
		}
		
        $Page = LibPage::Show($res['data']['count'], $perPage);
        LibTpl::Set('Page', $Page);

        if (!empty($res['data']['count']))
        {
            $where .= sprintf(' order by td_date desc limit %d,%d', ($page - 1) * $perPage, $perPage);
            $res = $BaseDb->get('at_tongji_date', $field, $where);
            $lists = $res['data'];
            LibTpl::Set('lists', $lists);
        }
        if(!empty($params['td_site']) && $params['td_site'] != 'all')
        {
              $res = $BaseDb->get('at_tongji_reg', ['*'], sprintf("  and tr_site = '%s' order by tr_seq",$params['td_site']));
        }else{
              $res = $BaseDb->get('at_tongji_reg', ['*'], ' order by tr_seq');
        }
        LibTpl::Set('actArt', array_column($res['data'], null, 'tr_act'));

        $res = $BaseDb->get('at_tongji', ['distinct tj_from'], ' order by tj_from');
        $from = [
            'PJL' => 'PJL',
            'PJLAND' => '安卓',
            'PJLIOS' => '苹果',
            'PJLH5' => 'H5',
            'PJLSOFT' => '软件',
            'PJLPC' => 'PC端',
			'WXROBOT'=>'WXROBOT',
        ];

		$site = $BaseDb->get('at_tongji_reg',['tr_site_name','tr_site',"group_concat( concat_ws('-', tr_act, tr_act_name)) as ac_list"], ' group by tr_site_name,tr_site order by tr_seq asc');
		$trGroup = $BaseDb->get('at_tongji_reg',['tr_act_group','tr_act_group'],' group by tr_act_group order by tr_seq asc');
		$site = $site['data'];
		foreach($site as &$value){
			if($value['ac_list']){
				$value['ac_list'] = explode(',',$value['ac_list']);
				if(is_array($value['ac_list'])){
					foreach($value['ac_list'] as $index => $item) {
						$temp = explode('-',$item);
						$value['ac_list'][$temp['0']] = $temp['1'];
						unset($value['ac_list'][$index]);
					}
				}
				$value['ac_list'] = json_encode($value['ac_list'],JSON_UNESCAPED_UNICODE);
			}
		}
		$site = array_column($site,null,'tr_site');
		$trGroup = array_column($trGroup['data'],'tr_act_group','tr_act_group');
		LibTpl::Set('tr_group',$trGroup);
		LibTpl::Set('site',$site);
        LibTpl::Set('from', $from);
        LibTpl::Set('fromArr', $res['data']);
        LibTpl::Set('Params', $params);
        LibTpl::Set('title', 'API每日统计-跑街令');
        LibTpl::Put();
    }


	//生成统计
	function creatDayTj()
	{
		LibRule::Check('AP00');
		$LibYpApi=new LibYpApi();
		$res = $LibYpApi->Get('pjl/creatDayTj',[],[]);
		LibFc::ajaxJsonEncode($res);
	}
	//批量操作
	function apiOperate()
	{
		LibRule::Check('AP00');
		LibTpl::Set('title','API日批量操作-跑街令');
		LibTpl::Put();
	}
	/**
	 * @method    版本列表
	 * @return    [type]     [description]
	 * @author lu
	 * @copyright 2018-12-07
	 */
	function appVersion()
	{
		LibRule::Check('PP00');
		$LibYpApi=new LibYpApi();
		$page=!empty($Params['page'])?(int)$Params['page']:1;
		$perPage=!empty($_COOKIE['perPage'])? (int)$_COOKIE['perPage'] : 25;
		$where='';
		$res = $LibYpApi->Get('app/getAppVersion',[],['where'=>$where,'fields'=>['count(1) count'],'oneRow'=>true]);
		$total=$res['data']['count'];
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		if($total>0)
		{
			$where.=sprintf(' order by ver_id desc limit %d,%d',($page-1)*$perPage,$perPage);
			$res = $LibYpApi->Get('app/getAppVersion',[],['where'=>$where]);
			$lists=$res['data'];
			LibTpl::Set('lists',$lists);
		}
		$appNameArr=[
			'PJLAND'=>'跑街令-安卓',
			'PJLIOS'=>'跑街令-苹果',
			'PJDZS'=>'跑街助手-安卓'
		];
		LibTpl::Set('appNameArr',$appNameArr);
		LibTpl::Set('title','APP版本管理-跑街令');
		LibTpl::Put();
	}
	/**
	 * @method    添加/修改版本
	 * @author lu
	 * @copyright 2018-12-07
	 */
	function addAppVersion()
	{
		LibRule::Check('PP00');
		$Params = MVC::$URL_PARAMS;
		$LibYpApi=new LibYpApi();
		if(!empty($_POST))
		{
			$dataArr=$_POST;
			if(!empty($dataArr['ver_id']))
			{
				$res = $LibYpApi->Get('app/setAppVersion',[],$dataArr);
				if($res['data'])
				{
					LibTpl::Success('修改成功',  mvc::$cfg['ADMIN_URI'].'pjlSys/addAppVersion?verId='.$dataArr['ver_id']);
				}else{
					LibTpl::Error('修改成功',  mvc::$cfg['ADMIN_URI'].'pjlSys/addAppVersion');
				}
			}else
			{
				unset($dataArr['ver_id']);
				$res = $LibYpApi->Get('app/addAppVersion',[],$dataArr);
				if($res['data'])
				{
					LibTpl::Success('添加成功',  mvc::$cfg['ADMIN_URI'].'pjlSys/addAppVersion?verId='.$res['data']);
				}else{
					LibTpl::Error('添加成功',  mvc::$cfg['ADMIN_URI'].'pjlSys/addAppVersion');
				}
			}
			exit();
		}
		$appNameArr=[
			'PJLAND'=>'跑街令-安卓',
			'PJLIOS'=>'跑街令-苹果',
			'PJDZS'=>'跑街助手-安卓'
		];
		LibTpl::Set('appNameArr',$appNameArr);
		LibTpl::Set('title','添加APP版本-跑街令');
		if(LibFc::Int($Params['verId']))
		{
			$where=sprintf(' and ver_id=%d',$Params['verId']);
			$res = $LibYpApi->Get('app/getAppVersion',[],['where'=>$where,'oneRow'=>true]);
			LibTpl::Set('title','修改APP版本-跑街令');
			LibTpl::Set('data',$res['data']);
		}
		LibTpl::Put();
	}
	/**
	 * @method    删除版本
	 * @return    [type]     [description]
	 * @author lu
	 * @copyright 2018-12-07
	 */
	function delVersion()
	{
		LibRule::Check('PP00');
		$res=['status'=>false,'data'=>'删除失败'];
		if(!empty($_POST['verId'])&&LibFc::Int($_POST['verId']))
		{
			$LibYpApi=new LibYpApi();
			$res = $LibYpApi->Get('app/delAppVersion',[],['verId'=>$_POST['verId']]);
		}
		LibFc::ajaxJsonEncode($res);
	}
	/**
	 * @method    黑名单列表
	 * @return    [type]     [description]
	 * @author lu
	 * @copyright 2018-12-14
	 */
	function blackList()
	{
		LibRule::Check('AP00');
		$Params = MVC::$URL_PARAMS;
		$Params = array_map('trim',$Params);
		$LibYpApi=new LibYpApi();
		$where = '';
		$page =! empty($Params['page'])?(int)$Params['page']:1;
		$perPage =! empty($_COOKIE['perPage'])? (int)$_COOKIE['perPage'] : 25;
		if(!empty($Params['bl_ip'])){
		    $where .= sprintf(" and bl_ip='%s'",$Params['bl_ip']);
        }
		if(!empty($Params['bl_devcode'])){
		    $where .= sprintf(" and bl_devcode='%s'",$Params['bl_devcode']);
        }
		if(!empty($Params['bl_type'])){
		    $where .= sprintf(" and bl_type='%s'",$Params['bl_type']);
        }
		if(!empty($Params['bl_apiact'])){
		    $where .= sprintf(" and bl_apiact='%s'",$Params['bl_apiact']);
        }
		if(!empty($Params['bl_uid'])){
            $PostData=[
                'filed'=>['u_id','u_name'],
                'where'=>sprintf(" and (u_name='%s' or u_mobile = '%s')",$Params['bl_uid'],$Params['bl_uid']),
                'oneRow'=>true
            ];
            $userArr = $LibYpApi->Get('user/getUser', [], $PostData);
            if(empty($userArr['data']['u_id']))
            {
                $uid = -1;
            }else{
                $uid = $userArr['data']['u_id'];
            }
		    $where .= sprintf(" and bl_uid=%d",$uid);
        }
		//添加时间
		if($Params['time'])
		{
			$timearr = explode('~',$Params['time']);
			$where .= sprintf(" and bl_atime>=%d and bl_atime<=%d",strtotime($timearr[0]),strtotime($timearr[1])+86399);
		}

		$res = $LibYpApi->Get('pjl/getBlackList',[],['where'=>$where,'fields'=>['count(1) count'],'oneRow'=>true]);
		$total = $res['data']['count'];
		$Page = LibPage::Show($total, $perPage);

		LibTpl::Set('Page', $Page);
		if($total>0)
		{
			$orderBy='';
			$where.=sprintf(' order by bl_id desc limit %d,%d',($page-1)*$perPage,$perPage);
			$where.=$orderBy;
			$res = $LibYpApi->Get('pjl/getBlackList',[],['where'=>$where]);
			$uArr=array_column($res['data'], 'bl_uid');
			LibTpl::Set('lists',$res['data']);
			if(!empty($uArr))
			{
			    $uIds = implode(',',$uArr);
			    $shop = (new PjlBase)->get("pl_shop",['shop_name','shop_pu_id'],sprintf(" and shop_pu_id in (%s)",$uIds));
			    if(empty($shop['data'])){
                    $shop = [];
                }else{
                    $shop = array_column($shop['data'],'shop_name','shop_pu_id');
                }

                LibTpl::Set('shop',$shop);
				$PostData=[
					'filed'=>['u_id','u_name'],
					'where'=>sprintf(" and u_id in(%s)",$uIds),
					'oneRow'=>false
				];
				$resArr = $LibYpApi->Get('user/getUser', [], $PostData);
				LibTpl::Set('user', array_column($resArr['data'],'u_name', 'u_id'));
			}
		}
        $db = (new BaseDb(mvc::$cfg['DB']['API_TJ']));
        $reg = $db->get('at_tongji_reg',['tr_act'], ' order by tr_seq');
        LibTpl::Set('act',$reg['data']);
		LibTpl::Set('param',$Params);
        LibTpl::Set('typeList',[
            'userapi' => 'userapi',
            'ip' => 'ip',
            'user' => 'user'
        ]);
		LibTpl::Set('title','api黑名单-跑街令');
		LibTpl::Put();
	}
	/**
	 * @method    添加黑名单
	 * @author lu
	 * @copyright 2018-12-14
	 */
	function addBlack()
	{
		LibRule::Check('AP00');
		$LibYpApi=new LibYpApi();
        $db = (new BaseDb(mvc::$cfg['DB']['API_TJ']));
		if(!empty($_POST))
		{
			$dataArr = array_map([LibFc::class,'Escape'],$_POST);
			if(!empty($dataArr['bl_id']))
			{
				if((int) $dataArr['bl_uid'] <= 0)
				{
					$PostData=[
						'filed'=>['u_id','u_name'],
						'where'=>sprintf(" and u_name='%s'",$dataArr['bl_user_name']),
						'oneRow'=>true
					];
					$userArr = $LibYpApi->Get('user/getUser', [], $PostData);
					if(empty($userArr['data']['u_id']))
					{
						LibTpl::Error('添加失败,未找到'.$dataArr['bl_user_name'].'对应的用户',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid='.$dataArr['bl_id']);
					}
					$dataArr['bl_uid'] = $userArr['data']['u_id'];
					
				}
				$blId = $dataArr['bl_id'];
				unset($dataArr['bl_id'],$dataArr['data'],$dataArr['bl_user_name']);
				$dataArr['bl_etime'] = strtotime($dataArr['bl_etime']);
				$db->Set('tj_blacklist',$dataArr,sprintf(" and bl_id=%d",$blId));
				LibTpl::Success('修改成功',  mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid='.$blId);
			}else{
			    $tempTime = time();
				unset($dataArr['bl_id']);
				if($dataArr['day'] == -1){
					//20年后
					$dataArr['bl_etime'] = $tempTime + ($dataArr['day'] * 86400 * 20);
				}
				if($dataArr['day'] != -1 && $dataArr['day'] <= 0){
					LibTpl::Error('封停时间不能为0',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
				}
				if($dataArr['bl_type'] == 'user'){
					if(empty($dataArr['bl_ip'])){
						LibTpl::Error('IP不可为空',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
					}
					if(empty($dataArr['bl_user_name']) && empty($dataArr['bl_u_id'])){
						LibTpl::Error('用户不能为空',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
					}
					unset($dataArr['bl_apiact']);
				}
				if($dataArr['bl_type'] == 'ip'){
					if(empty($dataArr['bl_ip'])){
						LibTpl::Error('IP不可为空',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
					}
					unset($dataArr['bl_uid'],$dataArr['bl_user_name'],$dataArr['bl_apiact']);
				}
				if($dataArr['bl_type'] == 'userapi'){
					if(empty($dataArr['bl_ip'])){
						LibTpl::Error('IP不可为空',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
					}
					if(empty($dataArr['bl_apiact'])){
						LibTpl::Error('接口不可为空',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
					}
				}
				if(empty($dataArr['bl_remark'])){
					LibTpl::Error('备注不可为空',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
				}
				$dataArr['bl_etime'] = $tempTime + ($dataArr['day'] * 86400);
				$dataArr['bl_atime'] = $tempTime;
				unset($dataArr['day'],$tempTime);
			
				if((int) $dataArr['bl_uid'] <= 0)
				{
					$PostData=[
						'filed'=>['u_id','u_name'],
						'where'=>sprintf(" and u_name='%s'",$dataArr['bl_user_name']),
						'oneRow'=>true
					];
					$userArr = $LibYpApi->Get('user/getUser', [], $PostData);
					if(empty($userArr['data']['u_id']))
					{
						LibTpl::Error('添加失败,未找到'.$dataArr['bl_user_name'].'对应的用户',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
					}
					$dataArr['bl_uid'] = $userArr['data']['u_id'];
					
				}
				unset($dataArr['bl_user_name']);
				if(strlen($dataArr['bl_remark']) > 64){
					LibTpl::Error('添加失败,备注长度超过限制(64)',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
				}
				if(strlen($dataArr['bl_ip']) > 15){
					LibTpl::Error('添加失败,ip长度超过限制(15)',mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid=0');
				}
				$resArr = $db->add('tj_blacklist',$dataArr);
				LibTpl::Success('添加成功',  mvc::$cfg['ADMIN_URI'].'pjlSys/addBlack?bid='.$resArr['data']);
			}
			// print_r($_POST);
		}
		$Params = MVC::$URL_PARAMS;
		if(LibFc::Int($Params['bid']))
		{
			$where=sprintf(' and bl_id=%d',$Params['bid']);
			$res = $LibYpApi->Get('pjl/getBlackList',[],['where'=>$where,'oneRow'=>true]);
			// $res = $db->BaseDb->Row(sprintf("select * from tj_blacklist where bl_id=%d",$Params['bid']));
			// $res['day'] = ceil(($res['bl_etime'] - time())/86400);
			LibTpl::Set('data',$res['data']);
			if(!empty($res['data']) && !empty($res['data']['bl_uid']))
			{
				$PostData=[
					'filed'=>['u_id','u_name'],
					'where'=>sprintf(" and u_id=%d",$res['data']['bl_uid']),
					'oneRow'=>true
				];
				$resArr = $LibYpApi->Get('user/getUser', [], $PostData);
				LibTpl::Set('user',$resArr['data']);
			}
		}
		$reg = $db->get('at_tongji_reg',['*'], ' order by tr_seq');
        $dateList = [
            '1天'  => date("Y-m-d H:i",strtotime("+1 day")),
            '5天'  => date("Y-m-d H:i",strtotime("+5 day")),
            '15天' => date("Y-m-d H:i",strtotime("+15 day")),
            '永久' => date("Y-m-d H:i",strtotime('+10 year'))
        ];
        LibTpl::Set('date_list',$dateList);
		LibTpl::Set('actArt', array_column($reg['data'], null, 'tr_act'));
		LibTpl::Set('title','添加黑名单-跑街令');
		LibTpl::Put();
	}
	/**
	 * @method    获取用户
	 * @return    [type]     [description]
	 * @author lu
	 * @copyright 2018-12-14
	 */
	function getUser()
	{
		$Params = MVC::$URL_PARAMS;
		$LibYpApi=new LibYpApi();
		if(!empty($Params['q']))
		{
			$PostData=[
				'filed'=>['u_id','u_name'],
				'where'=>sprintf(" and u_name like '%%%s%%'",LibFc::Escape($Params['q'])),
				'oneRow'=>false
			];
			$resArr = $LibYpApi->Get('user/getUser', [], $PostData);
			LibFc::ajaxJsonEncode($resArr);
		}
	}
	/**
	 * @method    删除黑名单
	 * @return    [type]     [description]
	 * @author lu
	 * @copyright 2018-12-14
	 */
	function delBlack()
	{
		LibRule::Check('AP00');
		$Params = MVC::$URL_PARAMS;
		$bId = (int) LibFc::Escape($_POST['bId']);
		if($bId <= 0){
			LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
		}
		$db = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		$bl = $db->Get('tj_blacklist',['bl_remark'],sprintf(" and bl_id=%d",$bId),true);
		$str = $bl['data']['bl_remark'] ?: '';
		$str .= '   '.$_SESSION['admin_uname'].'取消了黑名单';
        $result = $db->set('tj_blacklist',['bl_etime' => time(),'bl_remark' => $str],sprintf(" and bl_id=%d",$bId));
        LibFc::ajaxJsonEncode($result);
	}

	public function savBlack()
    {
        $data = array_map([LibFc::class,'Escape'],$_POST);
        unset($data['isAjax']);
        if(empty($data['bl_etime'])){
            LibFc::ajaxJsonEncode(['status'=> false,'data'=>'时间不可为空']);
        }
        $data['bl_etime'] = strtotime($data['bl_etime']);
        if(empty($data['bl_remark']) || strlen($data['bl_remark']) > 255){
            LibFc::ajaxJsonEncode(['status'=>false,'data'=>'备注不可为空或者过长']);
        }
        $LibYpApi=new LibYpApi();
        switch ($data['bl_type']){
            case 'user':
                $tempUser = $data['bl_user_name'];
                if(empty($tempUser)){
                    LibFc::ajaxJsonEncode(['status'=>false,'data'=>'用户名称不存在']);
                }
                unset($data['bl_ip'],$data['bl_apiact'],$data['bl_user_name']);
                $param=[
                    'filed'=>['u_id','u_name'],
                    'where'=>sprintf(" and u_name='%s'",$tempUser),
                    'oneRow'=>true
                ];
                $userArr = $LibYpApi->Get('user/getUser', [], $param);
                if($userArr['status'] == true && isset($userArr['data']['u_id']) && $userArr['data']['u_id'] > 0){
                    $data['bl_uid'] = $userArr['data']['u_id'];
                }else{
                    LibFc::ajaxJsonEncode(['status' => false,'data'=> '找不到该用户']);
                }
                break;
            case 'userapi':
                $tempUser = $data['bl_user_name'];
                unset($data['bl_user_name']);
                if(empty($tempUser)){
                    LibFc::ajaxJsonEncode(['status'=>false,'data'=>'用户名称不存在']);
                }
                if(empty($data['bl_ip'])){
                    LibFc::ajaxJsonEncode(['status'=> false,'data'=> 'ip不可为空']);
                }
                if(empty($data['bl_apiact'])){
                    LibFc::ajaxJsonEncode(['status'=>false,'data'=>'接口名称不可为空']);
                }
                $param=[
                    'filed'=>['u_id','u_name'],
                    'where'=>sprintf(" and u_name='%s'",$tempUser),
                    'oneRow'=>true
                ];
                $userArr = $LibYpApi->Get('user/getUser', [], $param);
                if($userArr['status'] == true && isset($userArr['data']['u_id']) && $userArr['data']['u_id'] > 0){
                    $data['bl_uid'] = $userArr['data']['u_id'];
                }else{
                    LibFc::ajaxJsonEncode(['status' => false,'data'=> '找不到该用户']);
                }
                break;
            case 'ip':
                unset($data['bl_apiact'],$data['bl_user_name']);
                if(empty($data['bl_ip'])){
                    LibFc::ajaxJsonEncode(['status'=> false,'data'=> 'ip不可为空']);
                }
                break;
        }
        $db =  $db = (new BaseDb(mvc::$cfg['DB']['API_TJ']));
        if($data['bl_id'] > 0){
            $blId = $data['bl_id'];
            unset($data['bl_id']);
            $result = $db->Set('tj_blacklist',$data,sprintf(" and bl_id=%d",$blId));
        }else{
            $data['bl_atime'] = time();
            $result = $db->Add('tj_blacklist',$data);
        }
        unset($data);
        LibFc::ajaxJsonEncode($result);
    }

	//访问明细
	public function fangwen()
	{
		//todo 权限
		LibRule::Check('AP00');
		$Params = mvc::$URL_PARAMS;
		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);

		$LibYpApi=new LibYpApi();
		$page=!empty($Params['page'])?(int)$Params['page']:1;
		$perPage=!empty($_COOKIE['perPage'])? (int)$_COOKIE['perPage'] : 25;
		$where='';
		if(!empty($Params['user']))
		{
			$PostData=[
				'filed'=>['u_id'],
				'where'=>sprintf(" and (u_name LIKE '%s' OR u_mobile LIKE '%s')", LibFc::Escape($Params['user']), LibFc::Escape($Params['user'])),
				'oneRow'=>false
			];
			$res = $LibYpApi->Get('user/getUser', [], $PostData);
			if(!empty($res['data']))
			{
				$where.=sprintf(" and tj_uid in('%s')",implode(',', array_column($res['data'], 'u_id')));
			}
			else
			{
				$where.=' and tj_uid < 0';
			}
		}
		if(!empty($Params['api']))
		{
			$where.=sprintf(" and tj_act='%s'",LibFc::Escape($Params['api']));
		}
		if(!empty($Params['group'])){
			$where .= sprintf(" and tj_act in (select tr_act from at_tongji_reg where tr_act_group='%s' group by tr_act)",$Params['group']);
		}
		if(!empty($Params['ip']))
		{
			$where.=sprintf(" and tj_ip like '%s%%'",LibFc::Escape($Params['ip']));
		}
		if(!empty($Params['from']))
		{
			$where.=sprintf(" and tj_from='%s'",LibFc::Escape($Params['from']));
		}
		if(!empty($Params['site'])){
			$where .= sprintf( "and tj_site='%s'",LibFc::Escape($Params['site']));
		}
		if(!empty($Params['time'])){
			$temp = explode(' - ',$Params['time']);
			$where .= sprintf(" and tj_time between %s and %s",strtotime($temp['0']),strtotime($temp['1'])+86439);
		}
		
		if(!empty($Params['shop_name'])){
			$table1 = 'sh_shop left join us_user_base on shop_uid=ub_uid ';
			$B2cBase = new B2cBase();
			$res = $B2cBase->get($table1,['shop_uid'],sprintf(" and shop_name like '%%%s%%'",LibFc::Escape($Params['shop_name'])));
			if($res['data'])
			{
				$where.=sprintf(" and tj_shopid in(%s)",implode(',', array_column($res['data'], 'shop_uid')));
			}
			
		}

		if(!empty($Params['action'])){
			$table = $Params['action'];
		}else{
			$table = 'at_tongji';
		}
		if(!empty($Params['tj_devcode'])){

			$where .= sprintf(" and tj_devcode like '%%%s%%'",$Params['tj_devcode']);
		}
		if(!empty($Params['api_name'])){
			$temp = $BaseDb->get('at_tongji_reg',['tr_act'],sprintf(" and tr_act_name like '%%%s%%'",$Params['api_name']));
			$temp = array_column($temp['data'],'tr_act');
			if($temp){
				foreach($temp as &$value){
					$value = sprintf("'%s'",LibFc::Escape($value));
				}
				$where .= sprintf(" and tj_act in (%s)",implode(',',$temp));
			}else{
				$where .= sprintf(" and tj_uid < 0");
			}

		}
		$res= $BaseDb->get($table,['count(*) count'], $where, true);
		$Page = LibPage::Show($res['data']['count'], $perPage);
		LibTpl::Set('Page', $Page);
		if(!empty($res['data']['count']))
		{
			$where.=sprintf(' order by tj_time desc limit %d,%d',($page-1)*$perPage,$perPage);
			$res = $BaseDb->get($table,['*'], $where);
			$lists = $res['data'];
			$uArr = array_unique(array_column($lists, 'tj_uid'));
			if(!empty($uArr))
			{
				$PostData=[
					'filed'=>['u_id','u_name'],
					'where'=>sprintf(" and u_id in(%s)",implode(',',$uArr)),
					'oneRow'=>false
				];
				$resArr = $LibYpApi->Get('user/getUser', [], $PostData);
				LibTpl::Set('user', array_column($resArr['data'],'u_name', 'u_id'));
			}
			$shopArr = array_unique(array_column($lists, 'tj_shopid'));
			if(!empty($shopArr))
			{
				$table1 = 'sh_shop left join us_user_base on shop_uid=ub_uid ';
				$B2cBase = new B2cBase();
				$resArr = $B2cBase->get($table1,['shop_name','shop_uid'],sprintf(" and shop_id in(%s)",implode(',',$shopArr)));
				LibTpl::Set('shop', array_column($resArr['data'],'shop_name', 'shop_uid'));
			}
			LibTpl::Set('lists', $lists);
		}

		$site = $BaseDb->get('at_tongji_reg',['tr_site_name','tr_site'], ' group by tr_site_name,tr_site order by tr_seq asc');
		$trAct = $BaseDb->get('at_tongji_reg',['tr_site','tr_act','tr_act_name'],' group by tr_act,tr_act_name order by tr_seq asc');
		$trActs = [];
		foreach($trAct['data'] as $value){
			$trActs['data'][$value['tr_site']][] = $value;
		}

		$trGroup = $BaseDb->get('at_tongji_reg',['tr_act_group','tr_act_group'],' group by tr_act_group order by tr_seq asc');
		$trGroup = array_column($trGroup['data'],'tr_act_group','tr_act_group');

		$sites = array_column($site['data'],null,'tr_site');
		$trAct = array_column($trAct['data'],null,'tr_act');
		$res = $BaseDb->get('at_tongji',['distinct tj_from'], ' order by tj_from');
		LibTpl::Set('Params', $Params);
		LibTpl::Set('tr_group',$trGroup);
		LibTpl::Set('tr_act',json_encode($trActs['data'],true));
		LibTpl::Set('sites',$sites);
		LibTpl::Set('trAct',$trAct);
	    LibTpl::Set('site',$site['data']);
		LibTpl::Set('fromArr', $res['data']);

		LibTpl::Set('title','主接口监控明细');
		LibTpl::Put();
	}

	/**
	 * [brandPhb 品牌排行榜]
	 * @Author   Yangxing
	 * @DateTime 2020-05-08T11:12:44+0800
	 * @return   [type]                   [view]
	 */
	public function brandPhb()
	{
        LibRule::Check('AP00');
		$db = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		$params = mvc::$URL_PARAMS;
        $where = '';
        if(!empty($params['start']) && empty($params['end'])){
        	$where = sprintf(" and bm_month between '%s' and '%s'",$params['start'],date('Ym',time()));
        }elseif(!empty($params['start']) && !empty($params['end'])){
        	$where = sprintf(" and bm_month between '%s' and '%s'",$params['start'],$params['end']);
        }elseif(empty($params['start']) && !empty($params['end'])){
        	$where = sprintf(" and bm_month between '%s' and '%s'",date('Ym',strtotime("-6 month")),$params['end']);
        }else{
        	$where = sprintf(" and bm_month between '%s' and '%s'",date('Ym',strtotime("-6 month")),date('Ym',time()));
        	$params['start'] = date('Ym',strtotime("-6 month"));
        	$params['end'] = date('Ym',time());
        }
        $select = $db->get('at_brand_month',['bm_month as month']," group by bm_month");
        $list = $db->get('at_brand_month',["sum(bm_count) as bm_counts,at_brand_month.*"],sprintf(" %s group by bm_brand order by bm_counts desc limit 500",$where));
		$brandArr = array_column($list['data'],'bm_brand');

		$where .= sprintf(" and bm_brand in ('%s') group by bm_brand,bm_modtype",implode("','",$brandArr));
		$templist = $db->get('at_brand_month',["sum(bm_count) as bm_counts,at_brand_month.*"],$where);
		$arr = [];
		foreach ($templist['data'] as $val) {
			$arr[$val['bm_modtype']][$val['bm_brand']] = $val['bm_counts'];
		}
		foreach ($list['data'] as &$value) {
			$value['pc'] = $arr['pc'][$value['bm_brand']]??0;
			$value['cv'] = $arr['cv'][$value['bm_brand']]??0;
		}
		unset($value);
		if (!empty($params['sort'])) {
			$sortarr = array_column($list['data'],$params['sort']);
			array_multisort($sortarr,SORT_DESC ,$list['data'] , SORT_DESC);
		}
		LibTpl::Set('list',array_chunk($list['data'],100));
        LibTpl::Set('select',$select['data']);
        LibTpl::Set('params',$params);
		LibTpl::Set('title', '品牌排行');
		LibTpl::Put();
	}

	/**
	 * [partsPhb 零件排行榜]
	 * @Author   Yangxing
	 * @DateTime 2020-05-08T11:58:18+0800
	 * @return   [type]                   [view]
	 */
	public function partsPhb()
	{
        LibRule::Check('AP00');
		$params = mvc::$URL_PARAMS;
		$where = '';
        if(!empty($params['start']) && empty($params['end'])){
        	$where = sprintf(" and bp_month between '%s' and '%s'",$params['start'],date('Ym',time()));
        }elseif(!empty($params['start']) && !empty($params['end'])){
        	$where = sprintf(" and bp_month between '%s' and '%s'",$params['start'],$params['end']);
        }elseif(empty($params['start']) && !empty($params['end'])){
        	$where = sprintf(" and bp_month between '%s' and '%s'",date('Ym',strtotime("-6 month")),$params['end']);
        }else{
        	$where = sprintf(" and bp_month between '%s' and '%s'",date('Ym',strtotime("-6 month")),date('Ym',time()));
        	$params['start'] = date('Ym',strtotime("-6 month"));
        	$params['end'] = date('Ym',time());
        }

		$db = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		$select = $db->get('at_part_month',['bp_month as month'],sprintf(" group by bp_month"));

		$list = $db->get('at_part_month',['sum(bp_count) as bp_counts,at_part_month.*'],sprintf(" %s group by bp_part order by bp_counts desc limit 500",$where));
	
		LibTpl::Set('params',$params);
		LibTpl::Set('list',$list['data']);
		LibTpl::Set('select',$select['data']);
		LibTpl::Put();
	}

	/**
	 * [userPhb 用户排行榜]
	 * @Author   Yangxing
	 * @DateTime 2020-05-08T11:58:10+0800
	 * @return   [type]                   [view]
	 */
	public function userPhb()
	{
        LibRule::Check('AP00');
		$Params = mvc::$URL_PARAMS;
		$Params['time'] = empty($Params['time'])? date('Y-m-01').' ~ '.date('Y-m-d'): $Params['time'];
		$page=!empty($Params['page'])?(int)$Params['page']:1;

		$perPage=!empty($_COOKIE['perPage'])? (int)$_COOKIE['perPage'] : 25;

		$db = new BaseDb(mvc::$cfg['DB']['API_TJ']);

		$where = '';

		$orderByName = '';

		if($Params['order_name'])
		{
			$orderByName = $Params['order_name'];
		}
		else
		{
			$orderByName = 'ud_pv';
		}

		if($Params['user'] == 1)
		{
			//未注册
			$where .= sprintf(" and ud_uid = 0");
		}
		if($Params['user'] == 2)
		{
			//已注册
			$where .= sprintf(" and ud_uid > 0");
		}

		if($Params['time'])
		{
			$temp = explode(" ~ ", $Params['time']);
			$where .= sprintf(" and ud_date between %d and %d",date('Ymd',strtotime($temp['0'])),date('Ymd',strtotime($temp['1'])));
		}

		$config = [
			'ud_pv' => '总PV',
			'plj_pv' => '跑街PV',
			'yp_pv' => '宜配PV',
			'vin_pv' => 'VIN数',
			'number_count' => '号码数',
			'epc_count' => 'EPC数'
		];

		$lists = $db->get("at_user_date",
			[
				'ud_uid as uid',
				'SUM(ud_pv) as ud_pv',
				'SUM(ud_pjl_pv) as plj_pv',
				'SUM(ud_yp_pv) as yp_pv',
				'SUM(ud_vin_pv) as vin_pv',
				'SUM(ud_number_count) as number_count',
				'SUM(ud_epc_count) as epc_count'
			],
			sprintf(' %s GROUP BY ud_uid ORDER BY %s DESC limit %s,%s',$where,$orderByName,($page-1)*$perPage,$perPage)
		);
		//var_dump($where);
		$res= $db->get(
			'(SELECT ud_uid FROM at_user_date where 1=1 '.$where.' GROUP BY ud_uid ORDER BY null) as tt',
			['count(*) count'],
			'',
			true
		);
		$uArr = array_unique(array_column($lists['data'], 'uid'));

		if(!empty($uArr))
		{

			$PostData=[
				'filed'=>['u_id','u_name','u_name'],
				'where'=>sprintf(" and u_id in(%s)",implode(',',$uArr)),
				'oneRow'=>false
			];

			$resArr = (new LibYpApi)->Get('user/getUser', [], $PostData);

			LibTpl::Set('user', array_column($resArr['data'],null, 'u_id'));
		}

		$Page = LibPage::Show($res['data']['count'],$where ,$perPage);

		LibTpl::Set('Page', $Page);

		LibTpl::Set('param',$Params);

		LibTpl::Set('lists',$lists['data']);

		LibTpl::Set('config',$config);

		LibTpl::Put();
	}

	/* 
	* @method    申请单列表
	* @Author   Zheng
	*/
	public function applyList()
	{
		LibRule::Check('HY01');
		$typeList = [
			'user'=>'账户相关',
			'invcode'=>'邀请码',
			'orther'=>'其他'
		];
		$statusList = [
			'0'=>'待处理',
			'2'=>'初审通过',
			'1'=>'已处理',
			'-1'=>'退回'
			
		];
		$params = mvc::$URL_PARAMS;
		$Params = array_map('trim',$params);
		$where = '';
		foreach($params as $field=>$val)
		{
			$val = LibFc::Escape($val);
			if($val == '') continue;
			switch($field)
			{
                case 'ap_status':
					$where .= sprintf(" and ap_status = %d", $val);
                    break;
				case 'ap_type':
					$where .= sprintf(" and ap_type = '%s'", $val);
				break;
			}
		}
		$PjlBase = new PjlBase();
		$res = $PjlBase->get('bu_apply',['count(*) count'], $where, true);
		$count = $res['data']['count'];
		$listArr = [];
		if ($count > 0)
		{
			$page = (int) $params['page'];
			$page = $page < 1 ? 1: $page;
            $perPage = !empty($_COOKIE['perPage']) ? (int)$_COOKIE['perPage'] : 20;
			$res = $PjlBase->get('bu_apply',['*'],sprintf('%s order by CASE WHEN ap_status =0 THEN 0 ELSE 1 END,ap_atime desc limit %d, %d', $where, ($page-1)*$perPage, $perPage));
			
			if (!empty($res['data']))
			{
				$listArr = $res['data'];
				foreach($listArr as $k=> &$v)
				{	
                    $v['ap_imgs'] = !empty($v['ap_imgs'])? explode(',',$v['ap_imgs']):[];
					$v['ap_type_text'] = $typeList[$v['ap_type']]??'';
					$v['ap_atime'] = date('Y-m-d H:i', $v['ap_atime']);
					$v['ap_etime'] = $v['ap_etime']?date('Y-m-d H:i', $v['ap_etime']):'';
					$listArr[$k] = $v;
				}
				unset($v);
			}
			$page = LibPage::Show($count, $perPage);
			LibTpl::Set('Page', $page);
		}
		LibTpl::Set('params',$params);
		LibTpl::Set('statusList',$statusList);
		LibTpl::Set('typeList',$typeList);
		LibTpl::Set('lists',$listArr);
		LibTpl::Set('title','申请单列表');
		LibTpl::Put();
	}

	/* 
	* @method 审核申请单
	* @author Zheng
	*/
	public function editApply()
	{
		LibRule::Check('HY01');
		if(!empty($_POST))
		{
			$dataArr = array_map([LibFc::class,'Escape'],$_POST);
			if(!empty($dataArr['ap_id']))
			{
				$apId = $dataArr['ap_id'];
				$PjlBase = new PjlBase();
				$where = sprintf(" and  ap_id = %d", $apId);
				$result = $PjlBase->get('bu_apply', ['*'], $where, true);
				if (!$result['data']) return LibFc::ajaxJsonEncode(['status' => false, 'data' => '不存在该记录']);
				//拼装需要更新的字段
				$data = [
					'ap_status' => $_POST['ap_status'] ?? 0,//更改状态
					'ap_etime' => time(), //更改处理时间
					'ap_check_uid' => $_SESSION['admin_userid'], //处理人id
					'ap_check_name' => $_SESSION['admin_uname'], //处理人姓名
					'ap_check_remark' => $_POST['ap_check_remark'], //更改处理意见
				];
				$res = $PjlBase->Set('bu_apply', $data, $where);
				if($res['status']){
					//0待处理  1已处理 -1退回
					if($data['ap_status'] != $result['data']['ap_status']){
						$LibYpApi = new LibYpApi();
						$addtime = date('m-d H:i',$result['data']['ap_atime']);
						$statusList = ['0'=>'待处理','1'=>'已处理','-1'=>'退回','2'=>'初审通过'];
						$msg = "{$addtime}提交的申请单{$result['data']['ap_id']}，状态被改为：".$statusList[$data['ap_status']];
						if($data['ap_check_remark']){
							$msg = "{$addtime}提交的申请单{$result['data']['ap_id']}，状态被改为：{$statusList[$data['ap_status']]}，处理意见：{$data['ap_check_remark']}";
						}
						$postData = [
							'msg'=> $msg,
							'uids'=> $result['data']['ap_by_uid'],
							'msgType'=>'im'
						];
						$LibYpApi->Get('im/sendImSysNotice',[],$postData);
					}
				}
				return LibFc::ajaxJsonEncode(['status' => true, 'data' => '操作成功']);
			}
		}
		$params = mvc::$URL_PARAMS;
		if(LibFc::Int($params['ap_id']))
		{
			$where=sprintf(' and ap_id=%d',$params['bid']);
			$PjlBase = new PjlBase();
			$where = sprintf(" and ap_id = %d", $params['ap_id']);
			$result = $PjlBase->get('bu_apply', ['*'], $where, true);
			if (!$result['data']) return LibFc::ajaxJsonEncode(['status' => false, 'data' => '不存在该记录']);
			$apType = [
				'user'=>'账户相关',
				'invcode'=>'邀请码',
				'orther'=>'其他'
			];
			$result['data']['ap_type_text'] = $apType[$result['data']['ap_type']]?:'';
			$result['data']['ap_imgs'] =  !empty($result['data']['ap_imgs'])? explode(',',$result['data']['ap_imgs']):[];
			LibTpl::Set('data', $result['data'] ?: []);
		}
		LibTpl::Set('title','审核申请单');
		LibTpl::Put();
	}

	/* 
	* @method 删除申请单
	* @author Zheng
	*/
	public function delApply()
	{
		LibRule::Check('HY01');
		$apId = (int) LibFc::Escape($_POST['ap_id']);
		if($apId <= 0){
			return LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
		}
		$PjlBase = new PjlBase();
        $result = $PjlBase->del('bu_apply', sprintf(' and ap_id = %d ', $apId));
      	return  LibFc::ajaxJsonEncode($result);
	}

	/**
	 * @method 白名单
	 * @author zhengweihua 
	 * @copyright 2022-07-18
	 */
	public function whiteList()
	{
		LibRule::Check('AP00');
		$Params = MVC::$URL_PARAMS;
		$Params = array_map('trim',$Params);
		$LibYpApi=new LibYpApi();
		$where = '';
		$page =! empty($Params['page'])?(int)$Params['page']:1;
		$perPage =! empty($_COOKIE['perPage'])? (int)$_COOKIE['perPage'] : 25;
		
		if(!empty($Params['wl_uid'])){
            $PostData=[
                'filed'=>['u_id','u_name'],
                'where'=>sprintf(" and (u_name='%s' or u_mobile = '%s')",$Params['wl_uid'],$Params['wl_uid']),
                'oneRow'=>true
            ];
            $userArr = $LibYpApi->Get('user/getUser', [], $PostData);
            if(empty($userArr['data']['u_id']))
            {
                $uid = -1;
            }else{
                $uid = $userArr['data']['u_id'];
            }
		    $where .= sprintf(" and wl_uid=%d",$uid);
        }
		$db = new BaseDb(mvc::$cfg['DB']['API_TJ']);
        $res = $db->get('tj_whitelist',['count(*) count'], $where, true);
		$total = $res['data']['count'];
		$Page = LibPage::Show($total, $perPage);

		LibTpl::Set('Page', $Page);
		if($total>0)
		{
			$orderBy='';
			$where.=sprintf(' order by wl_id desc limit %d,%d',($page-1)*$perPage,$perPage);
			$where.=$orderBy;
			$res = $db->get('tj_whitelist',['*'], $where);
			$uArr=array_column($res['data'], 'wl_uid');
			LibTpl::Set('lists',$res['data']);
			if(!empty($uArr))
			{
			    $uIds = implode(',',$uArr);
			    $shop = (new PjlBase)->get("pl_shop",['shop_name','shop_pu_id'],sprintf(" and shop_pu_id in (%s)",$uIds));
			    if(empty($shop['data'])){
                    $shop = [];
                }else{
                    $shop = array_column($shop['data'],'shop_name','shop_pu_id');
                }
                LibTpl::Set('shop',$shop);
				$PostData=[
					'filed'=>['u_id','u_name'],
					'where'=>sprintf(" and u_id in(%s)",$uIds),
					'oneRow'=>false
				];
				$resArr = $LibYpApi->Get('user/getUser', []
				, $PostData);
				LibTpl::Set('user', array_column($resArr['data'],'u_name', 'u_id'));
			}
		}
		LibTpl::Set('param',$Params);
		LibTpl::Set('title','api黑名单-跑街令');
		LibTpl::Put();
	}

	/**
	 * @method 添加/编辑白名单
	 * @author zhengweihua 
	 * @copyright 2022-07-18
	 */
	public function addWhite()
	{
		LibRule::Check('AP00');
		$LibYpApi = new LibYpApi();
		$db = (new BaseDb(mvc::$cfg['DB']['API_TJ']));
		$data = [];
		$Params = MVC::$URL_PARAMS;
		$title = '添加白名单-跑街令';
		if (LibFc::Int($Params['wid'])) {
			$where = sprintf(' and wl_id=%d', $Params['wid']);
			$res = $db->get('tj_whitelist',['*'],$where,true);
			$data = $res['data'];
			$title = '编辑白名单-跑街令';
			if (!empty($data) && !empty($data['wl_uid'])) {
				$PostData = [
					'filed' => ['u_id', 'u_name'],
					'where' => sprintf(" and u_id=%d", $data['wl_uid']),
					'oneRow' => true
				];
				$resArr = $LibYpApi->Get('user/getUser', [], $PostData);
				if(!empty($resArr['data']['u_name'])){
					$data['u_name'] = $resArr['data']['u_name'];
				}
			}
		}
		LibTpl::Set('data',$data);
		LibTpl::Set('title', $title);
		LibTpl::Put();
	}
	/**
	 * @method 保存白名单
	 * @author zhengweihua 
	 * @copyright 2022-07-18
	 */
	public function saveWhite()
	{
		LibRule::Check('AP00');
		$data = array_map([LibFc::class,'Escape'],$_POST);
        unset($data['isAjax']);
        if(empty($data['wl_etime']) || empty($data['wl_btime'])){
            LibFc::ReturnJson(0,'时间不可为空');
        }
		$data['wl_btime'] = strtotime($data['wl_btime']);
        $data['wl_etime'] = strtotime($data['wl_etime']);
        if(empty($data['wl_remark']) || strlen($data['wl_remark']) > 64){
            LibFc::ReturnJson(0,'备注不可为空或者过长');
        }
        $LibYpApi=new LibYpApi();
		$tempUser = $data['wl_user_name'];
		if(empty($tempUser)){
			LibFc::ReturnJson(0,'用户名称不存在');
		}
		$param=[
			'filed'=>['u_id','u_name'],
			'where'=>sprintf(" and u_name='%s'",$tempUser),
			'oneRow'=>true
		];
		$userArr = $LibYpApi->Get('user/getUser', [], $param);
		if($userArr['status'] == true && isset($userArr['data']['u_id']) && $userArr['data']['u_id'] > 0){
			$data['wl_uid'] = $userArr['data']['u_id'];
		}else{
			LibFc::ReturnJson(0,'找不到该用户');
		}
		unset($data['wl_user_name']);
        $db =  $db = (new BaseDb(mvc::$cfg['DB']['API_TJ']));
        if($data['wl_id'] > 0){
            $wlId = $data['wl_id'];
            unset($data['wl_id']);
            $result = $db->Set('tj_whitelist',$data,sprintf(" and wl_id=%d",$wlId));
        }else{
            $data['wl_atime'] = time();
            $result = $db->Add('tj_whitelist',$data);
        }
        LibFc::ajaxJsonEncode($result);
	}

	/**
	 * @method 删除白名单
	 * @author zhengweihua 
	 * @copyright 2022-07-18
	 */
	public function delWhite()
	{
		LibRule::Check('AP00');
		$Params = MVC::$URL_PARAMS;
		$wid = (int) LibFc::Escape($_POST['wid']);
		if(empty($wid)){
			LibFc::ReturnJson(0, '参数错误');
		}

		$db = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		// $wlres = $db->Get('tj_whitelist',['wl_remark,wl_id'],sprintf(" and wl_id=%d",$wid),true);
		$result = $db->Del('tj_whitelist',sprintf(" and wl_id=%d",$wid));
        LibFc::ajaxJsonEncode($result);

	}

	public function tjAnalyse()
	{	
		LibRule::Check('SY02');
		$params = mvc::$URL_PARAMS;
		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);
        $page = !empty($params['page']) ? (int)$params['page'] : 1;
        $perPage = !empty($_COOKIE['perPage']) ? (int)$_COOKIE['perPage'] : 20;
		$where = " and td_act ='all' and td_site!='all'";
		$field = ['*'];
        if(!empty($params['td_site']))
        {
          $where .= sprintf(" and td_site='%s'", $params['td_site']);
		}
       
		//默认时间
		if(empty($params['time']))
		{	
			$params['time'] = date('Y-m-d',strtotime('-30 days')).' - '.date('Y-m-d');
		}
	
        //筛分时间
        if (!empty($params['time']))
        {
            $temp = explode(' - ', $params['time']);
            $where .= sprintf(" and td_date >= '%d' and td_date <= '%s'", LibFc::Escape(date('Ymd', strtotime($temp['0']))), LibFc::Escape(date('Ymd', strtotime($temp['1']))));
			$stime = date('Y/m/d',strtotime($temp[0]));
			$etime = date('Y/m/d',strtotime($temp[1]));
			LibTpl::Set('stime',$stime);
			LibTpl::Set('etime',$etime);
		}
		//有配置才显示
		if(mvc::$cfg['TJANALYSE']){
			$siteArr = $BaseDb->get('at_tongji_reg',['tr_site_name','tr_site'], ' group by tr_site_name,tr_site order by tr_seq asc');
			$siteArr = $siteArr['data'];
			$siteArr = array_column($siteArr,null,'tr_site');
			$setArr = array_keys(mvc::$cfg['TJANALYSE']);
			foreach ($setArr as  $val) {
				if($siteArr[strtoupper($val)]) $site[] = $siteArr[strtoupper($val)]; 
			}
			LibTpl::Set('site', $site);

			$res = $BaseDb->get('at_tongji_date', ['count(*) count'], $where, true);
			$Page = LibPage::Show($res['data']['count'], $perPage);
			LibTpl::Set('Page', $Page);

			if (!empty($res['data']['count']))
			{
				$where .= sprintf(' order by td_date desc limit %d,%d', ($page - 1) * $perPage, $perPage);
				$res = $BaseDb->get('at_tongji_date', $field, $where);
				$lists = $res['data'];
				foreach ($lists as $key=> $item) {
					$item['td_out_rate'] = '';
					$item['td_use_time'] = '';
					$sitekey = strtolower($item['td_site']);
					if(mvc::$cfg['TJANALYSE'][$sitekey])
					{
						$item['td_pv_count'] = $item['td_pv_count'] * mvc::$cfg['TJANALYSE'][$sitekey]['pv_rate'];
						$item['td_ip_count'] = $item['td_ip_count'] * mvc::$cfg['TJANALYSE'][$sitekey]['ip_rate'];
						$trate = (substr($item['td_pv_count'], -2) - substr($item['td_ip_count'], -2))/100;
						if($trate > 0.5 || $trate < -0.5) $trate = $trate/4;
						else if($trate > 0.3 || $trate < -0.3) $trate = $trate/3;
						$out_rate = mvc::$cfg['TJANALYSE'][$sitekey]['out_rate'];
						if(!empty($out_rate)) $item['td_out_rate'] = sprintf('%.2f', $out_rate*(1+$trate)*100).'%';
						$user_time =mvc::$cfg['TJANALYSE'][$sitekey]['use_time'];
						if ($user_time){
							$user_time = ceil($user_time*(1+$trate));
							$hour = floor($user_time/3600);
							$minute = floor(($user_time-3600 * $hour)/60);
							$second = floor((($user_time-3600 * $hour) - 60 * $minute) % 60);
							$item['td_use_time'] = str_pad($hour,2,0,STR_PAD_LEFT).":".str_pad($minute,2,0,STR_PAD_LEFT).":".str_pad($second,2,0,STR_PAD_LEFT);
						}
					}
					$lists[$key] = $item;
				}
				LibTpl::Set('lists', $lists);
			}
		}
		
		LibTpl::Set('Params', $params);
		LibTpl::Set('title', '统计分析');
		LibTpl::Put();
	}
}
