<?php
/**
*跳转
*/
class goAction extends baseAction
{
	//获取IP的省市区
	function ipToPct()
	{
		$YpcBase = new YpcBase();
		$OthPct = new OthPct();
		while(1)
		{
			$ipres = $YpcBase->Get('yt_ip_pct', ['ip'], ' and pct_name = "" order by rand () limit 1000');
			if(empty($ipres['data'])) break;
			foreach($ipres['data'] as $v)
			{
				$res = $OthPct->getIpPCT($v['ip']);
				$set = [
					'pct_name'=>implode(',', $res['data']['pcts']),
					'pct_ids'=>implode(',', $res['data']['pctids']),
				];
				$YpcBase->Set('yt_ip_pct', $set, sprintf(" and ip='%s'", $v['ip']));
			}
		}
		echo 'ok';
	}
	/**
	  * @method 微信回调后再由API调整到对应的链接  不需要token
	  * @http	get
	  * @author soul
	  * @copyright 2018/3/5
	  */
	public function wxRedirect()
	{
		if(empty($_GET['backurl']) || empty($_GET['app']) || empty($_GET['code'])) 
			LibFc::ReturnJson(false, 'backurl||app参数异常');
		$backUrl = base64_decode($_GET['backurl']);
		$MainWeiXin = new MainWeiXin();
		$res = $MainWeiXin->getUserByCode($_GET['app'], $_GET['code']);
		$data = base64_encode(json_encode($res['data']));
		$backUrl .= stripos($backUrl, '?') !== false? '&udata='.$data: '?udata='.$data;
		header('Location:'.$backUrl);
	}


	/**
	  * @method QQ回调后再由API调整到对应的链接  不需要token
	  * @http	get
	  * @author soul
	  * @copyright 2018/3/5
	  */
	public function qqRedirect()
	{
		if(empty($_GET['backurl']) || empty($_GET['app']) || empty($_GET['code'])) 
			LibFc::ReturnJson(false, 'backurl||app参数异常');
		$backUrl = base64_decode($_GET['backurl']);
		$MainQQ = new MainQQ();
		$res = $MainQQ->getUserByCode($_GET['app'], $_GET['code'], $backUrl);
		$data = base64_encode(json_encode($res['data']));
		$backUrl .= stripos($backUrl, '?') !== false? '&udata='.$data: '?udata='.$data;
		header('Location:'.$backUrl);
	}


	/**
	  * @method 微信发起的支付回调
	  * @author soul
	  * @copyright 2017/8/16
	  */
	function notifyWX()
	{
		$xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
		libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		$MainOrder = new MainOrder();
		$res = $MainOrder->get('pa_order', ['por_transaction_id', 'por_account'], sprintf(" AND por_transaction_id='%s'",  LibFc::Escape($data['transaction_id'])), true);
		if(!empty($res['data']['por_account']))
		{
			$MainWxNotify = new MainWxNotify($res['data']['por_account']);
			$MainWxNotify->Handle(false);
		}
		return true;
	}

	/**
	  * @method 支付宝发起的支付回调
	  * @author soul
	  * @copyright 2017/8/16
	  */
	function notifyAli()
	{
		if(!empty($_POST['out_trade_no']))
		{
			$MainBase = new MainBase();
			$res = $MainBase->get('pa_order', ['por_id', 'por_style', 'por_orderids'], sprintf(" AND por_trade_no='%s'", LibFc::Escape($_POST['out_trade_no'])), true);
			if(!empty($res['data']))
			{
				$MainOrder = new MainOrder();
				$MainOrder->checkPay($res['data']['por_id']);
				echo 'success';
			}
		}
	}

	/**
	  * @method 百度统计回调
	  * @http	get
	  * @author soul
	  * @copyright 2018/3/5
	  */
	public function baiduTjRedirect()
	{
		if(!empty($_GET['code']))
		{
			$code = $_GET['code'];
			$cfg = mvc::$cfg['WEBTJ']['PJL'];
			$LibCurl = new LibCurl();
			$redirect_uri = urlencode('http://hub.paojd.cn/go/baiduTjRedirect');
			$url = 'http://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code='.$code.'&client_id='.$cfg['API_KEY'].'&client_secret='.$cfg['SECRET_KEY'].'&redirect_uri='.$redirect_uri;
			$res = $LibCurl->fetch($url);
			$res = json_decode($res, true);
			if(!empty($res['access_token']))
			{
				$cacheFile = mvc::$cfg['ROOT'].'home/cache/BaiduTjToken.php';
				$arr = file_exists($cacheFile)? include($cacheFile): [];
				$res['expires_in'] = time()+$res['expires_in']-3600;
				$arr['PJL'] = $res;
				LibFc::ArraySave($arr, $cacheFile);
				echo 'ok';
			}
			else
			{
				echo $res['error_description'];
			}

		}
	}
	
