<?php
/**
  * @class E云微信机器人
  * @author soul 2022/5/27
  */
class wechatEyAction
{
	private $orgArr = [];
	private $postArr = [];
	public $btime = 0;
	public $eywid = '';
	public $tokenInfo = [];
	public $OthWechat = null;

	public function __construct()
	{
		$this->btime = microtime(true);
		$postStr = file_get_contents('php://input');
		$this->orgArr = json_decode($postStr, true);
		//LibFc::logs($_GET['wrt_id'].':'.$this->orgArr['wcId'].'=>'.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['wcId']));
		$res = $B2cBase->get('wx_robot_token', ['wrt_id', 'wrt_wxid', 'wrt_token_type','wrt_token', 'wrt_loginurl', 'wrt_endtime', 'wrt_eywid', 'wer_eyproxy', 'wer_aid', 'wrt_verify', 'wrt_verifycode', 'wrt_device', 'wrt_autocheck', 'wrt_comname','wrt_login_first'], $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'] != 'eyapi'){
			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'];
		$this->OthWechat = new OthWechatEy();
		$this->OthWechat->eywid = $this->eywid;
	}

	//获取登陆二维码 wechatEy/restart?wrt_id=xxx
	public function restart()
	{
		//强制下线之前的
		if(!empty($this->tokenInfo['wrt_wxid'])){
			$res = $this->OthWechat->getWxApi('member/offline', ['account'=>mvc::$cfg['EYBOT']['account'], 'wcIds'=>[$this->tokenInfo['wrt_wxid']]]);
			if($res['code'] != 1000){
				LibFc::ReturnJson(false, '下线失败'.json_encode($res, JSON_UNESCAPED_UNICODE));
			}
		}
		for($i = 1; $i < 20; $i++){
			$tpost = [
				'wcId'=>$this->tokenInfo['wrt_wxid']? $this->tokenInfo['wrt_wxid']: '',
				"proxy"=>$this->tokenInfo['wer_eyproxy']? $this->tokenInfo['wer_eyproxy']: 16
			];
			if($this->tokenInfo['wer_aid']) $tpost['aid'] = $this->tokenInfo['wer_aid'];
			if($this->tokenInfo['wrt_device']) $tpost['deviceType'] = $this->tokenInfo['wrt_device'];
			$this->OthWechat->eywid = '';
			$res = $this->OthWechat->getWxApi('iPadLogin', $tpost);
			LibFc::logs($this->tokenInfo['wrt_id'].'重启=>'.$i.'=>'.json_encode(['post'=>$tpost, 'result'=>$res], JSON_UNESCAPED_UNICODE));
			
			if(!empty($res['data']['wId'])){
				$B2cBase = new B2cBase();
				$set = [
					'wrt_eywid'=>$res['data']['wId'],
					'wrt_loginurl'=>$res['data']['qrCodeUrl'],
					'wrt_loginurl_time'=>time(),
					'wrt_verify'=>0,
					'wrt_verifycode'=>'',
					'wrt_chknew'=>'',
					'wrt_addrinit'=>0,
					'wrt_loginstatus'=>-1,
					'wrt_sleeptime' => date('Y-m-d H:i:s', time() - 24*3600)
				];
				$this->OthWechat->eywid = $set['wrt_eywid'];
				$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/wechatEy/checkLogin?count=100&wrt_id='.$this->tokenInfo['wrt_id'];
				$html = $http->fetch($url);
				LibFc::logs($url.$html);
				LibFc::ReturnJson(true, '');
			}
			sleep(5);
		}
		LibFc::ReturnJson(false, '请点击微信上方的MAC或者IPAD进行“退出登录”操作，再点击“重启”。'.json_encode($res, JSON_UNESCAPED_UNICODE));
	}
	
	
	//检测登陆状态 wechatEy/checkLogin?wrt_id=xxx
	public function checkLogin()
	{
		set_time_limit(0);
		$B2cBase = new B2cBase();
		$max = $_GET['count']? (int) $_GET['count']: 1;
		if($max > 10) sleep(10);
		for($i = 1; $i <= $max; $i++){
			$post = ['wId'=>$this->tokenInfo['wrt_eywid'], 'autoCheck'=>$this->tokenInfo['wrt_autocheck']? true: false];
			$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']){
				$post['verifyCode'] = $res['data']['wrt_verifycode'];
			}
			$res = $this->OthWechat->getWxApi('getIPadLoginInfo', $post);
			LibFc::logs($_GET['wrt_id'].':检测'.$i.'=>'.json_encode($res, JSON_UNESCAPED_UNICODE));
			if(!empty($res['data']['wId'])){
				//登陆成功
				$info = $res['data'];
				$wxInfo = [
					'wxid'=>$info['wcId'],
					'nickName'=>$info['nickName'],
					'mobile'=>$info['mobilePhone'],
					'weixin'=>$info['wAccount'],
					'avatar'=>$info['headUrl'],
				];
				$now = time();
				$set = [
					'wrt_eywid'=>$res['data']['wId'],
					'wrt_wxid'=>$res['data']['wcId'],
					'wrt_sleeptime'=>date('Y-m-d H:i:s', $now + 24*3600),
					'wrt_wxinfo'=>json_encode($wxInfo, JSON_UNESCAPED_UNICODE),
					'wrt_wxinfoorg'=>json_encode($info, JSON_UNESCAPED_UNICODE),
					'wrt_loginurl'=>'',
					'wrt_verify'=>-1,
					'wrt_verifycode'=>'',
					'wrt_loginurl_time'=>0,
					'wrt_chknew'=>'',
					'wrt_loginstatus'=>1,
					'wrt_login_last'=>$now
				];
				if($this->tokenInfo['wrt_wxid'] != $set['wrt_wxid']){
					$set['wrt_login_first'] = $now;
					if($this->tokenInfo['wrt_comname'] == '宜配CRM') $set['wrt_sleeptime'] = date('Y-m-d H:i:s', $now + 24*3600*2);
				}
				$B2cBase->set('wx_robot_token', $set, sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']));
				//设置回调地址
				$this->OthWechat->getWxApi('setHttpCallbackUrl', ['httpUrl'=>mvc::$cfg['EYBOT']['callback'], 'type'=>2]);
				LibFc::ReturnJson(true);
			}else if(!empty($res['data']['url'])){
				$B2cBase->set('wx_robot_token', ['wrt_loginurl'=>'', 'wrt_chknew'=>$res['data']['url']], sprintf(" and wrt_id=%d", $this->tokenInfo['wrt_id']));
			}else if(stripos($res['message'], '验证码')){
				$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(true, '获取登陆状态失败'.json_encode($res, JSON_UNESCAPED_UNICODE));
	}

	
	//检测所有机器人状态
	function chkRobot()
	{
		$res = $this->OthWechat->getWxApi('isOnline', ['wId'=>$this->tokenInfo['wrt_eywid']]);
		if(isset($res['data']['isOnline'])){
			$B2cBase = new B2cBase();
			if($res['data']['isOnline']){
				if(empty($this->tokenInfo['wrt_eywid']) || empty($this->tokenInfo['wrt_wxid'])){
					$_GET['count'] = 1;
					$this->checkLogin();
				}else{
					$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, 'wrt_sleeptime'=>'#@NULL'], sprintf(" and wrt_eywid='%s' AND wrt_token_type IN ('eyapi','geapi')", $this->tokenInfo['wrt_eywid']));
				$url = mvc::$cfg['EYBOT']['handlebase'].'restart?wrt_id='.$this->tokenInfo['wrt_id'].'&type='.$this->tokenInfo['wrt_token_type'];
				$LibHttp = new LibHttp();
				$LibHttp->fetch($url);
			}
		}
		echo 'ok';
	}
}