<?php
/**
  * @class 微信机器人
  * @author soul 2022/5/27
  */
class wechatAction extends baseAction
{
	private $wcof = [];
	private $B2cBase = null;
	private $postArr = [];
	private $isMorePro = 0;
	private $urlArr = [];
	private $wordtype = '';

	public function __construct()
	{
		parent::__construct();
		LibFc::useMainDb();
		$this->B2cBase = new B2cBase();
		$this->postArr = $_POST;
		//LibLog::write(json_encode($this->postArr, JSON_PARTIAL_OUTPUT_ON_ERROR));
	}

	public function getCfg()
	{
		$arr = [];
		$res = $this->B2cBase->get('wx_robot_token', ['wrt_id, wrt_type, wrt_wxnum, wrt_wxnickname, wrt_token,wrt_sleeptime,wrt_status'], sprintf(" and wrt_id=%d limit 1", $this->postArr['wrt_id']), true);
		if(!empty($res['data']))
		{
			$arr = $res['data'];
			$res = $this->B2cBase->get('wx_robot_token', ['wrt_wxid'], ' and wrt_wxid !=""');
			$arr['robotIds'] = array_column($res['data'], 'wrt_wxid');
		}
		LibFc::ReturnJson(true, $arr);
	}

	public function initBotCof()
	{
		if(!empty($this->postArr['talkerId'])){
			$res = $this->B2cBase->get('wx_robot_token', ['wrt_wxid'], sprintf(" and wrt_wxid ='%s' and wrt_comname !='宜配CRM'", LibFc::Escape($this->postArr['talkerId'])));
			if(!empty($res['data'])) LibFc::ReturnJson(true, ['saymsg'=>'']);
		}

		$res = $this->B2cBase->get('wx_robot_token', ['wrt_id, wrt_type, wrt_wxnum, wrt_wxnickname, wrt_token,wrt_sleeptime,wrt_status,wrt_comname'], sprintf(" and wrt_id=%d limit 1", $this->postArr['wrt_id']), true);
		$tokenInfo = $res['data'];

		//是否需要休眠
		if(stripos($this->tokenInfo['wrt_comname'], 'CRM') !== false || (!empty($tokenInfo['wrt_sleeptime']) && strtotime($tokenInfo['wrt_sleeptime']) > time())){
			LibFc::ReturnJson(true, ['saymsg'=>'']);
		}
		$now = time();
		$where = sprintf(" and wr_status = 1 and wr_btime <= %d and wr_etime >= %d", $now, $now);
		$fileds = ['ro.*, ssu_id, ssu_super_gzh'];
		if(empty($this->postArr['wrt_id']) && !empty($this->postArr['wr_wxnum']))
		{//微信公众号
			$this->wcof['talkfrom'] = 'wxgzh';
			$table = "wx_robot ro left join sh_super on wr_uid=ssu_shop_id and ssu_style='B2C'";
			$where .= sprintf(" and wr_type not in ('wxgr') and wr_wxnum='%s'", LibFc::Escape($this->postArr['wr_wxnum']));
		}else if(!empty($this->postArr['corpid']) && !empty($this->postArr['wr_id']))
		{//微信客服 wxkf
			$this->wcof['talkfrom'] = 'wxkf';
			$table = "wx_robot ro join wx_robot_token on wrt_id=wr_wrt_id left join sh_super on wr_uid=ssu_shop_id and ssu_style='B2C'";
			$where .= sprintf(" and wr_type in ('wxkf', 'wxgr') and wr_id=%d and wrt_wxid='%s'", $this->postArr['wr_id'], LibFc::Escape($this->postArr['corpid']));
		}
		else if(!empty($this->postArr['roomId']))
		{//群聊
			$this->wcof['talkfrom'] = 'room';
			$table = "wx_robot ro join wx_robot_room ON wrr_wr_id = wr_id left join sh_super on wr_uid=ssu_shop_id and ssu_style='B2C'";
			$where .= sprintf(" and wr_wrt_id=%d and wr_type in ('wxgr') and wrr_room_id='%s'", $this->postArr['wrt_id'], LibFc::Escape($this->postArr['roomId']));
			$fileds = ['ro.*, ssu_id, ssu_super_gzh,wrr_room_id,wrr_mel_id,wrr_hideurl,wrr_status,wrr_factory,wrr_part_ids,wrr_prb_ids,wrr_sort_ids'];
		}
		else
		{//私聊
			$this->wcof['talkfrom'] = 'wxsl';
			$table = "wx_robot ro join wx_robot_wx ON wrw_wr_id = wr_id left join sh_super on wr_uid=ssu_shop_id and ssu_style='B2C'";
			$where .= sprintf(" and wr_wrt_id=%d and wr_type in ('wxgr') and wrw_wx_id='%s'", $this->postArr['wrt_id'], LibFc::Escape($this->postArr['talkerId']));
		}
		$res = $this->B2cBase->get($table, $fileds, $where.' limit 1', true);
		if(empty($res['data']))
		{
			if($this->wcof['talkfrom'] == 'room'){
				LibFc::ReturnJson(true, ['act'=>'check']);
			}else if($this->wcof['talkfrom'] == 'wxsl'){
				LibFc::ReturnJson(true, ['saymsg'=>'您尚未开通本机器人服务，开通后再向我发送“修复”二字。']);
			}else if($this->wcof['talkfrom'] == 'wxgzh'){
				LibFc::ReturnJson(true, ['saymsg'=>'您尚未开通微信公众号机器人服务。']);
			}else if($this->wcof['talkfrom'] == 'wxkf'){
				LibFc::ReturnJson(true, ['saymsg'=>'您尚未开通微信客服机器人服务。']);
			}
		}
		$this->wcof = array_merge($this->wcof, $res['data']);

		//群被停用，静默
		if(isset($this->wcof['wrr_status']) && $this->wcof['wrr_status'] != 1) LibFc::ReturnJson(true, ['act'=>'']);

		$this->wcof['wr_autotxt'] = json_decode($this->wcof['wr_autotxt'], true);
		$this->wcof['wr_othdata'] = empty($this->wcof['wr_othdata'])? []:json_decode($this->wcof['wr_othdata'], true);
		$this->wcof['host'] = '';
		$this->wcof['wr_selfmod'] = explode(',', $this->wcof['wr_selfmod']);
		$this->wcof['wr_vin_fileds'] = explode(',', $this->wcof['wr_vin_fileds']);
		$this->wcof['wr_othcof'] = explode(',', $this->wcof['wr_othcof']);
		switch($this->wcof['wr_totype'])
		{
			case 'super':
				//开通了公众号目录的
				if($this->wcof['ssu_super_gzh']){
					$this->wcof['host'] = mvc::$cfg['HOST']['super'].$this->wcof['wr_uid'].'/index.php/';
				}else{
					$this->wcof['wr_totype'] = 'superpjl';
					$this->wcof['host'] = 'https://pjl.paojd.cn/s/';
				}
			break;
			case 'gzh':
				$this->wcof['host'] = mvc::$cfg['HOST']['gzh'].$this->wcof['wr_uid'].'/index.php/';
			break;
			case 'yiparts':
			case 'vin':
				$this->wcof['host'] = 'https://pjl.paojd.cn/s/';
			break;
			case 'customize': 
				$this->wcof['wr_cuscof'] = json_decode($this->wcof['wr_cuscof'], true);
			break;
			case 'crm':
				LibFc::ReturnJson(true, ['saymsg'=>'']);
				break;
		}
		if(empty($this->wcof['wr_autotxt'])) $this->wcof['wr_autotxt'] = [];
		if(empty($this->wcof['wr_autotxt']['subscribe'])) $this->wcof['wr_autotxt']['subscribe'] = '欢迎关注'.$this->wcof['wr_wxname'].'，您现在可以给我发送车架号图片、车架号、号码自助查询哦！';
		if(empty($this->wcof['wr_autotxt']['nores'])) $this->wcof['wr_autotxt']['nores'] = '在线【<a href="'.$this->wcof['host'].'">品牌目录</a>】查询系统';
	}