	/**
	  * @method IM消息回调
	  * @author soul
	  * @copyright 2022/7/21
	  */
	public function imCallback()
	{
		$params = mvc::$URL_PARAMS;
		$postStr = file_get_contents('php://input');
		if($params['SdkAppid'] == mvc::$cfg['IM']['APP_ID'] && !empty($params['CallbackCommand']))
		{
			$YpwUser = new YpwUser();
			$dataArr = json_decode($postStr, true);
			$addArr = [
				'icb_callname'=>$dataArr['CallbackCommand'],
				'icb_json'=>json_encode($dataArr, JSON_UNESCAPED_UNICODE),
				'icb_atime'=>time()
			];
			$chkUser = [];
			if(!empty($dataArr['From_Account']))
			{
				$addArr['icb_from'] = $dataArr['From_Account'];
				$chkUser[] = LibFc::Escape($addArr['icb_from']);
			}
			if(!empty($dataArr['To_Account']))
			{
				$addArr['icb_to'] = $dataArr['To_Account'];
				$chkUser[] = LibFc::Escape($addArr['icb_to']);
			}
			if(!empty($chkUser))
			{
				$uidArr = [];
				$res = $YpwUser->get('yp_user', ['u_id', 'upper(u_name) u_name'], sprintf(" and u_name in ('%s')", implode("','", $chkUser)));
				$hasArr = array_column($res['data'], 'u_id', 'u_name');
				if(!empty($addArr['icb_from']))
				{
					$addArr['icb_from_uid'] = (int) $hasArr[strtoupper($addArr['icb_from'])];
					$uidArr[] = $addArr['icb_from_uid'];
				}
				if(!empty($addArr['icb_to']))
				{
					$addArr['icb_to_uid'] = (int) $hasArr[strtoupper($addArr['icb_to'])];
					$uidArr[] = $addArr['icb_to_uid'];
				}
				$OthIm = new OthIm();
				$OthIm->addImActUser($uidArr, 'im');
			}
			$YpwUser->add('im_callback', $addArr);
		}
		echo '{"ActionStatus":"OK","ErrorInfo": "","ErrorCode":0}';
	}

	/**
	  * @method IM活跃用户汇集
	  * @author soul
	  * @copyright 2022/7/21
	  */
	public function initImActUser()
	{
		if(!LibFc::hasFunLock(mvc::$URL_METHOD, 3600)) return true;
		$now = time();
		$btime = strtotime('-3 day');
		$sqlArr = [
			"delete from im_actuser where at_from!='manual'",
			//入驻商家
			"INSERT INTO im_actuser (at_uid, at_etime, at_from)
			SELECT u_id, {$now}, 'shop' FROM yp_user 
			WHERE u_id IN (SELECT DISTINCT shop_pu_id FROM `yp_paojieling`.`pl_shop` where shop_status=2)
			AND u_id NOT IN (SELECT at_uid FROM im_actuser)",
			
			//维修厂
			/*"INSERT INTO im_actuser (at_uid, at_etime, at_from)
			SELECT u_id, {$now}, 'repair' FROM yp_user 
			WHERE u_id IN (SELECT DISTINCT shopr_pu_id FROM `yp_paojieling`.`pl_repair` where shopr_status=2)
			AND u_id NOT IN (SELECT at_uid FROM im_actuser)",*/
			
			//询单
			"INSERT INTO im_actuser (at_uid, at_etime, at_from)
			SELECT u_id, {$now}, 'purchase' FROM yp_user 
			WHERE u_id IN (SELECT DISTINCT pur_pu_id FROM `yp_paojieling`.`pl_purchase` where pur_status>=0 and pur_atime>{$btime})
			AND u_id NOT IN (SELECT at_uid FROM im_actuser)",
			
			//订单
			"INSERT INTO im_actuser (at_uid, at_etime, at_from)
			SELECT u_id, {$now}, 'order' FROM yp_user 
			WHERE u_id IN (SELECT DISTINCT ord_pu_uid FROM `yp_paojieling`.`pl_order` where ord_atime>{$btime})
			AND u_id NOT IN (SELECT at_uid FROM im_actuser)",

			//商城商家
			"INSERT INTO im_actuser (at_uid, at_etime, at_from)
			SELECT u_id, {$now}, 'shop' FROM yp_user 
			WHERE u_id IN (SELECT DISTINCT shop_uid FROM `ypb2c`.`sh_shop` where shop_status = 1)
			AND u_id NOT IN (SELECT at_uid FROM im_actuser)",

			//商城订单
			"INSERT INTO im_actuser (at_uid, at_etime, at_from)
			SELECT u_id, {$now}, 'order' FROM yp_user 
			WHERE u_id IN (SELECT DISTINCT ord_uid FROM `ypb2c`.`or_order`)
			AND u_id NOT IN (SELECT at_uid FROM im_actuser)",
			
			//广告主
			"INSERT INTO im_actuser (at_uid, at_etime, at_from)
			SELECT u_id, {$now}, 'order' FROM yp_user 
			WHERE u_id IN (SELECT DISTINCT ads_u_id FROM `b2c_other`.`pj_user_ads`)
			AND u_id NOT IN (SELECT at_uid FROM im_actuser)",

			//聊天记录
			"INSERT INTO im_actuser (at_uid, at_etime, at_from)
			SELECT u_id, {$now}, 'im' FROM yp_user 
			WHERE (
				u_id IN (SELECT DISTINCT icb_from_uid FROM im_callback where icb_atime>{$btime}) 
				OR u_id IN (SELECT DISTINCT icb_to_uid FROM im_callback where icb_atime>{$btime})
			)
			AND u_id NOT IN (SELECT at_uid FROM im_actuser)",
		];
		$YpwBase = new YpwBase();
		$YpwBase->exeAnySql($sqlArr);
		LibFc::delFunLock(mvc::$URL_METHOD);
		echo 'ok';
	}


