<?php
/**
  * @class 企微机器人
  * @author soul 2022/5/27
  */
class wechatQwAction
{
	private $orgArr = [];
	private $postArr = [];
	public $btime = 0;
	public $eywid = '';
	public $tokenInfo = [];

	public function __construct()
	{
		$this->btime = microtime(true);
		$postStr = file_get_contents('php://input');
		$this->orgArr = json_decode($postStr, true);
		LibFc::logs(json_encode($this->orgArr, JSON_UNESCAPED_UNICODE), mvc::$cfg['LOGS'].$this->orgArr['wcId'].'.log');
		$B2cBase = new B2cBase();
		$where = !empty($_GET['wrt_id']) ? sprintf(" and wrt_token_type='qiweapi' and wrt_id=%d", $_GET['wrt_id']) : sprintf(" and wrt_token_type='qiweapi' and wrt_wxid='%s'", LibFc::Escape($this->orgArr['wcId']));
		$res = $B2cBase->get('wx_robot_token', ['wrt_id', 'wrt_wxid', 'wrt_token', 'wrt_token_type', 'wrt_sleeptime', 'wrt_loginurl', 'wrt_endtime', 'wrt_eywid', 'wer_eyproxy', 'wrt_verify', 'wrt_verifycode', 'wrt_device', 'wrt_addrinit'], $where, true);
		if(empty($res['data']) || strtotime($res['data']['wrt_endtime']) < time()){
			LibFc::logs($this->orgArr['wcId'].'机器人token不可用');
			exit;
		}
		$this->tokenInfo = $res['data'];
		if($this->tokenInfo['wrt_token_type'] != 'qiweapi'){
			echo $this->tokenInfo['wrt_id'].'=>TOKEN类型'.$this->tokenInfo['wrt_token_type'].'不符';
			exit;
		}
		$this->postArr['wrt_id'] = $this->tokenInfo['wrt_id'];
		$this->eywid = $this->tokenInfo['wrt_eywid'];
	}

