<?php
class robotAction
{   
	public $HEAD_CSSJS = ['css'=>[],'js'=>[],'plugin'=>[]];
    /**
     * @method 检测机器人登录
     * @author zhengweihua 
     * @copyright 2026-05-21
     */
    public function robotInfo()
    {	

        $params = mvc::$URL_PARAMS;
		if(!$params['id']) LibTpl::Error('参数错误');
		//获取机器人token信息
		$tokenArr = $this->getRobotExist($params['id']);
		if(!$tokenArr) LibTpl::Error('机器人不存在');

		if($tokenArr['wrt_id'])
        {
            $LibYpApi = new LibYpApi();
            $LibYpApi->Get('index/chkRobotStatus',['wrt_id'=>$tokenArr['wrt_id']]);
        }
		$tokenArr['wrt_wxinfo'] =$tokenArr['wrt_wxinfo']? json_decode($tokenArr['wrt_wxinfo'], true):[];
		$provinceArr = mvc::$cfg['ROBOT_CONFIG']['proxy'][$tokenArr['wrt_token_type']]?:[];
		$this->HEAD_CSSJS['plugin'][] = 'layui';
		LibTpl::Set('provinceArr',$provinceArr);
		LibTpl::Set('tokenArr',$tokenArr);
		LibTpl::Set('HEAD_CSSJS',$this->HEAD_CSSJS);
		LibTpl::Set('title', '机器人');
		LibTpl::Set('params',$params);
		LibTpl::Put();
    }

	public function saveTokenInfo()
	{
		if($_SERVER['REQUEST_METHOD']=='POST'){
			$id = isset($_POST['id']) ? $_POST['id'] : '';
			if(!$id) {
				LibFc::ReturnJson(false, '参数错误：ID缺失');
			}
			
			$tokenArr = $this->getRobotExist($id);
			if(!$tokenArr) LibFc::ReturnJson(false,'该机器人不存在！');

			// 获取POST数据
			$wer_aid = isset($_POST['wer_aid']) ? trim($_POST['wer_aid']) : '';
			$wrt_device = isset($_POST['wrt_device']) ? trim($_POST['wrt_device']) : '';
			$wer_eyproxy = isset($_POST['wer_eyproxy']) ? trim($_POST['wer_eyproxy']) : '';
			$wrt_sleeptime = isset($_POST['wrt_sleeptime']) ? trim($_POST['wrt_sleeptime']) : '';
			$wrt_autocheck = isset($_POST['wrt_autocheck'])?$_POST['wrt_autocheck']:0;
	
			$updata = [
				'wer_aid' => $wer_aid,
				'wrt_device' => $wrt_device,
				'wer_eyproxy' => $wer_eyproxy,
				'wrt_sleeptime' => $wrt_sleeptime ?: '#@NULL',
				'wrt_autocheck' => $wrt_autocheck ?: 0
			];
			
			$B2cWxRobot = new B2cWxRobot();
			$res = $B2cWxRobot->set('wx_robot_token', $updata, sprintf(" AND `wrt_id` = %d", $tokenArr['wrt_id']));
			
			if($res) {
				LibFc::ReturnJson(true, '保存成功');
			} else {
				LibFc::ReturnJson(false, '保存失败');
			}
		} else {
			LibFc::ReturnJson(false, '请求方法错误');
		}
	}

	/**
	 * @param  string $id
	 * @method 获取机器人信息
	 * @author zhengweihua 
	 * @copyright 2026-05-22
	 */
	private function getRobotExist($id)
	{	
		$B2cWxRobot = new B2cWxRobot();
		$today = date('Y-m-d');
		$sql = "SELECT * FROM `wx_robot_token` WHERE MD5(CONCAT('Y@', `wrt_id`, '@P', '{$today}')) = '{$id}' LIMIT 1";
        $tokenArr = $B2cWxRobot->B2CDb->Row($sql);
		return $tokenArr;
	}

    /**
     * @method 登录机器人
     * @author zhengweihua 
     * @copyright 2026-05-21
     */
    public function restartRobot()
	{
		$Params= mvc::$URL_PARAMS;
		if(!$Params['id']) return LibFc::ReturnJson(false,'参数错误');
		$id = $Params['id'];
		$tokenArr = $this->getRobotExist($id);
		if($tokenArr['wrt_id'])
		{
			$LibYpApi = new LibYpApi();
			$res = $LibYpApi->Get('index/restartRobot',['wrt_id'=>$tokenArr['wrt_id']]);
			$return = json_decode($res['data'],true);
			if(is_array($return)){
				LibFc::ReturnJson($return['status']);
			}else{
				LibFc::ajaxJsonEncode($res);
			}
		}
		LibFc::ReturnJson(true);
		
	}

