<?php
/**
  * @class ge微信机器人
  * @author soul 2022/5/27
  */
class wechatGeAction
{
	private $orgArr = [];
	private $postArr = [];
	public $btime = 0;
	public $eywid = '';
	public $tokenInfo = [];

	public function __construct()
	{
		ignore_user_abort(true);
		set_time_limit(0);
		$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));
		$B2cBase = new B2cBase();
		$where = !empty($_GET['wrt_id']) ? sprintf(" and wrt_id=%d", $_GET['wrt_id']) : sprintf(" and wrt_wxid='%s'", LibFc::Escape($this->orgArr['Wxid']));
		$res = $B2cBase->get('wx_robot_token', ['wrt_id', 'wrt_wxid', 'wrt_token_type', 'wrt_token', 'wrt_loginurl', 'wrt_endtime', 'wrt_eywid', 'wrt_loginuuid', 'wer_eyproxy'], $where, true);
		if(empty($res['data']) || strtotime($res['data']['wrt_endtime']) < time()){
			LibFc::logs('机器人token不可用');
			exit;
		}
		$this->tokenInfo = $res['data'];
		if($this->tokenInfo['wrt_token_type'] != 'geapi'){
			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'];
	}

	//获取登陆二维码 wechatEy/restart?wrt_id=xxx
	public function restart()
	{
		//强制下线之前的
		if(!empty($this->eywid)){
			$res = $this->getWxApi('login/logout', []);
			/*if($res['ret'] != 200){
				LibFc::ReturnJson(false, '下线失败'.json_encode($res, JSON_UNESCAPED_UNICODE));
			}*/
		}
		for($i = 1; $i < 20; $i++){
			$tpost = [
				"regionId"=>$this->tokenInfo['wer_eyproxy']? $this->tokenInfo['wer_eyproxy']: '440000'
			];
			if($this->tokenInfo['wrt_eywid']) $tpost["appId"] = $this->tokenInfo['wrt_eywid'];
			$this->eywid = '';
			$res = $this->getWxApi('login/getLoginQrCode', $tpost);
			LibFc::logs($this->tokenInfo['wrt_id'].'重启=>'.$i.'=>'.json_encode($res, JSON_UNESCAPED_UNICODE));
			if(stripos($res['data']['msg'], '设备不存在')){
				$this->tokenInfo['wrt_eywid'] = '';
				$B2cBase = new B2cBase();
				$B2cBase->set('wx_robot_token', ['wrt_eywid'=>''], sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']));
				continue;
			}
			if(!empty($res['data']['appId'])){
				$B2cBase = new B2cBase();
				$set = [
					'wrt_eywid'=>$res['data']['appId'],
					'wrt_loginurl'=>$res['data']['qrData'],
					'wrt_loginuuid'=>$res['data']['uuid'],
					'wrt_loginurl_time'=>time(),
					'wrt_verify'=>1,
					'wrt_verifycode'=>'',
					'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/wechatGe/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));
	}
	
	
	//检测登陆状态 wechatEy/checkLogin?wrt_id=xxx
	public function checkLogin()
	{
		set_time_limit(0);
		$max = $_GET['count']? (int) $_GET['count']: 1;
		for($i = 1; $i <= $max; $i++){
			$post = ['uuid'=>$this->tokenInfo['wrt_loginuuid']];
			if($this->tokenInfo['wrt_verify'] == 1 && $this->tokenInfo['wrt_verifycode']){
				$post['captchCode'] = $this->tokenInfo['wrt_verifycode'];
			}
			$res = $this->getWxApi('login/checkLogin', $post);
			LibFc::logs($_GET['wrt_id'].':检测'.$i.'=>'.json_encode($res, JSON_UNESCAPED_UNICODE));
			if(!empty($res['data']['loginInfo'])){
				$info = $res['data']['loginInfo'];
				$wxInfo = [
					'wxid'=>$info['wxid'],
					'nickName'=>$info['nickName'],
					'mobile'=>$info['mobile'],
					'weixin'=>$info['alias'],
					'avatar'=>$res['data']['headImgUrl'],
				];

				//登陆成功
				$B2cBase = new B2cBase();
				$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_loginurl'=>'',
					'wrt_loginuuid'=>'',
					'wrt_verify'=>-1,
					'wrt_verifycode'=>'',
					'wrt_loginurl_time'=>0
				];
				$B2cBase->set('wx_robot_token', $set, sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']));
				//初始化通讯录列表
				$this->getWxApi('contacts/getPhoneAddressList', []);
				//设置回调地址
				$this->getWxApi('login/setCallback', ['callbackUrl'=>mvc::$cfg['GEBOT']['callback'].'?wrt_id='.$this->tokenInfo['wrt_id'], 'token'=>$this->tokenInfo['wrt_token']]);
				LibFc::ReturnJson(true);
			}else if(stripos($res['message'], '验证码')){
				$B2cBase = new B2cBase();
				$B2cBase->set('wx_robot_token', ['wrt_verify'=>1], sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']));
			}else if(stripos($res['message'], '重新登录')){
				break;
			}
			if($max > 1) sleep(5);
		}
		LibFc::ReturnJson(false, '获取登陆状态失败'.json_encode($res, JSON_UNESCAPED_UNICODE));
	}

	
	//检测机器人状态
	function chkRobot()
	{
		$res = $this->getWxApi('login/checkOnline', []);
		if($res['ret'] == 200 && isset($res['data'])){
			$B2cBase = new B2cBase();
			if($res['data']){
				$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 ('eyapi','geapi')", $this->tokenInfo['wrt_eywid']));
				$url = mvc::$cfg['GEBOT']['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, $data){
		$url = mvc::$cfg['GEBOT']['api'].$path;
		if(!empty($this->eywid)) $data['appId'] = $this->eywid;
		$headers = ['X-GEWE-TOKEN: '.$this->tokenInfo['wrt_token'],'Content-Type: application/json'];
		if(is_array($data)) $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);// 检查证书中是否设置域名
        }
		$response = curl_exec($ch);
		curl_close($ch);
		//echo $url.'=>'.$data.'=>'.$response;
		$response = json_decode($response ,true);
		return $response;
	}
}