	//检测24小时内的支付
	function checkPay()
	{
		$now = time();
		$lockFile = mvc::$cfg['PATH_ROOT'].'checkPayLock.txt';
		//被锁超过2分钟自动解锁
		if(file_exists($lockFile) && (time() - filemtime($lockFile)) < 120) return true;
		file_put_contents($lockFile, 'lock');
		$MainBase = new MainBase();
		$MainOrder = new MainOrder();
		$YpwUser = new YpwUser();
		$PjlUser = new PjlUser();

		//PJLVIP
		$res = $PjlUser->get('pl_user_vip_list', ['uvl_id'], sprintf(" and uvl_status = 0 and uvl_btime > %d", time()-3600*24*2));
		foreach($res['data'] as $v)
		{
			$PjlUser->checkVipOrderPay($v['uvl_id']);
		}

		//PJLPAC
		$res = $PjlUser->get('pl_user_pac_list', ['upl_id'], sprintf(" and upl_status = 0 and upl_btime > %d", time()-3600*24*2));
		foreach($res['data'] as $v)
		{
			$PjlUser->checkPacOrderPay($v['upl_id']);
		}

		//PJLTSPAC
		$res = $PjlUser->get('pl_tuisong_order', ['tuo_id'], sprintf(" and tuo_status = 0 and tuo_btime > %d", time()-3600*24*2));
		foreach($res['data'] as $v)
		{
			$PjlUser->checkTsfwPacOrderPay($v['tuo_id']);
		}

		//PJLCZ
		$res = $PjlUser->get('pl_money_chongzhi', ['moc_id'], sprintf(" and moc_status = 0 and moc_btime > %d", time()-3600*24*2));
		foreach($res['data'] as $v)
		{
			$PjlUser->checkChongZhiOrderPay($v['moc_id']);
		}

		//APIZYB
		$MainZyb = new MainZyb();
		$res = $MainZyb->get('api_zyb', ['az_id'], sprintf(" and az_status = 0 and az_atime > %d", time()-3600*24*2));
		foreach($res['data'] as $v)
		{
			$MainZyb->checkZybOrderPay($v['az_id']);
		}

		//YPING
		$res = $YpwUser->get('yp_user_pay', ['up_id'], sprintf(" and up_status = 0 and up_atime > %d", time()-3600*24*2));
		foreach($res['data'] as $v)
		{
			$YpwUser->checkRechargeIntegral($v['up_id']);
		}

		$res = $MainBase->get('pa_refund', ['pre_id'], sprintf(" and pre_status = 0 and pre_atime > %d", time()-3600*24*15));
		foreach($res['data'] as $v)
		{
			$MainOrder->getRefund($v['pre_id']);
		}
		
		$PjlMoney = new PjlMoney();
		$res = $PjlMoney->get('pl_money_withdrawals', ['mow_id'], sprintf(" and mow_type = 0 and mow_status = 0 and mow_atime > %d", time()-3600*24*7));
		foreach($res['data'] as $v)
		{
			$PjlMoney->checkWithdrawShop($v['mow_id']);
		}
		
		@unlink($lockFile);

		//初始化用户IM
		$YpwUser = new YpwUser();
		$res = $YpwUser->get('yp_user', ['u_id'], sprintf(" and u_im_init = 'wait' and u_register_time > %d", time()-3600*24*15));
		if(!empty($res['data']))
		{
			$OthIm = new OthIm();
			$OthIm->importUser(array_column($res['data'], 'u_id'));
		}
		echo 'ok';
	}

}