	public function checkRebots()
	{
		$Params= mvc::$URL_PARAMS;
		$id = $Params['id'];
		//二维码
		$forwardEwm = $Params['forwardEwm'];
		$data = [];
		if($id){
			$tokenArr = $this->getRobotExist($id);
			
			if($tokenArr)
			{
				
				//检测验证码,0不需要，1需要
				$data['verify'] = 0;
				if ($tokenArr['wrt_verify'] == 1 && $tokenArr['wrt_verifycode'] == '') {
					$data['verify'] = 1;
				}
				//检测登录二维码
				$data['showewm']=0;
				if(!empty($tokenArr['wrt_loginurl'])){
					$data['showewm'] = 1;
					$data['wrt_wxnickname'] = $tokenArr['wrt_wxnickname'];
					$data['loginurl'] = $tokenArr['wrt_loginurl'];
					if ($forwardEwm && $forwardEwm == $tokenArr['wrt_loginurl']) {
					} else {
						if(in_array($tokenArr['wrt_token_type'],mvc::$cfg['ROBOT_CONFIG']['nobase64'])){
							$data['ewmurl'] = $data['loginurl'];
						}else{
							$OthQrcode = new OthQrcode();
							$ewmurl = $OthQrcode->png($data['loginurl']);
							$data['ewmurl'] = $ewmurl;
						}
					}
				}
				
				$data['chknew'] = 0;
				if($tokenArr['wrt_chknew']){
					$data['chknew'] = 1;
					$data['chknewurl'] = $tokenArr['wrt_chknew'];
					$data['showewm']=0;
				}

				//检测显示重启按钮
				$data['showrestart']=0;
				if(time()-$tokenArr['wrt_restart_last']>120){
					$data['showrestart']=1;
				}
				
			}
			
			return LibFc::ReturnJson(true,$data);
		}
	}

	public function setVerifycode()
	{
		if($_SERVER['REQUEST_METHOD']=='POST'&&$_POST['id'])
		{
			$tokenArr = $this->getRobotExist($_POST['id']);
			if(!empty($tokenArr['wrt_id'])&&!empty($_POST['verifycode'])){
				$verifycode  = $_POST['verifycode'];
				$wrt_id = $tokenArr['wrt_id'];
				//更新
				$B2cWxRobot = new B2cWxRobot();
				$res = $B2cWxRobot->set('wx_robot_token',['wrt_verifycode'=>$verifycode],sprintf(" AND wrt_id=%d",$wrt_id));

				$http = new LibHttp(false,false);
				$http->timeout = 2;
				$http->fetch('http://hub.paojd.cn:75/wechatEy/checkLogin?wrt_id='.$wrt_id);
				LibFc::ajaxJsonEncode($res);
			}
		}
	}

	/**
	 * @method 获取机器人状态
	 * @author zhengweihua 
	 * @copyright 2026-05-26
	 */
	public function getRobotStatus()
	{
		$params= mvc::$URL_PARAMS;
		$tokenArr = $this->getRobotExist($params['id']);
		if(!$tokenArr) return [];

		/*if($tokenArr['wrt_id'])
        {
            $LibYpApi = new LibYpApi();
            $LibYpApi->Get('index/chkRobotStatus',['wrt_id'=>$tokenArr['wrt_id']]);
        }*/
		$B2cWxRobot = new B2cWxRobot();
		$res = $B2cWxRobot->get('wx_robot_token',['wrt_id','wrt_loginstatus','wrt_sleeptime'],sprintf(" AND wrt_id=%d",$tokenArr['wrt_id']),true);
		LibFc::ajaxJsonEncode($res);	
	}

	/** 
	 * @method 设置微信token为null
	 * @author zhengweihua 
	 * @copyright 2026-05-27
	 */
	public function setWxTokenNull()
	{
		if($_SERVER['REQUEST_METHOD']=='POST'&&$_POST['id'])
		{
			$tokenArr = $this->getRobotExist($_POST['id']);
			if(!empty($tokenArr['wrt_id'])){
				$wrt_id = $tokenArr['wrt_id'];
				//更新
				$B2cWxRobot = new B2cWxRobot();

				$B2cWxRobot->set('wx_robot_token',['wrt_wxid'=>'','wrt_wxinfo'=>'#@NULL'],sprintf(" and wrt_ispjd =0 AND wrt_id=%d", $wrt_id));
				
				LibFc::ReturnJson(true,'操作成功');
			}
		}
	}
}