	//获取登陆二维码 wechatQw/restart?wrt_id=xxx
	public function restart()
	{
		$B2cBase = new B2cBase();
		//创建设备
		if($this->tokenInfo['wrt_token'] && empty($this->eywid)){
			$tpost = [
				'proxyUrl'=>'',
				'areaCode'=>$this->tokenInfo['wer_eyproxy']? $this->tokenInfo['wer_eyproxy']: 440000,
				'deviceName'=>'my ipad',
				'deviceType'=>$this->tokenInfo['wrt_device'] == 'windows'? 2: 0,
				'clientVersion'=>''
			];
			$res = $this->getWxApi('/client/createClient', $tpost);
			if(!empty($res['data']['guid'])){
				$this->eywid = $res['data']['guid'];
				$this->tokenInfo['wrt_eywid'] = $this->eywid;
				$B2cBase->set('wx_robot_token', ['wrt_eywid'=>$this->eywid], sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']));
			}else{
				LibFc::ReturnJson(false, '创建设备失败'.json_encode($res, JSON_UNESCAPED_UNICODE));
			}
		}
		for($i = 1; $i < 20; $i++){
			$res = $this->getWxApi('/login/getLoginQrcode', ["useCache"=>false]);
			LibFc::logs($this->tokenInfo['wrt_id'].'重启=>'.$i.'=>'.json_encode(['post'=>$tpost, 'result'=>$res], JSON_UNESCAPED_UNICODE));
			if(!empty($res['data']['loginQrcodeKey'])){
				$set = [
					'wrt_loginurl'=>$res['data']['qrUrl'],
					'wrt_loginurl_time'=>time(),
					'wrt_verify'=>1,
					'wrt_verifycode'=>'',
					'wrt_chknew'=>'',
					'wrt_addrinit'=>0,
					'wrt_loginstatus'=>-1,
					'wrt_sleeptime' => date('Y-m-d H:i:s', time() - 24*3600)
				];
				$B2cBase->set('wx_robot_token', $set, sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']));
				set_time_limit(5);
				ignore_user_abort(true); 
				$http = new LibHttp(false,false);
				$http->timeout = 5;
				$url = 'http://hub.paojd.cn:75/wechatQw/checkLogin?wrt_id='.$this->tokenInfo['wrt_id'];
				$html = $http->fetch($url);
				LibFc::logs($url.$html);
				LibFc::ReturnJson(true, $html);
			}
			sleep(5);
		}
		LibFc::ReturnJson(false, '请点击微信上方的IPAD进行“退出登录”操作，再点击“重启”。'.json_encode($res, JSON_UNESCAPED_UNICODE));
	}
	
	
	//检测登陆状态 wechatE/checkLogin?wrt_id=xxx
	public function checkLogin()
	{
		set_time_limit(0);
		$B2cBase = new B2cBase();
		for($i = 1; $i < 20; $i++){
			$res = $B2cBase->get('wx_robot_token', ['wrt_verify', 'wrt_verifycode'], sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']), true);
			if($res['data']['wrt_verify'] == 1 && $res['data']['wrt_verifycode']){
				$res = $this->getWxApi('/login/verifyLoginQrcode', ['code'=>$res['data']['wrt_verifycode']]);
				LibFc::logs($_GET['wrt_id'].':检测验证码'.$i.'=>'.json_encode($res, JSON_UNESCAPED_UNICODE));
			}
			$res = $this->getWxApi('/login/checkLoginQrCode');
			LibFc::logs($_GET['wrt_id'].':检测'.$i.'=>'.json_encode($res, JSON_UNESCAPED_UNICODE));
			if($res['data']['loginQrcodeStatus'] == 2){
				//登陆成功
				$info = $res['data'];
				$wxInfo = [
					'wxid'=>$info['userId'],
					'nickName'=>$info['nickname'],
					'mobile'=>'',
					'weixin'=>$info['nickname'],
					'avatar'=>$info['avatarUrl'],
					'corpId'=>$info['corpId'],
				];
				$set = [
					'wrt_wxid'=>$wxInfo['wxid'],
					'wrt_sleeptime'=>date('Y-m-d H:i:s', time() + 24*3600),
					'wrt_wxinfo'=>json_encode($wxInfo, JSON_UNESCAPED_UNICODE),
					'wrt_comname'=>$wxInfo['corpId'],
					'wrt_loginurl'=>'',
					'wrt_verify'=>-1,
					'wrt_verifycode'=>'',
					'wrt_loginurl_time'=>0,
					'wrt_chknew'=>'',
					'wrt_loginstatus'=>1
				];
				$B2cBase->set('wx_robot_token', $set, sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']));
				//设置回调地址
				$this->getWxApi('/client/setCallback', ['callbackUrl'=>mvc::$cfg['QWBOT']['callback']]);
				LibFc::ReturnJson(true);
			}if($res['data']['loginQrcodeStatus'] == 10){
				$B2cBase->set('wx_robot_token', ['wrt_verify'=>1], sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']));
			}else if(stripos($res['message'], '重新登录')){
				break;
			}
			sleep(5);
		}
		LibFc::ReturnJson(false, '获取登陆状态失败'.json_encode($res, JSON_UNESCAPED_UNICODE));
	}

	
	//检测所有机器人状态
	function chkRobot()
	{
		/*$res = $this->getWxApi('/login/checkLogin');
		if($res['code'] === 0){
			$B2cBase = new B2cBase();
			if($res['data']['isOnline']){
				$B2cBase->set('wx_robot_token', ['wrt_loginstatus'=>1], sprintf(" and wrt_eywid='%s'", $this->tokenInfo['wrt_eywid']));
			}else{
				$B2cBase->set('wx_robot_token', ['wrt_loginstatus'=>-1], sprintf(" and wrt_eywid='%s' AND wrt_token_type IN ('qiweapi')", $this->tokenInfo['wrt_eywid']));
				$url = mvc::$cfg['QWBOT']['handlebase'].'restart?wrt_id='.$this->tokenInfo['wrt_id'].'&type='.$this->tokenInfo['wrt_token_type'];
				$LibHttp = new LibHttp();
				$LibHttp->fetch($url);
			}
		}
		echo 'ok';*/
	}


	//机器人的接口
	public function getWxApi($path, $params = []){
		$url = mvc::$cfg['QWBOT']['api'];
		if(!empty($this->eywid)) $params['guid'] = $this->eywid;
		$headers = ['Content-Type: application/json'];
		if($this->tokenInfo['wrt_token']) $headers[] = 'X-QIWEI-TOKEN: '.$this->tokenInfo['wrt_token'];
		$data = [
			'method'=>$path,
			'params'=>is_array($params)? $params: []
		];
		$data = json_encode($data);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		$ssl = substr($url, 0, 8) == "https://" ? true : false;
		if($ssl){
		   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);// 信任任何证书
		   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);// 检查证书中是否设置域名
		}
		$html = curl_exec($ch);
		//echo $url.'=>'.$data.'=>'.$html;
		$response = json_decode($html ,true);
		if(!isset($response['code']) || $response['code'] !== 0){
			LibFc::logs('QW接口异常：'.$path.'=>'.$html.'=>'.$data.'=>'.json_encode($headers));
			if(stripos($response['msg'], '不在线')){//{"code":422100,"msg":"guid错误: 客户端实例不存在/不在线","data":{}}
				$this->getWxApi('/client/restoreClient');
				return $this->getWxApi($path, $params);
			}else if(stripos($response['msg'], '停止实例')){//{"code":422100,"msg":"该实例已在线，不可重复恢复。如需重置，请先停止实例","data":{}}
				$this->getWxApi('/client/stopClient');
				return $this->getWxApi($path, $params);
			}
			LibFc::ReturnJson(false, 'QW接口异常：'.$path.'=>'.$html.'=>'.$data.'=>'.json_encode($headers));
		}
		LibFc::logs('QW接口：'.$path.'=>'.$html.'=>'.$data.'=>'.json_encode($headers));
		return $response;
	}
}