	/**
	  * @method 微信群聊机器人 消息
	  * @http  post
	  * @author soul 
	  * @copyright 2022/7/4
	  * @return {"status":true,"data":{"saymsg":"车架号【LC0CG4CG7F0004330】\r\n品牌: 比亚迪\r\n车系: M6\r\n车型: 2.4L\r\n制造日期: 2015-03\r\n发动机:
BYD488QA\r\n功率: 123kw\r\n排量: 2362cc\r\n变速箱: 6DCT\r\n驱动: 前置前驱\r\n车身: 5门7座MPV\r\n燃油: 汽油\r\n前\/后制动器: 通风盘式\/盘式\r\n驻车制动:
手刹\r\n尺寸: 4820mm*1810mm*1765mm\r\n轴距: 2960mm\r\n车辆类型: 乘用车\r\n整备质量: 1790kg\r\n载客:
7人\r\n查配件>>https:\/\/gzh.paojd.cn\/369676\/index.php\/item\/search?type=model&mod3_id=2366&vin=LC0CG4CG7F0004330\r\n"},"code":0,"runtime":735}
	  */
	public function msg()
	{
		$content = '';
		$keyword = '';
		$orgmsg = '';
		$this->initBotCof();
		if($this->postArr['type'] == 'notice' && $this->postArr['wrn_id'] > 0)
		{
			sleep(1);
			$res = $this->B2cBase->get('wx_robot_notice', ['*'], sprintf(" and wrn_status=0 and wrn_wrt_id=%d and wrn_id=%d", $this->postArr['wrt_id'], $this->postArr['wrn_id']), true);
			if(empty($res['data'])) LibFc::ReturnJson(true, ['saymsg'=>'']);
			$noticeArr = $res['data'];
			$noticeArr['wrn_info'] = json_decode($noticeArr['wrn_info'], true);
			$this->B2cBase->set('wx_robot_notice', ['wrn_status'=>1,'wrn_stime'=>time()], sprintf(" and wrn_id=%d", $this->postArr['wrn_id']));
			switch($noticeArr['wrn_info']['act'])
			{
				case 'jiucuo':
					if($noticeArr['wrn_info']['ve_status'] == -1){
						LibFc::ReturnJson(true, ['saymsg'=>'您好，车架号【'.$noticeArr['wrn_info']['vin'].'】纠错无效。'.$noticeArr['wrn_info']['saymsg']]);
					}else{
						$content .= "\r\n纠错处理完成".($noticeArr['wrn_info']['saymsg']? '【'.$noticeArr['wrn_info']['saymsg'].'】': '')."，以下是最新的解码结果。\r\n";
						$vin = $noticeArr['wrn_info']['vin'];
					}
				break;
				case 'saymsg': 
					LibFc::ReturnJson(true, ['saymsg'=>$noticeArr['wrn_info']['saymsg']]);
				break;
				default: 
					LibFc::ReturnJson(true, ['saymsg'=>'']);
				break;
			}
			exit;
		}
		else if(!empty($this->postArr['image']) || !empty($this->postArr['imgurl']))
		{
			if(empty($this->postArr['image']) && !empty($this->postArr['imgurl'])){
				$LibHttp = new LibHttp();
				$this->postArr['image'] = base64_encode($LibHttp->fetch($this->postArr['imgurl']));
			}
			$MainOcr = new MainOcr();
			$res = $MainOcr->vin($this->postArr['image']);
			if(strlen($res['data']) == 17){
				$vin = $res['data'];
				$orgmsg = $vin;
			}
		}
		else
		{
			$orgmsg = $this->postArr['text'];

			//消息中转不需要处理
			if(!in_array('toselfmsg', $this->wcof['wr_selfmod'])){
				$keyword = LibFc::filterEmoji($this->postArr['text']);
				//忽略网址、小程序
				if(preg_match('/https?\:\/\/.{4,}/i', $keyword, $imatch) || stripos($keyword, 'weixin://') !== false)
					LibFc::ReturnJson(true, ['saymsg'=>'']);

				//ASCII 194
				$keyword = strtr($keyword, [' '=>' ']);

				//遇到忽略的关键字，直接不处理
				if(!empty($this->wcof['wr_ignoretxt']))
				{
					if(stripos(str_ireplace(explode(',', $this->wcof['wr_ignoretxt']), '#忽略#', $keyword), '#忽略#') !== false)
					{
						LibFc::ReturnJson(true, ['saymsg'=>'']);
					}
				}
				$formatNum = LibFc::FormatNum($keyword);
				if(preg_match('/[0-9a-zA-Z]{17}/i', $keyword, $match)){
					$vin = LibFc::FormatNum($match[0]);
				}else if(strlen($formatNum) == 17){
					$vin = $formatNum;
				}
				//忽略不含车架号长度超过100
				if(empty($vin) && LibFc::slen($keyword) > 100) LibFc::ReturnJson(true, ['saymsg'=>'']);
			}
		}
		
		$this->postArr['roomId'] = $this->postArr['roomId']? $this->postArr['roomId']: '';
		$userkey = $this->postArr['talkerId'];
		if(!empty($this->postArr['roomId'])) $userkey .= ':'.$this->postArr['roomId'];
		
		//消息中转
		if(in_array('toselfmsg', $this->wcof['wr_selfmod'])){
			$toCusApiData = [
				'keyword'=>$orgmsg,
				'room_id'=>$this->postArr['roomId'],
				'talker_id'=>$this->postArr['talkerId']
			];
			$resArr = $this->getSelfApiUrl($toCusApiData, 'msg');
			if(isset($resArr['saymsg'])) $content = $resArr['saymsg'];
			LibFc::ReturnJson(true, ['saymsg'=>$content]);
		}

		if($vin) $this->wordtype = 'vin';

		if(!$vin && $this->wcof['talkfrom'] == 'wxgzh')
		{//微信公众号 非车架号关键字回复
			$B2cBase = new B2cBase();
			$table = 'wx_robot_auto JOIN wx_robot_autoword ON waw_wra_id = wra_id JOIN wx_robot ON wr_id = wra_wr_id';
			$where = sprintf(" and wr_uid=%d AND wr_totype='%s' AND ((waw_style = 0 AND waw_word = '%s') OR (waw_style = 1 AND waw_word LIKE '%%%s%%')) LIMIT 1", 
				$this->wcof['wr_uid'], $this->wcof['wr_totype'], LibFc::Escape($keyword), LibFc::Escape($keyword));
			$res = $B2cBase->get($table, ['wra_answer'], $where, true);
			if(!empty($res['data'])) LibFc::ReturnJson(true, ['saymsg'=>$res['data']['wra_answer']]);
		}
		
		if(in_array('bmtsr', $this->wcof['wr_selfmod']))
		{//贝偲特定制
			$toCusApiData = [
				'text'=>$keyword,
				'talkerId'=>$this->postArr['talkerId'],
				'roomId'=>$this->postArr['roomId']
			];
			if($vin)
			{
				$OthCom = new OthCom();
				$res = $OthCom->decodeVinBmtsr($vin);
				$modArr = $res['data'];
				$toCusApiData['vindecode'] = $modArr;
				if(!empty($modArr['mch_code']))
				{
					$MainZyb = new MainZyb();
					$hisArr = [
						'ash_uid'=>$this->wcof['wr_uid'],
						'ash_type'=>'vin',
						'ash_act'=>'comBmtsr/decodeVin',
						'ash_val'=>$vin,
						'ash_wxid_by'=>$this->postArr['talkerId'],
						'ash_wx_room'=>$this->postArr['roomId'],
						'ash_ip'=>LibFc::GetClientIp(),
						'ash_from'=>'robot',
					];
					$MainZyb->addHistory($hisArr);
				}
			}
			//推送到接口
			$LibHttp = new LibHttp();
			$html = $LibHttp->fetch($this->wcof['wr_cuscof']['msgapi'], $toCusApiData);
			$result = json_decode($html, true);
			if(is_array($result) && !empty($result['saymsg'])){
				$content = $result['saymsg'];
			}
			LibFc::ReturnJson(true, ['saymsg'=>$content]);
		}

		$B2cSearch = new B2cSearch();
		//车架号纠错
		//if(preg_match('/纠错|错误|出错|解码错|错了|不正确|不对|错的/iU', $keyword))
		if(!preg_match('/回复|链接|若VIN|小程序|车车|查看|有奖|点击/iU', $keyword) && preg_match('/纠错|解码错|解错|车型错|车型不对|发动机错|变速箱错|排量错|排量不对|年份错/iU', $keyword))
		{
			$imagedata = '';
			if(!$vin){
				$res = $B2cSearch->get('wx_robot_vinlast', ['wrv_vin','wrv_image'], sprintf(" and wrv_user='%s' and wrv_etime > %d limit 1", LibFc::Escape($userkey), time()-60), true);
				if(!empty($res['data'])){
					$vin = $res['data']['wrv_vin'];
					$imagedata = $res['data']['wrv_image'];
				}
			}
			if($vin){
				$YpwVin = new YpwVin();
				$res = $YpwVin->addVinJiuCuo($vin, $keyword, $this->postArr['talkerId'], $this->postArr['roomId'], $imagedata, $this->postArr);
				$jcres = $res['data'];
				if($jcres['result'] == 1){
					LibFc::useMainDb();
					$content .= "\r\n纠错已处理完成，以下是最新的解码结果。\r\n";
				}else if($jcres['result'] == 2){
					LibFc::ReturnJson(true, ['saymsg'=>$jcres['msg']]);
				}
			}
		}
		
		if($vin && in_array('jnmd', $this->wcof['wr_selfmod']))
		{
			$vinDesurl = $this->wcof['host'].'item/searchVin?type=vin&keyword='.$vin;
			$content .= ($this->postArr['roomId']? "\r\n":'').'车架号: '.$vin."\r\n★★★点击链接查配件★★★\r\n".$vinDesurl."\r\n";
			$this->urlArr[] = $vinDesurl;
			if(!empty($this->wcof['wr_hasrestxt'])) $content = rtrim($content, "\r\n")."\r\n".$this->wcof['wr_hasrestxt'];
		}
		else if($vin)
		{
			$YpcVin = new YpcVin();
			mvc::$cfg['VINSHOPID'] = $this->wcof['wr_uid'];
			$othcfg = [
				'from'=>'robot',
				'shop_id'=>$this->wcof['wr_uid']
			];
			$res = $YpcVin->decodeVin($vin, '', $othcfg);
			$modArr = $res['data'];
			if(!empty($modArr['model']))
			{
				$mtjArr = ['vin'=>$vin, 'm3ids'=>[], 'roomid'=>$this->postArr['roomId'], 'wxid'=>$this->postArr['talkerId'], 'nickname'=>$this->postArr['talkerNickName']?? ''];
				if($this->wcof['wr_totype'] == 'pjlshop'){
					$res = $this->B2cBase->get('wx_robot_brand', ['wrb_brand_id'], sprintf(" and wrb_wr_id=%d", $this->wcof['wr_id']));
					$limitBrands = array_column($res['data'], 'wrb_brand_id');
					if(!empty($limitBrands) && !in_array($modArr['brand_id'], $limitBrands)) LibFc::ReturnJson(true, ['saymsg'=>'商家尚未开放【'.$modArr['brand_name'].'】车架号解码。']);
				}else{
					$res = $this->B2cBase->get('sh_shop_brand', ['ssb_brand_id'], sprintf(" and ssb_shop_id=%d", $this->wcof['wr_uid']));
					$limitBrands = array_column($res['data'], 'ssb_brand_id');
					if(!empty($limitBrands) && !in_array($modArr['brand_id'], $limitBrands)) LibFc::ReturnJson(true, ['saymsg'=>'目录尚未开放【'.$modArr['brand_name'].'】车架号解码。']);
				}

				$MainZyb = new MainZyb();
				$hisArr = [
					'ash_uid'=>$this->wcof['wr_uid'],
					'ash_type'=>'vin',
					'ash_act'=>'vin/decodeVin',
					'ash_val'=>$vin,
					'ash_wxid_by'=>$this->postArr['talkerId'],
					'ash_wx_room'=>$this->postArr['roomId']?? '',
					'ash_ip'=>LibFc::GetClientIp(),
					'ash_from'=>'robot_'.$this->wcof['wr_totype'],
					'ash_agent'=>$this->wcof['wr_type'],
				];
				$MainZyb->addHistory($hisArr);
				$vinDesurl = '';
				switch($this->wcof['wr_totype'])
				{
					case 'super': 
						$vinDesurl = $this->wcof['host'].'item/searchVin?type=vin&keyword='.$vin;
					break;
					case 'superpjl': 
						$vinDesurl = $this->wcof['host'].'superSearch?type=vin&keyword='.$vin.'&ssu_id='.$this->wcof['ssu_id'].'&shop_id='.$this->wcof['wr_uid'];
					break;
					case 'gzh':
						$vinDesurl = $this->wcof['host'].'item/searchVin?type=vin&keyword='.$vin;
					break;
					case 'yiparts':
					case 'vin':
						$vinDesurl = $this->wcof['host'].'vin?vin='.$vin;
					break;
				}
				
				$m3idsArr = [];
				if($modArr['from'] == 'ypc')
				{
					foreach($modArr['model'] as $mk=>$mod)
					{
						if(!empty($mod['mod3_jgl_kw'])) $mod['mod3_jgl_kw'] = $mod['mod3_jgl_kw'][1];
						if(!empty($mod['mod3_ed_kw'])) $mod['mod3_ed_kw'] = $mod['mod3_ed_kw'][1];
						if(in_array('mod3_year', $this->wcof['wr_vin_fileds'])){
							$mod['mod3_name'] .= ' '.LibFc::formatViewYear($mod['mod3_start_year'], $mod['mod3_end_year'],2);
						}
						$modArr['model'][$mk] = $mod;
					}
					$m3idsArr = array_column($modArr['model'], 'mod3_id');
					$mtjArr['m3ids'] = $m3idsArr;
				}
				$noVinKeyword = trim(str_ireplace($vin, '', $keyword));
				$modCount = count($modArr['model']);
				if(in_array('zjcsurl', $this->wcof['wr_selfmod']) || !in_array('url_vin', $this->wcof['wr_othcof']) || $this->wcof['wrr_hideurl']){//中机昌盛，或者隐藏链接
					$content .= ($this->postArr['roomId']? "\r\n":'').'车架号: '.$vin."\r\n";
				}else{
					if(in_array('apigeturl', $this->wcof['wr_selfmod'])){
						$selfUrlArr = $this->getSelfApiUrl($vin, 'vin');
						$vinDesurl = !empty($selfUrlArr['url'])? $selfUrlArr['url']: '';
					}else{
						$this->urlArr[] = $vinDesurl;
					}
					$content .= ($this->postArr['roomId']? "\r\n":'').'车架号: '.$vin.($vinDesurl? "   ".$vinDesurl: '')."\r\n";
				}
				
				if($modArr['from'] == 'ypc')
				{
					//自定义链接
					$selfUrlArr = in_array('apigeturl', $this->wcof['wr_selfmod'])? $this->getSelfApiUrl($m3idsArr, 'model') : [];

					//初始化更多数据
					foreach($modArr['model'] as $mk=>$mod)
					{
						if(in_array('apigeturl', $this->wcof['wr_selfmod'])){
							$mod['url'] = !empty($selfUrlArr[$mod['mod3_id']])? $selfUrlArr[$mod['mod3_id']]: '';
						}else{
							switch($this->wcof['wr_totype'])
							{
								case 'super': 
									$mod['url'] = $this->wcof['host'].'item/search?level=item&mod3_id='.$mod['mod3_id'].'&vin='.$vin;
								break;
								case 'superpjl': 
									$mod['url'] = $this->wcof['host'].'superSearch?type=item&level=item&mod3_id='.$mod['mod3_id'].'&vin='.$vin.'&ssu_id='.$this->wcof['ssu_id'].'&shop_id='.$this->wcof['wr_uid'];
								break;
								case 'gzh':
									$mod['url'] = $this->wcof['host'].'item/search?type=model&mod3_id='.$mod['mod3_id'].'&vin='.$vin;
								break;
								case 'yiparts':
									$mod['url'] = $this->wcof['host'].'model?mod3_id='.$mod['mod3_id'].'&vin='.$vin;
								break;
							}
							if($mod['url']) $this->urlArr[] = $mod['url'];
						}
						$modArr['model'][$mk] = $mod;
					}
					$itemArr = null;
					$itemBy = '';
					$wordArr = [];
					//产品列表
					if(in_array($this->wcof['wr_totype'], ['super','superpjl','gzh','pjlshop'])){
						if(!in_array('closevinword', $this->wcof['wr_othcof']) && LibFc::slen(str_replace(' ', '', $noVinKeyword)) > 1){
							$wordArr[] = $noVinKeyword;
						}
						if(!empty($this->wcof['wr_maxitem'])) $wordArr[] = '';
						foreach($wordArr as $tword)
						{
							$itemcount = $this->wcof['wr_maxitem'];
							//有关键字 并且不显示产品的直接显示10个
							if(!empty($tword) && empty($this->wcof['wr_maxitem'])) $itemcount = 10;
							$itemArr = $this->getItems(['type'=>'model', 'mod3_id'=>implode(',', $m3idsArr), 'keyword'=>$tword, 'vinyear'=>$modArr['model'][0]['vin_year']], $itemcount+1);
							if(!empty($itemArr)){
								$itemBy = $tword;
								if(count($itemArr) > $itemcount){
									array_pop($itemArr);
									$this->isMorePro = $itemcount;
								}
								break;
							}
						}
					}

					//无关键字相应配件时隐藏默认产品
					$wordNoItemHideIndex = in_array('wordnoitem_hideindex', $this->wcof['wr_othcof']) && $itemBy == '' && !empty($wordArr[0])? true: false;

					if(in_array('zjcsurl', $this->wcof['wr_selfmod']) && count($itemArr) == 1 && !empty($modArr['model'][0]['url'])){
						foreach($itemArr as $k=>$v){
							$itemArr[$k]['url'] = $modArr['model'][0]['url'];
						}
					}

					if(!in_array('modtpl1', $this->wcof['wr_vin_fileds']) && $modCount == 1)
					{//只有一个车型
						$mod = $modArr['model'][0];
						if(in_array('mer_modname', $this->wcof['wr_vin_fileds'])){
							$content .= "车型:";
							if(!in_array('nobrand', $this->wcof['wr_othcof'])) $content .= " ".$mod['brand_name'].($mod['make_name'] == $mod['brand_name']? '': ' ('.$mod['make_name'].')');
							$content .= " ".$mod['mod2_name'];
							$content .= " ".$mod['mod3_name']."\r\n";
						}else{
							if(!in_array('nobrand', $this->wcof['wr_othcof']))  $content .= "品牌: ".$mod['brand_name'].($mod['make_name'] == $mod['brand_name']? '': ' ('.$mod['make_name'].')')."\r\n";
							$content .= "车系: ".$mod['mod2_name']."\r\n";
							$content .= "车型: ".$mod['mod3_name']."\r\n";
						}
						if(!empty($mod['vin_year'])) $content .= $mod['vin_year_name'].": ".$mod['vin_year']."\r\n";
						if(in_array('mod3_engine', $this->wcof['wr_vin_fileds'])) $content .= "发动机: ".$mod['mod3_engine']."\r\n";
						if(in_array('mod3_kw', $this->wcof['wr_vin_fileds'])){
							if(!empty($mod['mod3_jgl_kw']))
							{
								$content .= "最大净功率: ".$mod['mod3_jgl_kw']."\r\n";
								if(!empty($mod['mod3_ed_kw'])) $content .= "额定功率: ".$mod['mod3_ed_kw']."\r\n";
							}
							else if(!empty($mod['mod3_kw']))
							{
								$content .= "功率: ".$mod['mod3_kw']."kw\r\n";
							}
						}
						if(!empty($mod['mod3_cc']) && in_array('mod3_cc', $this->wcof['wr_vin_fileds']) && !empty($mod['mod3_cc'])) $content .= "排量: ".$mod['mod3_cc']."cc\r\n";
						if(!empty($mod['mod3_transmission']) && in_array('mod3_transmission', $this->wcof['wr_vin_fileds'])) $content .= "变速箱: ".$mod['mod3_transmission']."\r\n";
						if(!empty($mod['mod3_drive']) && in_array('mod3_drive', $this->wcof['wr_vin_fileds'])) $content .= "驱动: ".$mod['mod3_drive']."\r\n";
						if(!empty($mod['mod3_chassis']) && in_array('mod3_chassis', $this->wcof['wr_vin_fileds'])) $content .= "底盘: ".$mod['mod3_chassis']."\r\n";
						if(!empty($mod['mod3_body']) && in_array('mod3_body', $this->wcof['wr_vin_fileds'])) $content .= "车身: ".$mod['mod3_body']."\r\n";
						if(!empty($mod['mod3_fuel']) && in_array('mod3_fuel', $this->wcof['wr_vin_fileds'])) $content .= "燃油: ".$mod['mod3_fuel']."\r\n";
						if((!empty($mod['mod3_front_brake']) || !empty($mod['mod3_rear_brake'])) && in_array('mod3_brake', $this->wcof['wr_vin_fileds'])) $content .= "前/后制动器: ".$mod['mod3_front_brake'].'/'.$mod['mod3_rear_brake']."\r\n";
						if(!empty($mod['mod3_parking_brake']) && in_array('mod3_parking_brake', $this->wcof['wr_vin_fileds'])) $content .= "驻车制动: ".$mod['mod3_parking_brake']."\r\n";
						if(in_array('mod3_start_stop', $this->wcof['wr_vin_fileds']) && !empty($mod['mod3_start_stop'])) $content .= "自动启停: ".$mod['mod3_start_stop']."\r\n";
						if(!empty($mod['param']))
						{
							foreach($mod['param'] as $pv)
							{
								if(in_array('param_'.$pv[2], $this->wcof['wr_vin_fileds'])) $content .= $pv[0].": ".$pv[1]."\r\n";
							}
						}

						if(!in_array('novinjiucuo', $this->wcof['wr_othcof'])) $content .= "★若VIN解码错误，请回复“纠错”★\r\n";
						
						if(!empty($itemArr) || empty($this->wcof['wr_maxitem']))
						{
							if(in_array('novinitemurl', $this->wcof['wr_othcof']) || $this->wcof['wrr_hideurl']){	
							}else if(!empty($mod['url'])){
								//中机昌盛
								if(in_array('zjcsurl', $this->wcof['wr_selfmod'])){
									$content .= "\r\n★★★【点击链接可直接购买商品】★★★\r\n".$mod['url']."\r\n";
								}else{
									if(!$wordNoItemHideIndex){
										$content .= $this->isMorePro? "\r\n★只展示".$this->isMorePro."条，点击链接显示更多产品★\r\n".$mod['url']."\r\n": "\r\n★点击链接查配件★\r\n".$mod['url']."\r\n";
										$this->isMorePro = 0;
									}
								}
							}
						}
					}
					else if(!in_array('modtpl1', $this->wcof['wr_vin_fileds']) && count(array_unique(array_column($modArr['model'], 'mod2_id'))) == 1)
					{//多车型车系一样
						$mergeArr = [];
						$mergeFileds = ['mod3_engine', 'mod3_kw', 'mod3_jgl_kw', 'mod3_ed_kw', 'mod3_cc', 'mod3_transmission', 'mod3_fuel', 'mod3_body', 'mod3_front_brake', 'mod3_rear_brake', 'mod3_parking_brake', 'mod3_drive', 'mod3_start_stop', 'mod3_chassis'];
						foreach($mergeFileds as $mf)
						{
							$mergeArr[$mf] = array_unique(array_column($modArr['model'], $mf));
						}
						if(in_array('mer_modname', $this->wcof['wr_vin_fileds'])){
							$content .= "车系:";
							if(!in_array('nobrand', $this->wcof['wr_othcof']))  
								$content .= ' '.$modArr['model'][0]['brand_name'].($modArr['model'][0]['make_name'] == $modArr['model'][0]['brand_name']? '': ' ('.$modArr['model'][0]['make_name'].')');
							$content .= ' '.$modArr['model'][0]['mod2_name']."\r\n";
						}else{
							if(!in_array('nobrand', $this->wcof['wr_othcof']))
								$content .= "品牌: ".$modArr['model'][0]['brand_name'].($modArr['model'][0]['make_name'] == $modArr['model'][0]['brand_name']? '': ' ('.$modArr['model'][0]['make_name'].')')."\r\n";
							$content .= "车系: ".$modArr['model'][0]['mod2_name']."\r\n";
						}
						foreach($modArr['model'] as $mk=>$mod)
						{
							$content .= "- - - - - 车型".($mk+1)."- - - - -\r\n".$mod['mod3_name'];
							if(in_array('mod3_engine', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_engine']) > 1) $content .= ' '.$mod['mod3_engine'];
							if(in_array('mod3_kw', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_kw']) > 1) $content .= ' '.$mod['mod3_kw'].'kw';
							if(in_array('mod3_cc', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_cc']) > 1 && !empty($mod['mod3_cc'])) $content .= ' '.$mod['mod3_cc'].'cc';
							if(in_array('mod3_transmission', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_transmission']) > 1) $content .= ' '.$mod['mod3_transmission'];
							if(in_array('mod3_drive', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_drive']) > 1) $content .= ' '.$mod['mod3_drive'];
							if(in_array('mod3_chassis', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_chassis']) > 1) $content .= ' '.$mod['mod3_chassis'];
							if(in_array('mod3_fuel', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_fuel']) > 1) $content .= ' '.$mod['mod3_fuel'];
							if(in_array('mod3_body', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_body']) > 1) $content .= ' '.$mod['mod3_body'];
							if(in_array('mod3_brake', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_front_brake']) > 1) $content .= ' 前制动:'.$mod['mod3_front_brake'];
							if(in_array('mod3_brake', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_rear_brake']) > 1) $content .= ' 后制动:'.$mod['mod3_rear_brake'];
							if(in_array('mod3_parking_brake', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_parking_brake']) > 1) $content .= ' '.$mod['mod3_parking_brake'];
							if(in_array('mod3_start_stop', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_start_stop']) > 1){
								if($mod['mod3_start_stop'] == '有') $content .= ' 有启停';
								else if($mod['mod3_start_stop'] == '无') $content .= ' 无启停';
							}
							if(in_array('novinitemurl', $this->wcof['wr_othcof']) || $this->wcof['wrr_hideurl']){
							}else if((!empty($itemArr) && !empty($mod['url'])) || empty($this->wcof['wr_maxitem'])){
								if($mod['url']) $content .= " \r\n".$mod['url'];
							}
							$content .= "\r\n";
						}
						$content .= "- - - - - - - - - - - - - -\r\n";

						$content .= $modArr['model'][0]['vin_year_name'].": ".$modArr['model'][0]['vin_year']."\r\n";
						if(in_array('mod3_engine', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_engine']) == 1) $content .= "发动机: ".$mergeArr['mod3_engine'][0]."\r\n";
						
						if(in_array('mod3_kw', $this->wcof['wr_vin_fileds'])){
							if(!empty($mergeArr['mod3_jgl_kw'][0]) && count($mergeArr['mod3_jgl_kw']) == 1)
							{
								$content .= "最大净功率: ".$mergeArr['mod3_jgl_kw'][0]."\r\n";
								if(!empty($mergeArr['mod3_ed_kw'][0]) && count($mergeArr['mod3_ed_kw']) == 1) $content .= "额定功率: ".$mergeArr['mod3_ed_kw'][0]."\r\n";
							}
							else if(count($mergeArr['mod3_kw']) == 1)
							{
								$content .= "功率: ".$mergeArr['mod3_kw'][0]."kw\r\n";
							}
						}
						if(in_array('mod3_cc', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_cc']) == 1 && !empty($mergeArr['mod3_cc'][0])) $content .= "排量: ".$mergeArr['mod3_cc'][0].'cc'."\r\n";
						if(in_array('mod3_transmission', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_transmission']) == 1) 
							$content .= "变速箱: ".$mergeArr['mod3_transmission'][0]."\r\n";
						if(in_array('mod3_drive', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_drive']) == 1) $content .= "驱动: ".$mergeArr['mod3_drive'][0]."\r\n";
						if(in_array('mod3_chassis', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_chassis']) == 1 && !empty($mergeArr['mod3_chassis'][0])) $content .= "底盘: ".$mergeArr['mod3_chassis'][0]."\r\n";
						if(in_array('mod3_body', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_body']) == 1) $content .= "车身: ".$mergeArr['mod3_body'][0]."\r\n";
						if(in_array('mod3_fuel', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_fuel']) == 1) $content .= "燃油: ".$mergeArr['mod3_fuel'][0]."\r\n";
						if(in_array('mod3_brake', $this->wcof['wr_vin_fileds']))
						{
							if(count($mergeArr['mod3_front_brake']) == 1 && count($mergeArr['mod3_rear_brake']) == 1)
							{
								$content .= "前/后制动: ".$mergeArr['mod3_front_brake'][0].'/'.$mergeArr['mod3_rear_brake'][0]."\r\n";
							}
							else
							{
								if(count($mergeArr['mod3_front_brake']) == 1) $content .= "前制动: ".$mergeArr['mod3_front_brake'][0]."\r\n";
								if(count($mergeArr['mod3_rear_brake']) == 1) $content .=  "后制动: ".$mergeArr['mod3_rear_brake'][0]."\r\n";
							}
						}
						if(in_array('mod3_parking_brake', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_parking_brake']) == 1) $content .= "驻车制动: ".$mergeArr['mod3_parking_brake'][0]."\r\n";
						if(in_array('mod3_start_stop', $this->wcof['wr_vin_fileds']) && count($mergeArr['mod3_start_stop']) == 1){
							if($mergeArr['mod3_start_stop'][0] == '有') $content .= "自动启停: 有\r\n";
							else if($mergeArr['mod3_start_stop'][0] == '无') $content .= "自动启停: 无\r\n";
						}
					
						//独立参数
						if(!empty($modArr['model'][0]['param']))
						{
							foreach($modArr['model'][0]['param'] as $pk=>$pv)
							{
								if(in_array('param_'.$pv[2], $this->wcof['wr_vin_fileds'])) $content .= $pv[0].": ".$pv[1]."\r\n";
							}
						}
						if(!in_array('novinjiucuo', $this->wcof['wr_othcof'])) $content .= "★若VIN解码错误，请回复“纠错”★\r\n";
					}
					else
					{
						foreach($modArr['model'] as $mk=>$mod)
						{
							$mod['brand_make'] = $mod['make_show_brand'] && $mod['make_show_brand'] == 1? $mod['brand_name']: $mod['make_name'];
							$mod['mod_name'] = $mod['brand_make'].' '.$mod['mod2_name'].' '.$mod['mod3_name'].' '.$mod['vin_year'];
							
							$showothmod = [];
							if(!empty($mod['mod3_engine']) && in_array('mod3_engine', $this->wcof['wr_vin_fileds']))	$showothmod[] = $mod['mod3_engine'];
							if(!empty($mod['mod3_kw']) && in_array('mod3_kw', $this->wcof['wr_vin_fileds']))	$showothmod[] = $mod['mod3_kw'].'kw';
							if(!empty($mod['mod3_cc']) && in_array('mod3_cc', $this->wcof['wr_vin_fileds']) && !empty($mod['mod3_cc']))	$showothmod[] = $mod['mod3_cc'].'cc';
							if(!empty($mod['mod3_transmission']) && in_array('mod3_transmission', $this->wcof['wr_vin_fileds']))	$showothmod[] = $mod['mod3_transmission'];
							if(!empty($mod['mod3_drive']) && in_array('mod3_drive', $this->wcof['wr_vin_fileds'])) $showothmod[] = $mod['mod3_drive'];
							if(!empty($mod['mod3_chassis']) && in_array('mod3_chassis', $this->wcof['wr_vin_fileds'])) $showothmod[] = $mod['mod3_chassis'];
							if(!empty($mod['mod3_body']) && in_array('mod3_body', $this->wcof['wr_vin_fileds'])) $showothmod[] = $mod['mod3_body'];
							if(!empty($mod['mod3_fuel']) && in_array('mod3_fuel', $this->wcof['wr_vin_fileds'])) $showothmod[] = $mod['mod3_fuel'];
							if(!empty($mod['mod3_brake']) && in_array('mod3_brake', $this->wcof['wr_vin_fileds'])) $showothmod[] = $mod['mod3_front_brake'].'/'.$mod['mod3_rear_brake'];
							if(!empty($mod['mod3_parking_brake']) && in_array('mod3_parking_brake', $this->wcof['wr_vin_fileds'])) $showothmod[] = $mod['mod3_parking_brake'];
							if(!empty($mod['mod3_start_stop']) && in_array('mod3_start_stop', $this->wcof['wr_vin_fileds'])){
								if($mod['mod3_start_stop'] == '有') $showothmod[] = ' 有启停';
								else if($mod['mod3_start_stop'] == '无') $showothmod[]= ' 无启停';

							} 
							if(!empty($showothmod)) $mod['mod_name'] .= " ".implode(' ', $showothmod);

							$content .= $modCount > 1? "- - - - - 解码车型- - - - -\r\n".$mod['mod_name']: $mod['mod_name'];
							if($this->wcof['wrr_hideurl']){	
							}else if((!empty($itemArr) && !empty($mod['url'])) || empty($this->wcof['wr_maxitem'])){
								if(!$wordNoItemHideIndex){
									$content .= $modCount == 1 ? "\r\n★点击链接查配件★\r\n".$mod['url']."\r\n": " ".$mod['url'];
								}
							}
							if(($mk+1) != $modCount) $content .= "\r\n";
						}
						if(!in_array('novinjiucuo', $this->wcof['wr_othcof'])) $content .= "★若VIN解码错误，请回复“纠错”★\r\n";
					}

					if(!empty($itemArr)){
						//有关键字但是无产品（产品是通过无关键字查询出来的）
						if(!$wordNoItemHideIndex){
							if($this->wcof['wrr_hideurl']){	
							}else if($vinDesurl && !in_array('zjcsurl', $this->wcof['wr_selfmod']) && $this->isMorePro){
								$content .= "\r\n★只展示".$this->isMorePro."条，点击链接显示更多产品★\r\n".$vinDesurl."\r\n";
								$this->isMorePro = 0;
							}
							$tplRes = $this->vinItemTpl($itemArr);
							$content .= "\r\n".$tplRes['content'];
						}else{
							if($this->wcof['wrr_hideurl']){	
								$content .= "\r\n★无【".$noVinKeyword."】配件\r\n";
							}else{
								$content .= "\r\n★无【".$noVinKeyword."】配件，点击链接查看其他配件★\r\n".$vinDesurl."\r\n";
							}
						}
					}else if($itemArr !== null){
						$content .= "\r\n- - - 无相关车型的配件信息 - - -\r\n";
					}
				}
				else
				{
					if(count($modArr['model']) >= 3)
					{
						$sameArr = [];
						$notsameArr = [];
						if($modArr['from'] == 'bigcar')
						{
							foreach($modArr['label'] as $lk=>$lv)
							{
								$vals = array_unique(array_column($modArr['model'], $lk));
								if(count($vals) == 1 || count($vals) ==2 && in_array('', $vals))
								{
									$sameArr[] = $lv.'：'.implode(',', $vals);
									unset($modArr['label'][$lk]);
								}
							}
						}
						else
						{
							foreach($modArr['label'] as $lk=>$lv)
							{
								$vals = array_unique(array_column($modArr['model'], $lv));
								if(count($vals) == 1 || count($vals) ==2 && in_array('', $vals))
								{
									$sameArr[] = $lv.'：'.implode(',', $vals);
									unset($modArr['label'][$lk]);
								}
							}
						}
						if(!empty($sameArr)) $content .= "- - - - -基本信息- - - - -\r\n".implode("\r\n", $sameArr)."\r\n";
						foreach($modArr['model'] as $mk=>$mod)
						{
							$vals = [];
							foreach($modArr['label'] as $lk=>$lv)
							{
								if(!empty($mod[$lk]))
									$vals[] = $mod[$lk];
								if(!empty($mod[$lv]))
									$vals[] = $mod[$lv];
							}
							$content .= "- - - - -解码车型- - - - -\r\n".implode(" ", $vals);
							if(($mk+1) != $modCount) $content .= "\r\n";
						}
					}
					else
					{
						$has = false;
						foreach($modArr['model'] as $mk=>$mod)
						{
							$vals = [];
							foreach($modArr['label'] as $lk=>$lv)
							{
								if(!empty($mod[$lk]))
									$vals[] = $lv.'：'.$mod[$lk];
								if(!empty($mod[$lv]))
									$vals[] = $lv.'：'.$mod[$lv];
							}
							if($vals) $has = true;
							$content .= "- - - - - 解码车型 - - - - \r\n".implode("\r\n", $vals);
							if(($mk+1) != $modCount) $content .= "\r\n";
						}
						if(!$has) $content = '';
					}
				}
				//结果提示语
				if($content){
					if(!empty($this->wcof['wr_hasrestxt'])) $content = rtrim($content, "\r\n")."\r\n\r\n".$this->wcof['wr_hasrestxt'];
					$tjArr = [
						'tj_site'=>'PJD',
						'tj_param'=>json_encode($mtjArr, JSON_UNESCAPED_UNICODE),	
						'tj_ip'=>LibFc::GetClientIp(),
						'tj_from'=>'WXROBOT',
						'tj_shopid'=>$this->wcof['wr_uid'],
						'tj_act'=>'wechat/msg',
						'tj_devcode'=>'robot?uid='.$this->wcof['wr_uid'].'&wrt_id='.$this->postArr['wrt_id'],
						'tj_time'=>time()
					];
					$allTjArr = [json_encode($tjArr)];
					$MainRabbit = new MainRabbit('TJ_MAIN');
					$MainRabbit->send($allTjArr);
				}
			}
		}
		
		//最后查询记录$m3idsArr
		if($vin){
			if(empty($m3idsArr)) $m3idsArr = [];
			$lastVin = [
				'wrv_user'=>$userkey,
				'wrv_vin'=>$vin,
				'wrv_m3ids'=>implode(',', $m3idsArr),
				'wrv_etime'=>time(),
				'wrv_image'=>$this->postArr['image']? $this->postArr['image']: ''
			];
			$B2cSearch->replace('wx_robot_vinlast', $lastVin);
		}
		
		//屏蔽中文  有可能是价格1~4位数字
		if(empty($content) && strlen($formatNum) >= 2 && !preg_match_all('/[\x{4e00}-\x{9fa5}]/u', $keyword, $match) && (in_array('onlynum34', $this->wcof['wr_othcof']) || !preg_match('/^[1-9][0-9]{2,3}$/', $keyword, $match)))
		{
			if($this->wcof['wr_number'] > 0 && $this->wcof['wr_totype'] != 'vin')
			{
				//产品列表
				switch($this->wcof['wr_totype'])
				{
					case 'super': 
					case 'superpjl': 
					case 'gzh': 
						$maxPer = 10;
						if($this->wcof['wr_totype'] == 'superpjl')
							$numurl = $this->wcof['host'].'superSearch?type=number&numtype='.$this->wcof['wr_number'].'&keyword='.urlencode($keyword).'&ssu_id='.$this->wcof['ssu_id'].'&shop_id='.$this->wcof['wr_uid'];
						else
							$numurl = $this->wcof['host'].'item/search?type=number&numtype='.$this->wcof['wr_number'].'&keyword='.urlencode($keyword);
						$itemArr = $this->getItems(['type'=>'number', 'number'=>$keyword,'numtype'=>$this->wcof['wr_number']], $maxPer);
					break;
					case 'yiparts':
						$maxPer = 1;
						$numurl = $this->wcof['host'].'num?num='.urlencode($keyword);
						$itemArr = $this->getItems(['type'=>'etk,yp,tcd,aaia','word'=>$keyword, 'dtype'=>'para'], $maxPer);
					break;
					case 'pjlshop':
						$maxPer = 10;
						$itemArr = $this->getItems(['type'=>'number','number'=>$keyword], $maxPer);
					break;
				}
				if(!empty($itemArr))
				{
					$this->wordtype = 'number';
					if($this->wcof['wrr_hideurl']){
						$content .= '号码【'.$this->showKeyword($keyword)."】\r\n";
					}else if(count($itemArr) > 0){
						if(in_array('apigeturl', $this->wcof['wr_selfmod'])){
							$selfUrlArr = $this->getSelfApiUrl($keyword, 'number');
							$numurl = !empty($selfUrlArr['url'])? $selfUrlArr['url']: '';
						}else if($numurl){
							$this->urlArr[] = $numurl;
						}
						if(count($itemArr) > 1 && $numurl){
							$content .= '号码【'.$this->showKeyword($keyword)."】".$numurl."\r\n";
						}else{
							$content .= '号码【'.$this->showKeyword($keyword)."】\r\n";
						}
					}

					$lastPart = '';
					foreach($itemArr as $mk=>$mv)
					{
						if($lastPart != $mv['part_name'])	$content .= "- - - {$mv['part_name']} - - -\r\n";
						$lastPart = $mv['part_name'];
						if($mv['part_name'] != $mv['pro_name'] && in_array('itemname', $this->wcof['wr_othcof'])) $content .= "【".$mv['pro_name']."】\r\n";
						if(!empty($mv['show_name'])) $content .= implode("\r\n", $mv['show_name'])."\r\n";

						if(!empty($mv['para']) && ($this->wcof['wr_totype'] == 'yiparts' || (in_array('itempara_one', $this->wcof['wr_othcof']) && count($itemArr) == 1) || in_array('itempara', $this->wcof['wr_othcof'])))
						{
							foreach($mv['para'] as $pvv){
								$content .= "{$pvv['name']}：{$pvv['val']}{$pvv['unit']}\r\n";
							}
						}
						if($this->wcof['wrr_hideurl']){	
						}else if(!empty($mv['url']) && ((in_array('itemurl_one', $this->wcof['wr_othcof']) && count($itemArr) == 1) || in_array('itemurl_any', $this->wcof['wr_othcof'])))
							$content .= $mv['url']."\r\n";
						//配件间无换行
						$content .= in_array('itemnobr', $this->wcof['wr_othcof'])? '': "\r\n";
					}
				}
			}
		}	
		
		//是否为发动机开头
		if($this->wcof['wr_engine'] > 0 && !$this->wordtype && preg_match('/^[0-9a-zA-Z]{2,}([0-9a-zA-Z\.\- \/\;]*[0-9a-zA-Z])?/i', $keyword, $match)){
			$engword = $match[0];
			$engendword = trim(substr($keyword, strlen($engword)));
			$engwordf = LibFc::FormatNum($engword);
			$engwords = [];
			if(!preg_match('/^[0-9]{2,5}$/', $engwordf, $tmatch)){
				$Ypc2Model = new Ypc2Model();
				if($this->wcof['wr_engine'] == 2){
					$where = sprintf(" and mod3_engine_format = '%s' group by mod3_engine_format", $engwordf);
				}else{
					$where = sprintf(" and mod3_engine_format like '%s%%' group by mod3_engine_format order by length(mod3_engine_format)", 
					$engwordf, strlen($engwordf)+3);
				}
				$where = sprintf(" and mod3_engine_format like '%s%%' group by mod3_engine_format order by length(mod3_engine_format)", 
					$engwordf, strlen($engwordf)+3);
				$res = $Ypc2Model->get('bc_model3', ['mod3_engine_format'], $where);
				if(!empty($res['data'])){
					if($res['data'][0]['mod3_engine_format'] == $engwordf){
						$engwords = [$res['data'][0]['mod3_engine_format']];
					}else{
						$engwords = array_column($res['data'], 'mod3_engine_format');
					}
					$this->wordtype = 'engine';
				}
			}
			
			if($this->wordtype == 'engine'){//单纯查发动机
				switch($this->wcof['wr_totype'])
				{
					case 'super': 
					case 'superpjl': 
					case 'gzh': 
						$maxPer = 10;
						if($this->wcof['wr_totype'] == 'superpjl')
							$engurl = $this->wcof['host'].'superSearch?type=engine&engtype='.$this->wcof['wr_engine'].'&keyword='.urlencode($engword).'&ssu_id='.$this->wcof['ssu_id'].'&shop_id='.$this->wcof['wr_uid'];
						else
							$engurl = $this->wcof['host'].'item/searchEngine?type=engine&engtype='.$this->wcof['wr_engine'].'&keyword='.urlencode($engword);
						$B2cSearch = new B2cSearch();
						$res = $B2cSearch->searchEngine($this->wcof['wr_uid'], $engwords, $this->wcof['wr_totype'], $maxPer, $this->wcof['wr_engine']);
						$engArr = $res['data'];
					break;
					case 'yiparts':
					case 'vin':
						$maxPer = 10;
						$engurl = $this->wcof['host'].'engine?word='.urlencode($engword);
						$LibYpApi = new LibYpApi();
						$res = $LibYpApi->get('ypc/getEngineInfo', ['word'=>$engword]);
						$engArr = $res['data'];
					break;
					case 'pjlshop':
						$maxPer = 10;
						$LibYpApi = new LibYpApi();
						$res = $LibYpApi->get('ypc/getEngineInfo', ['word'=>$engword]);
						$engArr = $res['data'];
					break;
				}
				if(!empty($engArr))
				{
					if(!empty($content)) $content .= "\r\n";
					$showmax = 2;
					if($this->wcof['wrr_hideurl']){	
						$content .= '发动机【'.$this->showKeyword($keyword)."】\r\n";
					}else{
						if(in_array('apigeturl', $this->wcof['wr_selfmod'])){
							$selfUrlArr = $this->getSelfApiUrl($keyword, 'engine');
							$engurl = !empty($selfUrlArr['url'])? $selfUrlArr['url']: '';
						}else if($engurl){
							$this->urlArr[] = $engurl;
						}
						$content .= '发动机【'.$this->showKeyword($keyword)."】".($engurl? $engurl: '')."\r\n";
					}

					foreach($engArr as $mk=>$mv)
					{
						$mv['show_name'] = $mv['brand_name'].' '.$mv['mod3_engine'].' '.$mv['mod3_kw'].'kw '.(empty($mv['mod3_cc'])? '':$mv['mod3_cc'].'cc ').$mv['mod3_fuel'];
						$content .= "- - - - - 发动机- - - - -\r\n".$mv['show_name'];
						if($this->wcof['wrr_hideurl']){	
						}else if(count($engArr) == 1 && in_array($this->wcof['wr_totype'], ['gzh', 'super'])){
							/*$mv['url'] = $this->wcof['host'].'item/search?type=item&name='.urlencode($mv['show_name']).'&brand_id='.$mv['brand_id'].'&mod3_engine='.$mv['mod3_engine'].'&mod3_cc='.$mv['mod3_cc'].'&mod3_kw='.$mv['mod3_kw'];
							$this->urlArr[] = $mv['url'];
							$content .= "\r\n".$mv['url'];*/
						}
						if(($mk+1) != count($engArr)) $content .= "\r\n";
						if(($mk+1) == $showmax) break;
					}
					/*if($this->wcof['wrr_hideurl']){	
					}else if(count($engArr) > $showmax){
						$content .= "\r\n- - - 点击下方链接查看更多信息 - - -\r\n".$engurl."\r\n";
					}*/

					if(LibFc::iscnlang($engendword) && in_array($this->wcof['wr_totype'], ['super','superpjl','gzh'])){//必须包含中文
						$itemcount = $this->wcof['wr_maxitem'];
						if(empty($this->wcof['wr_maxitem'])) $itemcount = 10;
						$itemArr = $this->getItems(['type'=>'model', 'mod3_engine'=>implode(',', $engwords), 'keyword'=>$engendword], $itemcount+1);
						if(!empty($itemArr)){
							if(count($itemArr) > $itemcount){
								array_pop($itemArr);
								$this->isMorePro = $itemcount;
							}
							$tplRes = $this->vinItemTpl($itemArr);
							$content .= "\r\n\r\n".$tplRes['content'];
						}
					}
				}
			}
		}

		//目录类 1分钟内的最后一次的VIN
		if(!in_array('closevinword', $this->wcof['wr_othcof']) && !$vin && LibFc::iscnlang($keyword) && empty($content) && in_array($this->wcof['wr_totype'], ['super','superpjl','gzh','pjlshop']))
		{
			$res = $B2cSearch->get('wx_robot_vinlast', ['wrv_vin,wrv_m3ids'], sprintf(" and wrv_user='%s' and wrv_etime > %d limit 1", LibFc::Escape($userkey), time()-60), true);
			if(!empty($res['data']['wrv_m3ids']))
			{
				$itemcount = $this->wcof['wr_maxitem'];
				if(empty($this->wcof['wr_maxitem'])) $itemcount = 10;
				$lastvin = $res['data'];
				$itemArr = $this->getItems(['type'=>'model', 'mod3_id'=>$lastvin['wrv_m3ids'], 'keyword'=>$keyword], $itemcount+1);
				if(!empty($itemArr))
				{
					if(count($itemArr) > $itemcount){
						array_pop($itemArr);
						$this->isMorePro = $itemcount;
					}
					$content = ($this->postArr['roomId']? "\r\n":'').'车架号：'.$lastvin['wrv_vin']."\r\n【".$this->showKeyword($keyword)."】配件\r\n";
					$tplRes = $this->vinItemTpl($itemArr);
					$content .= "\r\n".$tplRes['content'];
				}
			}
		}
		
		if(empty($content))
		{
			if($this->wcof['talkfrom'] == 'wxgzh'){
				if(!empty($this->wcof['wr_autotxt']['nores'])) $content = $this->wcof['wr_autotxt']['nores'];
			}else if($vin){ 
				$content = '车架号【'.$vin.'】无相关解码信息';
			}else if($this->wcof['talkfrom'] != 'room'){
				$content = '找不到相关信息';
			}
		}
		else if(!empty($this->urlArr))
		{
			$OthDwz = new OthDwz();
			$res = $OthDwz->dwz($this->urlArr);
			$dwzArr = array_column($res['data'], 'dwz', 'url');
			$content = strtr($content, $dwzArr);
		}
		$content = rtrim($content, "\r\n");
		LibFc::ReturnJson(true, ['saymsg'=>$content]);
	}


	//获取产品信息
	private function getItems($params, $maxPer = 10)
	{
		$itemArr = [];
		$melId = in_array('showprice', $this->wcof['wr_selfmod'])? $this->wcof['wrr_mel_id']: -1;
		$factory = in_array('roomfactory', $this->wcof['wr_selfmod']) && !empty($this->wcof['wrr_factory']) ? $this->wcof['wrr_factory']: '';
		//配件分类、配件品牌、配件店铺权限
		if(in_array('roompart', $this->wcof['wr_selfmod']) && !empty($this->wcof['wrr_part_ids'])) $params['part_id'] = $this->wcof['wrr_part_ids'];
		if(in_array('roompbrand', $this->wcof['wr_selfmod']) && !empty($this->wcof['wrr_prb_ids'])) $params['prb_id'] = $this->wcof['wrr_prb_ids'];
		if(in_array('roomsort', $this->wcof['wr_selfmod']) && !empty($this->wcof['wrr_sort_ids'])) $params['sort_id'] = $this->wcof['wrr_sort_ids'];
		$params['from'] = 'robot';
		$fileds = ['para', 'numMain'];
		switch($this->wcof['wr_totype'])
		{
			case 'super':
			case 'superpjl':
				$B2cSearch = new B2cSearch();
				$res = $B2cSearch->searchSuperItem($this->wcof['wr_uid'], $params, $maxPer);
				if(!empty($res['data']['proIds']))
				{
					$B2cProduct = new B2cProduct();
					$res = $B2cProduct->getApiProductInfo($this->wcof['wr_uid'], $res['data']['proIds'], $fileds, $params['mod3_id'], $melId, ['factory'=>$factory]);
					$itemArr = $res['data']; 
					$selfUrlArr = in_array('apigeturl', $this->wcof['wr_selfmod'])? $this->getSelfApiUrl(array_column($itemArr, 'pro_id'), 'item') : [];
					foreach($itemArr as $mk=>$mv)
					{
						$mv['show_name'] = [];
						//指定了厂商
						if(!empty($factory) && !empty($mv['numfac'])){
							$mv['show_name'][] = $mv['numfac'][0]['factory'].'：'.$mv['numfac'][0]['display'];
						}else{
							foreach($mv['num'] as $nk=>$nv){
								if((in_array('numzb', $this->wcof['wr_othcof']) && $nv['type'] == 'zb') || (in_array('nummain', $this->wcof['wr_othcof']) && $nv['type'] == 'main'))
									$mv['show_name'][] = $nv['factory'].'：'.$nv['display'];
							}
						}
						
						if(!empty($mv['prices'])){
							if(count($mv['prices']) == 1 && empty($mv['prices'][0]['men_alias'])) $mv['prices'][0]['men_alias'] = '价格';
							foreach($mv['prices'] as $mpv){
								$mv['show_name'][] = ($mpv['men_alias']?$mpv['men_alias']: $mpv['mel_name']).'：'.$mpv['price'].'元';
							}
						}
						if($selfUrlArr[$mv['pro_id']]){
							$mv['url'] = $selfUrlArr[$mv['pro_id']];
						}else if($this->wcof['wr_totype'] == 'superpjl'){
							$mv['url'] = $this->wcof['host'].'item?type=super&proId='.$mv['pro_id'];
							$this->urlArr[] = $mv['url'];
						}else{
							$mv['url'] = $this->wcof['host'].'item/info?proId='.$mv['pro_id'];
							$this->urlArr[] = $mv['url'];
						}
						$itemArr[$mk] = $mv;
					}
				}
			break;
			case 'gzh': 
				$B2cSearch = new B2cSearch();
				$res = $B2cSearch->searchGzhItem($this->wcof['wr_uid'], $params, $maxPer);
				if(!empty($res['data']['proIds']))
				{
					$B2cProduct = new B2cProduct();
					$res = $B2cProduct->getApiProductInfo($this->wcof['wr_uid'], $res['data']['proIds'], $fileds, $params['mod3_id'], $melId, ['factory'=>$factory]);
					$itemArr = $res['data'];
					$selfUrlArr = in_array('apigeturl', $this->wcof['wr_selfmod'])? $this->getSelfApiUrl(array_column($itemArr, 'pro_id'), 'item') : [];
					foreach($itemArr as $mk=>$mv)
					{
						$mv['show_name'] = [];
						if($selfUrlArr[$mv['pro_id']]){
							$mv['url'] = $selfUrlArr[$mv['pro_id']];
						}else{
							$mv['url'] = $this->wcof['host'].'item/info?proId='.$mv['pro_id'];
							$this->urlArr[] = $mv['url'];
						}
						//指定了厂商
						if(!empty($factory) && !empty($mv['numfac'])){
							$mv['show_name'][] = $mv['numfac'][0]['factory'].'：'.$mv['numfac'][0]['display'];
						}else{
							foreach($mv['num'] as $nk=>$nv){
								if((in_array('numzb', $this->wcof['wr_othcof']) && $nv['type'] == 'zb') || (in_array('nummain', $this->wcof['wr_othcof']) && $nv['type'] == 'main')){
									if($this->wcof['wr_uid'] == 965832 && $nv['type'] == 'zb'){
										$mv['show_name'][] = '配件码：'.$nv['display'];
										$mv['show_name'][] = '品牌：'.$nv['factory'];
									}else{
										$mv['show_name'][] = $nv['factory'].'：'.$nv['display'];
									}
								}
							}
						}
						if(in_array('zjcsurl', $this->wcof['wr_selfmod'])){//勤昌盛多价格
							unset($mv['url']);
							if($melId > -1)
							{
								$showPrice = [];
								if($mv['pro_sale_price'] > 0)
									$showPrice[] = '售价'.$mv['pro_sale_price'];
								if($mv['pro_price_vip'.$melId] > 0 && ($mv['pro_sale_price'] = 0 || $mv['pro_price_vip'.$melId] <= $mv['pro_sale_price']))
									$showPrice[] = 'VIP售价'.$mv['pro_price_vip'.$melId];
								if(!empty($showPrice)) $mv['show_name'][] = implode('   ', $showPrice);
							}
						}else if(!empty($mv['prices'])){
							if(count($mv['prices']) == 1 && empty($mv['prices'][0]['men_alias'])) $mv['prices'][0]['men_alias'] = '价格';
							foreach($mv['prices'] as $mpv){
								$mv['show_name'][] = ($mpv['men_alias']?$mpv['men_alias']: $mpv['mel_name']).'：'.$mpv['price'].'元';
							}
						}
						$itemArr[$mk] = $mv;
					}
				}
			break;
			case 'yiparts': 
				$LibYpApi = new LibYpApi();
				$res = $LibYpApi->Get('number/search', $params);
				$proArr = $res['data'];
				$itemArr = [];
				foreach($proArr as $pt=>$pvs)
				{
					foreach($pvs as $mv)
					{
						if(empty($mv['part_name'])) $mv['part_name'] = $mv['pro_name'];
						$mv['show_name'] = [];
						foreach($mv['num'] as $nk=>$nv)
						{
							if(count($mv['num']) > 1 && $nk == 0) continue;
							$mv['show_name'][] = $nv['factory'].'：'.$nv['display'];
							break;
						}
						$mv['url'] = $this->wcof['host'].'item?type='.$pt.'&proId='.$mv['pro_id'];
						$this->urlArr[] = $mv['url'];
						$itemArr[] = $mv;
						break;
					}
				}
			break;
			case 'pjlshop':
				$PjlProduct = new PjlProduct();
				$res = $PjlProduct->searchShopItem($this->wcof['wr_uid'], $params, $maxPer);
				$itemArr = $res['data']['items'];
				foreach($itemArr as $mk=>$mv){
					$mv['part_name'] = $mv['pro_name'];
					$mv['show_name'] = [];
					if(in_array('numpjl', $this->wcof['wr_othcof']) && $mv['pro_display']) $mv['show_name'][] = '号码：'.$mv['pro_display'];
					if(in_array('itemprice', $this->wcof['wr_othcof']) && $mv['pro_price'] > 0) $mv['show_name'][] = '价格：'.$mv['pro_price'].'元';
					if(in_array('itemquality', $this->wcof['wr_othcof']) && $mv['pro_quality']) $mv['show_name'][] = '品质：'.$mv['pro_quality'];
					if(in_array('itemmodeltxt', $this->wcof['wr_othcof']) && $mv['pro_model']) $mv['show_name'][] = '车型：'.$mv['pro_model'];
					$itemArr[$mk] = $mv;
				}
			break;
		}
		return $itemArr;
	}

	
	//车架号的产品模板
	private function vinItemTpl($itemArr)
	{
		$content = "";
		$partItems = [];
		foreach($itemArr as $mk=>$mv)
		{
			$partItems[$mv['part_name']][$mv['pro_name']][] = $mv;
		}
		foreach($partItems as $partname=>$ptivs)
		{
			$content .= "- - - {$partname} - - -\r\n";
			foreach($ptivs as $proname=>$tivs)
			{
				if(!empty($proname) && $proname != $partname && in_array('itemname', $this->wcof['wr_othcof'])) $content .= '【'.$proname."】\r\n";
				$anyItems = [];
				$isAnyRow = false;
				foreach($tivs as $mv)
				{
					$srow = [];
					if(!empty($mv['show_name'])) $srow = array_merge($srow, $mv['show_name']);
					//车型参数
					if(!empty($mv['mod3_para'])) $srow[] = '车型备注：'.$mv['mod3_para'];
					if(!empty($mv['para']) && ((in_array('itempara_one', $this->wcof['wr_othcof']) && count($itemArr) == 1) || in_array('itempara', $this->wcof['wr_othcof'])))
					{
						foreach($mv['para'] as $pvv)
						{
							$srow[] = "{$pvv['name']}：{$pvv['val']}{$pvv['unit']}";
						}
					}
					if(count($srow) > 1) $isAnyRow = true;
					if($this->wcof['wrr_hideurl']){	
					}else if(!empty($mv['url']) && ((in_array('itemurl_one', $this->wcof['wr_othcof']) && count($itemArr) == 1) || in_array('itemurl_any', $this->wcof['wr_othcof']))){
						$srow[] = $mv['url'];
					}
					if(!empty($srow)) $anyItems[] = implode("\r\n", $srow);
				}
				if($anyItems){
					$content .= $isAnyRow? implode("\r\n\r\n", $anyItems): implode("\r\n", $anyItems);
					$content .= "\r\n\r\n";
				}
			}
		}
		if(in_array('itemnobr', $this->wcof['wr_othcof']))
			$content = str_replace("\r\n\r\n", "\r\n", $content);
		return ['content'=>$content];
	}

	/**
	  * @method 检测是否有机器人控制权
	  * @http  post
	  * @author soul 
	  * @copyright 2022/7/4
	  * @return json
	  */
	public function checkIsOwner()
	{
		$arr = ['owner'=>false];
		$table = 'wx_robot_wx JOIN wx_robot ON wrw_wr_id = wr_id JOIN wx_robot_token ON wr_wrt_id = wrt_id';
		$res = $res = $this->B2cBase->get($table, ['wrt_id,wrt_uid,wrw_isadmin'], sprintf(" and wrt_id=%d and wrw_wx_id='%s'", $this->postArr['wrt_id'], LibFc::Escape($this->postArr['talkerId'])), true);
		if(!empty($res['data']['wrt_id'])){
			if($res['data']['wrt_id'] > 2 || ($res['data']['wrt_id'] <= 2 && $res['data']['wrw_isadmin'])){
				$arr['owner'] = true;
			}
		}
		LibFc::ReturnJson(true, $arr);
	}

	/**
	  * @method 检测是否开通机器人
	  * @http  post
	  * @author soul 
	  * @copyright 2022/7/4
	  * @return json
	  */
	public function check()
	{
		$wr_id = 0; //机器人id
		$wrr_id = 0; //群id
		$now = time();
		$res = $this->B2cBase->get('wx_robot_token', ['wrt_id,wrt_type,wrt_comname,wrt_wxid'], sprintf(" and wrt_id=%d", $this->postArr['wrt_id']), true);
		if(empty($res['data'])) LibFc::ReturnJson(true, ['wr_id'=>$wr_id, 'wrr_id'=>$wrr_id, 'saymsg'=>'']);
		$tokenArr = $res['data'];
		if(!empty($this->postArr['userinfo']['id']) && empty($this->postArr['roominfo']))
		{//好友修复
			$userinfo = $this->postArr['userinfo'];
			$setArr = [
				'wrw_wx_id'=>$userinfo['id'],
				'wrw_name'=>LibFc::filterEmoji($userinfo['name']),
				'wrw_info'=>json_encode($userinfo, JSON_PARTIAL_OUTPUT_ON_ERROR),
				'wrw_etime'=>$now,
			];
			$userinfo['id'] = LibFc::Escape($userinfo['id']);
			if($tokenArr['wrt_type'] == 'wxwork')
			{//企业微信 检测所属公司
				$where = sprintf(" and wr_wrt_id=%d and wr_type in ('wxgr') and wr_btime <= %d and wr_etime >= %d", $tokenArr['wrt_id'], $now, $now);
				$res = $this->B2cBase->get('wx_robot', ['wr_id'], $where, true);
				if(empty($res['data'])) LibFc::ReturnJson(true, ['saymsg'=>$tokenArr['wrt_comname'].'尚未配置机器人']);
				$wr_id = $res['data']['wr_id'];

				if($userinfo['id'] == $tokenArr['wrt_wxid']) LibFc::ReturnJson(true, ['saymsg'=>'您就是机器人，无需修复']);
				if($userinfo['corporation'] != $tokenArr['wrt_comname']) 
					LibFc::ReturnJson(true, ['saymsg'=>'当前账号不属于【'.$tokenArr['wrt_comname'].'】企业']);
				
				$where = sprintf(" and wrw_wr_id = %d", $wr_id);
				$where .= empty($userinfo['weixin'])? sprintf(" and (wrw_wx='%s' or wrw_wx_id='%s')", $userinfo['weixin'], $userinfo['id']): sprintf(" and wrw_wx='%s'", LibFc::Escape($userinfo['weixin']));
				$res = $this->B2cBase->get('wx_robot_wx', ['wrw_id'], $where, true);
				if(empty($res['data'])) LibFc::ReturnJson(true, ['saymsg'=>'请在机器人后台配置该账号的企微手机号']);
				$this->B2cBase->set('wx_robot_wx', $setArr, sprintf(" and wrw_id=%d", $res['data']['wrw_id']));

				/*if(!empty($userinfo['weixin'])) $setArr['wrw_wx'] = $userinfo['weixin'];
				$res = $this->B2cBase->get('wx_robot_wx', ['wrw_id'], sprintf(" and wrw_wr_id=%d and wrw_wx_id='%s'", $wr_id, $userinfo['id']), true);
				if(empty($res['data']))
				{//直接追加记录
					$setArr['wrw_wr_id'] = $wr_id;
					$this->B2cBase->add('wx_robot_wx', $setArr);
				}
				else
				{
					$this->B2cBase->set('wx_robot_wx', $setArr, sprintf(" and wrw_id=%d", $res['data']['wrw_id']));
				}*/
			}
			else
			{//个微预先绑定微信号
				$where = sprintf(" and wr_wrt_id=%d and wr_type in ('wxgr') and wr_btime <= %d and wr_etime >= %d", $tokenArr['wrt_id'], $now, $now);
				$where .= empty($userinfo['weixin'])? sprintf(" and (wrw_wx='%s' or wrw_wx_id='%s')", $userinfo['id'], $userinfo['id']): sprintf(" and wrw_wx='%s'", LibFc::Escape($userinfo['weixin']));
				$table = 'wx_robot join wx_robot_wx ON wrw_wr_id = wr_id';
				$res = $this->B2cBase->get($table, ['wr_id,wrw_id'], $where, true);
				if(empty($res['data'])) LibFc::ReturnJson(true, ['saymsg'=>'您的微信号尚未配置机器人']);
				$wr_id = $res['data']['wr_id'];
				$this->B2cBase->set('wx_robot_wx', $setArr, sprintf(" and wrw_id=%d", $res['data']['wrw_id']));
			}
			$this->B2cBase->replace('wx_acount', ['wa_id'=>$setArr['wrw_wx_id'], 'wa_nickname'=>$setArr['wrw_name']]);
		}
		else if($this->postArr['act'] == 'chkroom' && !empty($this->postArr['roominfo']))
		{//群修复
			$memsArr = is_array($this->postArr['mems'])? $this->postArr['mems']: [];
			$roominfo = $this->postArr['roominfo'];
			
			$res = $this->B2cBase->get('wx_robot_room', ['wrr_status'], sprintf(" and wrr_wr_id=%d and wrr_room_id='%s'", $wr_id, LibFc::Escape($roominfo['id'])), true);
			//群被停用，静默
			if(isset($res['data']['wrr_status']) && $res['data']['wrr_status'] != 1) LibFc::ReturnJson(true, ['saymsg'=>'']);

			$wrr_id = 0;
			//优先说修复的人
			if(!empty($this->postArr['talkerId']))
			{
				$chkMemsArr = [];
				$t2Arr = [];
				foreach($memsArr as $men)
				{
					if($men['id'] != $this->postArr['talkerId']){
						$t2Arr[] = $men;
					}else{
						$chkMemsArr[] = $men;
					}
				}
				$chkMemsArr = array_merge($chkMemsArr, $t2Arr);
			}
			else
			{
				$chkMemsArr = $memsArr;
			}

			/*if($tokenArr['wrt_type'] == 'wxwork')
			{//企业微信 检测所属公司
				$where = sprintf(" and wr_wrt_id=%d and wr_type in ('wxgr') and wr_btime <= %d and wr_etime >= %d", $tokenArr['wrt_id'], $now, $now);
				$res = $this->B2cBase->get('wx_robot', ['wr_id,wr_uid,wr_room_max,wr_mel_id'], $where, true);
				if(empty($res['data'])) LibFc::ReturnJson(true, ['saymsg'=>$tokenArr['wrt_comname'].'尚未配置机器人']);
				$wxRow = $res['data'];
				foreach($chkMemsArr as $men)
				{
					if($men['coworker'] && $men['id'] != $tokenArr['wrt_wxid'] && $men['corporation'] == $tokenArr['wrt_comname']){
						$wr_id = $wxRow['wr_id'];
						break;
					}
				}
			}
			else
			{*/
				foreach($chkMemsArr as $men)
				{
					$where = sprintf(" and wr_wrt_id=%d and wr_type in ('wxgr') and wr_btime <= %d and wr_etime >= %d and wrw_wx_id='%s'", $tokenArr['wrt_id'], $now, $now, LibFc::Escape($men['id']));
					$table = 'wx_robot join wx_robot_wx ON wrw_wr_id = wr_id';
					$res = $this->B2cBase->get($table, ['wr_id,wr_uid,wr_room_max,wr_mel_id'], $where, true);
					if(!empty($res['data']))
					{
						$wxRow = $res['data'];
						$wr_id = $wxRow['wr_id'];
						break;
					}
				}
			//}
			if($wr_id > 0)
			{
				$addRoom = [
					'wrr_wr_id'=>$wr_id,
					'wrr_room_id'=>$roominfo['id'],
					'wrr_room_name'=>LibFc::filterEmoji($roominfo['topic']),
					'wrr_info'=>json_encode($roominfo, JSON_PARTIAL_OUTPUT_ON_ERROR),
					'wrr_mems'=>json_encode($memsArr, JSON_PARTIAL_OUTPUT_ON_ERROR),
					'wrr_etime'=>$now
				];

				$res = $this->B2cBase->get('wx_robot_room', ['wrr_id', 'wrr_wr_id'], sprintf(" and wrr_wr_id=%d and wrr_room_id='%s'", $wr_id, LibFc::Escape($roominfo['id'])), true);
				if(!(empty($res['data'])))
				{//已经存在
					$wrr_id = $res['data']['wrr_id'];
					$this->B2cBase->set('wx_robot_room', $addRoom, sprintf(" and wrr_id=%d", $wrr_id));
						$where = sprintf(" and wrr_id!=%d and wrr_room_id='%s' AND wrr_room_id IN (
						SELECT * FROM (
						SELECT DISTINCT wrr_room_id FROM `wx_robot_room`
						JOIN `wx_robot` ON wrr_wr_id = wr_id
						JOIN `wx_robot_token` ON (wrt_id = wr_wrt_id OR wr_uid = wrt_uid)
						WHERE wrt_id = %d
					) t)", $wrr_id, LibFc::Escape($roominfo['id']), $tokenArr['wrt_id']);
					$this->B2cBase->del('wx_robot_room', $where);
				}
				else
				{
					$res = $this->B2cBase->get('wx_robot_room', ['count(*) count'], sprintf(" and wrr_wr_id='%s'", LibFc::Escape($wr_id)), true);
					if(isset($res['data']['count']) && $res['data']['count'] < $wxRow['wr_room_max'])
					{//群数量尚未达到上限
						$addRoom['wrr_mel_id'] = $wxRow['wr_mel_id'];
						$addRoom['wrr_atime'] = time();
						$res = $this->B2cBase->add('wx_robot_room', $addRoom);
						$wrr_id = $res['data'];
					}
					else
					{
						LibFc::ReturnJson(true, ['saymsg'=>'目录'.$wxRow['wr_uid'].'机器人的群数量已使用完']);
					}
				}
				$B2cShop = new B2cShop();
				$B2cShop->initWxAccount([$roominfo['id']]);
			}
			else
			{//删除群配置
				$where = sprintf(" and wrr_room_id='%s' AND wrr_room_id IN (
					SELECT * FROM (
					SELECT DISTINCT wrr_room_id FROM `wx_robot_room`
					JOIN `wx_robot` ON wrr_wr_id = wr_id
					JOIN `wx_robot_token` ON (wrt_id = wr_wrt_id OR wr_uid = wrt_uid)
					WHERE wrt_id = %d
				) t)", LibFc::Escape($roominfo['id']), $tokenArr['wrt_id']);
				$this->B2cBase->del('wx_robot_room', $where);
			}
			if($this->wcof['wr_selfmod'] && in_array('toselfmsg', $this->wcof['wr_selfmod'])){
				$this->getSelfApiUrl(['room_id'=>$roominfo['id']], 'check');
			}
		}
		LibFc::ReturnJson(true, ['wr_id'=>$wr_id, 'wrr_id'=>$wrr_id, 'saymsg'=>'']);
	}

	/**
	  * @method 删除群
	  * @http  post
	  * @author soul 
	  * @copyright 2022/7/4
	  * @return json
	  */
	public function delRoom()
	{
		if($this->postArr['act'] == 'delRoom' && !empty($this->postArr['roomId']))
		{
			$where = sprintf(" and wrr_room_id='%s' AND wrr_room_id IN (
				SELECT * FROM (
				SELECT DISTINCT wrr_room_id FROM `wx_robot_room`
				JOIN `wx_robot` ON wrr_wr_id = wr_id
				JOIN `wx_robot_token` ON (wrt_id = wr_wrt_id OR wr_uid = wrt_uid)
				WHERE wrt_id = %d
			) t)", LibFc::Escape($this->postArr['roomId']), $this->postArr['wrt_id']);
			$this->B2cBase->del('wx_robot_room', $where);
		}
		LibFc::ReturnJson(true, ['result'=>'ok']);
	}


	/**
	  * @method 清理无效的群
	  * @http  post
	  * @author soul 
	  * @copyright 2022/7/4
	  * @return json
	  */
	public function clearRoom()
	{
		//清理数据有但是微信没有的
		$delIds = [];
		if($this->postArr['act'] == 'clearDbRoom' && isset($this->postArr['roomids']) && is_array($this->postArr['roomids']))
		{
			$wxHasArr = $this->postArr['roomids'];
			//机器人已经配置的群
			$where = sprintf(" and wr_wrt_id=%d and wr_type in ('wxgr')", $this->postArr['wrt_id']);
			$table = "wx_robot ro join wx_robot_room ON wrr_wr_id = wr_id";
			$res = $this->B2cBase->get($table, ['wrr_id,wrr_room_id'], $where);
			foreach($res['data'] as $tv)
			{
				if(!in_array($tv['wrr_room_id'], $wxHasArr))
					$delIds[] = $tv['wrr_id'];
			}
			if(!empty($delIds)) $this->B2cBase->del('wx_robot_room', sprintf(" and wrr_id in (%s)", implode(',', $delIds)));
		}
		LibFc::ReturnJson(true, ['result'=>'ok', 'del_wrr_ids'=>$delIds]);
	}

	/**
	  * @method 清理微信有的但是数据没有的
	  * @http  post
	  * @author soul 
	  * @copyright 2022/7/4
	  * @return {"status":true,"data":{"result":"ok","del_wrr_ids":[]},"code":0,"runtime":36}
	  */
	public function clearFriend()
	{
		$delIds = [];
		if($this->postArr['act'] == 'clearFriend' && isset($this->postArr['wxids']) && is_array($this->postArr['wxids']))
		{
			//机器人已经配置的微信
			$where = sprintf(" and wr_wrt_id=%d and wr_type in ('wxgr') and wrw_wx_id != ''", $this->postArr['wrt_id']);
			$table = "wx_robot join wx_robot_wx ON wrw_wr_id = wr_id";
			$res = $this->B2cBase->get($table, ['wrw_wx_id'], $where);
			$hasIdArr = array_column($res['data'], 'wrw_wx_id');
			foreach($this->postArr['wxids'] as $wxid)
			{
				if(!in_array($wxid, $hasIdArr)) $delIds[] = $wxid;
			}
		}
		LibFc::ReturnJson(true, ['del_wxids'=>$delIds]);
	}


	/**
	  * @method 获取复制机器人配置的微信号和群信息
	  * @http  post
	  * @param  wr_id             string [必填] 
	  * @param  type         string [必填] wxids,wxnums,roomids
	  * @author soul 
	  * @copyright 2022/7/4
	  * @return {"status":true,"data":{"wxids":["wxid_fncwtpljs2qp22","wxid_14uqzg4626uq12"],"wxnums":["yiparts"],"roomids":["19697649452@chatroom","24807235086@chatroom"]},"code":0,"runtime":31}
	  */
	public function getRobotLink()
	{
		$arr = [];
		if(!empty($this->postArr['wr_id']) && !empty($this->postArr['type']))
		{
			$types = explode(',', $this->postArr['type']);
			if(in_array('wxids', $types))
			{
				$res = $this->B2cBase->get('wx_robot_wx', ['distinct wrw_wx_id'], sprintf(" and wrw_wr_id=%d and wrw_wx_id != ''", $this->postArr['wr_id']));
				$arr['wxids'] = array_column($res['data'], 'wrw_wx_id');
			}
			if(in_array('wxnums', $types))
			{
				$res = $this->B2cBase->get('wx_robot_wx', ['distinct wrw_wx'], sprintf(" and wrw_wr_id=%d and wrw_wx != ''", $this->postArr['wr_id']));
				$arr['wxnums'] = array_column($res['data'], 'wrw_wx');
			}
			if(in_array('roomids', $types))
			{
				$res = $this->B2cBase->get('wx_robot_room', ['distinct wrr_room_id'], sprintf(" and wrr_wr_id=%d and wrr_room_id != ''", $this->postArr['wr_id']));
				$arr['roomids'] = array_column($res['data'], 'wrr_room_id');
			}
		}
		LibFc::ReturnJson(true, $arr);
	}
	
	/**
	  * @method 设置token信息
	  * @http  post
	  * @param  wrt_id            string [必填] token id
	  * @param  wrt_loginurl      string [选填] 登录二维码
	  * @param  wrt_verify      string [选填] 1 | -1
	  * @author soul 
	  * @copyright 2022/7/4
	  * @return {"status":true,"data":true,"code":0,"runtime":31}
	  */
	public function setTokenInfo()
	{
		$setArr = [];
		foreach(['wrt_loginurl', 'wrt_verify', 'wrt_verifycode'] as $filed)
		{
			if(isset($this->postArr[$filed])) $setArr[$filed] = $this->postArr[$filed];
		}
		if(!empty($setArr))
		{
			if($setArr['wrt_loginurl']){
				$setArr['wrt_loginurl_time'] = time();
				//$setArr['wrt_sleeptime'] = date('Y-m-d H:i:s', time() + 24*3600);
			}
			$this->B2cBase->set('wx_robot_token', $setArr, sprintf(" and wrt_id=%d", $this->postArr['wrt_id']));
		}
		LibFc::ReturnJson(true, true);
	}
	
	/**
	  * @method 自定义回调链接
	  * @param  $vals            string|array [必填] LFV2A115893060506 [1,2...]
	  * @author soul 
	  * @copyright 2022/10/13
	  * @return {"status":true,"data":[1=>'mp://21ZZ8t4S7Ez2QHd',...],"code":0,"runtime":31}
		传参post
		shopid=1111

		//车型、产品
		type=model|item (id类型)
		id=1,2,3...
		回传json  [{"id":1,"url":"xxx"},...]

		//车架号、号码、发动机
		type=vin|number|engine
		keyword=LFV2A115893060506
		回传json {"url":"xxx"}

		//消息中转
		type=msg
		keyword=LFV2A115893060506 刹车片 刹车盘
		room_id=5608994888@chatroom  群ID  私聊为空
		talker_id=wxid_zeznwrblhc1921 发送消息人ID 
		回传json {"saymsg":"需要回复的内容", "room_id":"xxx", "talker_id":"xxxx"}

		//群员发"修复" 这时候需要调取群接口更新群的绑定情况
		type=check
		room_id=5608994888@chatroom  群ID
		回传json {"status":"true"}
	  */
	private function getSelfApiUrl($vals, $type="model")
	{
		$arr = [];
		if(!empty($vals))
		{
			$runtimeb = microtime(true);
			$url = $this->wcof['wr_othdata']['urlget'];
			$post = is_array($this->wcof['wr_othdata']['urlpost'])? $this->wcof['wr_othdata']['urlpost']:[];
			$post['shopid'] = $this->wcof['wr_uid'];
			if(stripos($url, 'api.zjshop.com.cn') === false) $post['type'] = $type;
			if(!empty($this->wcof['wr_othdata']['urlgethead']) && stripos(implode(',', $this->wcof['wr_othdata']['urlgethead']), 'application/json')){
				if(in_array($type, ["model", "item"])){
					$post['id'] = $vals;
				}else if($type == 'msg'){
					$post = array_merge($post, $vals);
				}else{
					$post['keyword'] = $vals;
				}
				$html = $this->curlJson($url, json_encode($post, JSON_UNESCAPED_UNICODE));
			}else{
				if(in_array($type, ["model", "item"])){
					$post['id'] = implode(',', $vals);
				}else if($type == 'msg'){
					$post = array_merge($post, $vals);
				}else{
					$post['keyword'] = $vals;
				}
				$LibHttp = new LibHttp();
				$LibHttp->timeout = 20;
				$html = $LibHttp->fetch($url, $post);
			}
			$resArr = json_decode($html, true);
			if(!empty($resArr['result']) && is_array($resArr['result'])){
				$arr = array_column($resArr['result'], 'url', 'id');
			}else if(!empty($resArr[0]['id'])){
				$arr = array_column($resArr, 'url', 'id');
			}else{
				$arr = $resArr;
			}
			/*$runtime = ceil((microtime(true) - $runtimeb)*1000);
			$file = mvc::$cfg['LOGS'].'getSelfApiUrl.log';
			$LibLog = new LibLog();
			$LibLog->write($url.'=>'.json_encode($post, JSON_UNESCAPED_UNICODE).'=>'.$runtime.'ms=>'.$html, $file);*/
		}
		return $arr;
	}

	function curlJson($url, $json)
	{
		$curl = curl_init();
		curl_setopt_array($curl, array(
		   CURLOPT_URL => $url,
		   CURLOPT_RETURNTRANSFER => true,
		   CURLOPT_ENCODING => '',
		   CURLOPT_MAXREDIRS => 10,
		   CURLOPT_TIMEOUT => 20,
		   CURLOPT_FOLLOWLOCATION => true,
		   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		   CURLOPT_CUSTOMREQUEST => 'POST',
		   CURLOPT_POSTFIELDS =>$json,
		   CURLOPT_HTTPHEADER => array(
			  'Content-Type: application/json'
		   ),
		));
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
	}
	


	/**
	  * @method 获取通知
	  * @http  post
	  * @author soul 
	  * @copyright 2022/7/4
	  * @return json
	  */
	public function getNotice()
	{
		$arr = [];
		if($this->postArr['wrt_id'])
		{
			$res = $this->B2cBase->get('wx_robot_notice', ['wrn_id, wrn_room_id, wrn_talker_id'], sprintf(" and wrn_status=0 and wrn_wrt_id=%d", $this->postArr['wrt_id']));
			$arr = $res['data'];
		}
		LibFc::ReturnJson(true, $arr);
	}

	public function needVerifyCode()
	{
		$res = $this->B2cBase->set('wx_robot_token', ['wrt_verify'=>1, 'wrt_verifycode'=>''], sprintf(" and wrt_id=%d and wrt_verify !=1 limit 1", $this->postArr['wrt_id']), true);
		LibFc::EchoJson($res);
	}

	public function getVerifyCode()
	{
		$res = $this->B2cBase->get('wx_robot_token', ['wrt_id, wrt_verify, wrt_verifycode'], sprintf(" and wrt_id=%d limit 1", $this->postArr['wrt_id']), true);
		LibFc::EchoJson($res);
	}

	public function showKeyword($keyword)
	{
		return strtr($keyword, [' '=>' ', "\r"=>' ', "\n"=>' ', '\t'=>'']);
	}

	public function addNotice()
	{
		if($this->postArr['wrt_id'] && $this->postArr['wrn_talker_id'] && $this->postArr['wrn_info']){
			$add = [
				'wrn_wrt_id'=>$this->postArr['wrt_id'],
				'wrn_talker_id'=>$this->postArr['wrn_talker_id'],
				'wrn_info'=>$this->postArr['wrn_info'],
				'wrn_unikey'=>md5($this->postArr['wrt_id'].$this->postArr['wrn_talker_id'].$this->postArr['wrn_info']),
				'wrn_atime'=>time()
			];
			$res = $this->B2cBase->add('wx_robot_notice', $add);
			LibFc::EchoJson($res);
		}
		LibFc::ReturnJson(true, []);
	}
}