<?php
/**
* @method RCA定制接口 2023/7/12
* @http  get
* @author soul
*/
class comRcaAction extends baseAction
{
	public $comCfg = [];
	public function __construct()
	{
		parent::__construct();
		mvc::$cfg['LOGUSER']['uid'] = 8;
		mvc::$cfg['LOGUSER']['urname'] = '系统API';
		$this->comCfg = mvc::$cfg['COMAPI'][mvc::$cfg['RQTOKEN']['uid']]? : [];
	}


	/**
	  * @method get  查询车型
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  brandId            int [选填] 品牌ID
	  * @param  m_id               int [选填] 厂商ID
	  * @param  m1_id              int [选填] 一级车型ID
	  * @param  m3_id              int/string [选填] 末级车型ID 多个英文逗号分隔
	  * @author soul
	  * @copyright 2017/10/31
	  * @return 
	    'b_id', 'b_name', 品牌
		'm_id','m_name',生产商
		'm1_id','m1_name', 一级车型
		'm2_id','m2_name', 二级车型
		'm2_start_year','m2_end_year',二级车型年份
		'm3_id','m3_name', 末级车型
		'm3_start_year','m3_end_year',末级车型年份
		'm3_kw',功率
		'm3_cc',排量
		'm3_engine'发动机,
		'pl_transmission', 变速器
		'pl_fuel', 燃料
			'pl_body', 车身形式
		'pl_front_brake',前制动器
		'pl_rear_brake',后制动器
		'pl_parking_brake', 驻车制动
		'pl_drive	驱动方式
	  {"status":true,"data": ["6491"=>{"m3_id":"6491", "b_id":"63", .....},.... ],"code":""}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function getModelByBrandId()
	{
		$modelArr = [];
		if(!empty($_GET['brandId']))
		{
			$where = sprintf(" AND m1_b_id=%d", (int) $_GET['brandId']);
		}
		else if(!empty($_GET['m_id']))
		{
			$where = sprintf(" AND m_id=%d", (int) $_GET['m_id']);
		}
		else if(!empty($_GET['m1_id']))
		{
			$where = sprintf(" AND m1_id=%d", (int) $_GET['m1_id']);
		}
		else if(!empty($_GET['m3_id']))
		{
			$t = [];
			foreach(explode(',', $_GET['m3_id']) as $id){
				$t[] = (int) $id;
			}
			$where = sprintf(" AND m3_id in (%s)", implode(',', array_unique($t)));
		}
		$langId = 1;
		if($where != '')
		{
			$YpcBase = new YpcBase();
			$YpcModel = new YpcModel();
			$res = $YpcModel->getModel(3, ['*'], $where);
			if(!empty($res['data']))
			{
				$labelArr = ['m3_transmission'=>'pl_transmission', 'm3_fuel'=>'pl_fuel', 'm3_body'=>'pl_body', 'm3_front_brake'=>'pl_front_brake', 'm3_rear_brake'=>'pl_rear_brake', 'm3_parking_brake'=>'pl_parking_brake', 'm3_drive'=>'pl_drive'];
				foreach($res['data'] as $v) 
				{
					foreach($labelArr as $KK=>$vv)
					{
						$v[$vv] = $v[$KK]? $v[$KK]: '';
					}
					$modelArr[$v['m3_id']] = $v;
				}

				$returnFiledArr = ['b_id', 'b_name', 'm_id','m_name','m1_id','m1_name','m2_id','m2_name','m2_start_year','m2_end_year','m3_id','m3_name','m3_start_year','m3_end_year','m3_kw','m3_cc','m3_engine'];
				foreach($modelArr as $K=>$V)
				{
					foreach($V as $KK=>$VV)
					{
						if(!in_array($KK, $returnFiledArr) && !in_array($KK, $labelArr))
						{
							unset($V[$KK]);
						}
					}
					$modelArr[$K] = $V;
				}
			}
		}
		$arr = array_values($modelArr);
		LibFc::ReturnJson(true, $arr);
	}


	/**
	  * @method get  号码搜索
	  * @http  get
	  * @param  number			   string [必填] 号码 GDB900
	  * @author soul
	  * @copyright 2023/7/12
	  * @return {"status":true,"data":{"yp":[{"pro_id":"29620","pro_url":"http:\/\/www.yiparts.com\/alfa_romeo,brake_pad_set,0060750413,cn.html","pro_name":"刹车片(前轮)","pic":["http:\/\/www.yiparts.com\/Files\/ProFile\/Image\/000455\/58\/\/52fe0bef51551.jpg"],"num":[{"factory":"TRW","display":"GDB900"},{"factory":"OE","display":"0060 750 413"}]}]},"code":0,"runtime":371}
	  */
	public function searchNumber()
	{
		$Params = mvc::$URL_PARAMS;
		$Params = [
			'word'=>$Params['number'],
			'type'=>empty($_GET['type']) ? 'etk,yp,tcd,aaia' : $_GET['type'],
		];
		$MainZyb = new MainZyb();
		$MainZyb->addFastComZybHistory('number', $Params['word']);
		$OthNumber = new OthNumber();
		$res = $OthNumber->search($Params);
		foreach($res['data'] as $type=>$rows)
		{
			foreach($rows as $pk=>$pv)
			{
				unset($res['data'][$type][$pk]['pro_price']);
				unset($res['data'][$type][$pk]['para']);
			}
		}
		LibFc::EchoJson($res);
	}


	/**
	  * @method get  通过号码获取适用汽车品牌
	  * @http  get
	  * @param  number			   string [必填] 号码 11138616793
	  * @author soul
	  * @copyright 2023/7/12
	  * @return {"status":true,"data":["4189","21007","6288"],"code":"","runtime":97}
	  */
	public function getNumberModelBrand()
	{
		$Params = mvc::$URL_PARAMS;
		$EtkNum = new EtkNum();
		$res = $EtkNum->getModelByNumber($Params['number'], 'all');
		$arr = [];
		if(!empty($res['data'])){
			$Ypc2Model = new Ypc2Model();
			$res = $Ypc2Model->getModel(3, ['brand_name'], sprintf(" and mod3_id in (%s) group by brand_id", implode(',', $res['data'])));
			$arr = array_column($res['data'], 'brand_name');
        }
		LibFc::ReturnJson(true, $arr);
	}


	/**
	  * @method get  号码的零件名称
	  * @http  get
	  * @param  number			   string [必填] 号码 GDB900
	  * @author soul
	  * @copyright 2023/7/12
	  * @return 
	  */
	public function getNumberPart()
	{
		$arr = [];
		$Params = mvc::$URL_PARAMS;
		$formatNum = LibFc::FormatNum($Params['number']);
		$formatNumArr = LibFc::SearchNum($formatNum);
		if(strlen($formatNum) > 2)
		{
			$typeArr = ['yp', 'tcd', 'etk', 'aaia'];
			foreach($typeArr as $type)
			{
				switch($type)
				{
					case 'etk':
						$EtkBasic = new EtkBasic();
						$res = $EtkBasic->Get('data_product_search JOIN data_product ON src_pro_id = pro_id AND pro_etk_id = src_etk_id', ['DISTINCT pro_name part_name'], sprintf(" and src_format in ('%s')", implode("','", $formatNumArr)));
						if(!empty($res['data'])){
							$arr[$type] = array_column($res['data'], 'part_name');
						}
					break;
					case 'yp':
						$YpsBase = new YpsBase();
						$table = 'yp_number AS num 
						JOIN yp_part AS pa ON num.partid=pa.partid
						JOIN yp_lng_des AS ld ON ld.desid=pa.desid AND ld.lngid=1
						JOIN yp_lng_text AS lt ON lt.txtid=ld.txtid';
						$res = $YpsBase->get($table, ['DISTINCT lt.txt part_name'], sprintf(" and num.format in ('%s')", implode("','", $formatNumArr)));
						if(!empty($res['data'])){
							$arr[$type] = array_column($res['data'], 'part_name');
						}
					break;
					case 'tcd':
						$TcdmArt = new TcdmArt();
						$ignoreSupId = [0, 11404];
						$table = 'tof_article_number
						join tof_articles on arl_art_id = art_id
						join tof_generic_articles on ga_id = art_ga_id';
						$where =  sprintf(" and arl_format in ('%s') and art_sup_id not in (%s)", implode("','", $formatNumArr), implode(',', $ignoreSupId));
						$res = $TcdmArt->get($table, ['DISTINCT ga_name_cn part_name'], $where);
						if(!empty($res['data'])){
							$arr[$type] = array_column($res['data'], 'part_name');
						}
					break;
					case 'aaia':
						$AaiaBase = new AaiaBase();
						$table = 'yp_number AS n
						join yp_part as pa on n.partid = pa.partid';
						$where = sprintf(" and n.format in ('%s')", implode("','", $formatNumArr));
						$res = $AaiaBase->get($table, ['DISTINCT pa.name part_name'], $where);
						if(!empty($res['data'])){
							$arr[$type] = array_column($res['data'], 'part_name');
						}
					break;
				}
			}
		}
		LibFc::ReturnJson(true, $arr);	
	}



	/**
	  * @method  获取007的接口数据
	  * @http  post
	  * @param  apiurl			   string[必填] 不需要完整路径 /api/parts/baseinfo
	  * @param  其他参数1		         [选填] 参考007的接口文档
	  * @param  其他参数2		         [选填] 参考007的接口文档
	  * @param  其他参数3...		     [选填] 参考007的接口文档
	  * @author soul
	  * @return 
	  */
	public function getOth7Api()
	{
		$Params = $_POST;
		$apiurl = $Params['apiurl'];
		if(empty($apiurl)) LibFc::ReturnJson(false, '请提供apiurl参数');
		unset($Params['apiurl']);
		$Oth007 = new Oth007();
		$res = $Oth007->getApi($apiurl, $Params, mvc::$cfg['RQTOKEN']['comname']);
		LibFc::EchoJson($res);
	}

	/**
	  * @method  机器人车架号纠错
	  * @http  post
	  * @param  vin	     string[必填] 车架号
	  * @param  keyword	 string[必填] 发出纠错时发出的文字信息
	  * @param  talkerId string[必填] 微信ID
	  * @param  roomId string[必填] 群ID
	  * @author soul
	  * @return 
	  */
	public function addVinJiuCuo()
	{
		$Params = $_POST;
		$YpwVin = new YpwVin();
		$res = $YpwVin->addVinJiuCuo($Params['vin'], $Params['keyword'], $Params['talkerId'], $Params['roomId']);
		LibFc::EchoJson($res);
	}

	/**
	  * @method get 配件详情信息
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  proId			   int [必填] 产品ID
	  * @param  type               string [必填] etk|pjd|yp|tcd
	  * @author soul
	  * @copyright 2017/9/30
	  * @return 
	  {"status":true,"data": [],"code":""}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function itemDes()
	{
		$proArr = [];
		$proId = $_GET['proId'];
		if($proId != '' && !empty($_GET['type']))
		{
			switch($_GET['type'])
			{
				case 'yp':
					$proId = (int) $proId;
					$YpsProduct = new YpsProduct();
					$res = $YpsProduct->getAnyProductInfo([$proId], ['picAll', 'model']);
					if(!empty($res['data']))
						$proArr = $res['data'][$proId];
				break;
				case 'tcd':
					$TcdmArt = new TcdmArt();
					$res = $TcdmArt->getProductInfo([$proId], ['para', 'nums', 'picAll', 'model']);
					if(!empty($res['data']))
						$proArr = $res['data'][$proId];
				break;
				case 'aaia':
					$AaiaProduct = new AaiaProduct();
					$res = $AaiaProduct->getAnyProductInfo([$proId], ['para', 'nums','picAll']);
					if(!empty($res['data']))
						$proArr = $res['data'][$proId];
				break;
			}
			if(!empty($proArr['pro_url'])) $proArr['pro_url'] .= '?isfrom=SOFT';
		}
		LibFc::ReturnJson(true, $proArr);
	}

	/**
	  * @method 获取号码的替换号
	  * @http  get
	  * @param  number			   string [必填] 号码 11138616793
	  * @author soul
	  * @copyright 2025/5/16
	  * @return {"status":true,"data":[{"display":"11137634190","oe_make":"宝马","pro_name":"机油刨"},{"display":"11138616793","oe_make":"宝马","pro_name":"机油刨"}],"code":"","runtime":404}
	  */
	public function getReplaceNumber()
	{
		$params = mvc::$URL_PARAMS;
		$arr = [];
		$formatNum = LibFc::FormatNum($params['number']);
		$formatNumArr = LibFc::SearchNum($formatNum);
		if(strlen($formatNum) > 2){
			$EtkNum = new EtkNum();
			$res = $EtkNum->getReplaceNumberFull([$formatNum]);
			$arr = $res['data'];
			if(empty($arr) && strlen($formatNum) > 5){//即时采集
				try{
					$LibHttp = new LibHttp();
					$LibHttp->timeout = 5;
					$html = $LibHttp->fetch('http://crm.yiparts.com:5700/online.php?number='.$formatNum);
					$htmlArr = json_decode($html, true);
					if(is_array($htmlArr) && $htmlArr['code']){
						$res = $EtkNum->getReplaceNumberFull([$formatNum]);
						$arr = $res['data'];
					}
				}catch(Exception $e) {
					
				}
			}
			
			if(empty($arr)){
				$res = $EtkNum->get('nodata_num', ['num_format'], sprintf(" and num_format='%s'", $formatNum), true);
				if(empty($res['data'])){
					$EtkNum->add('nodata_num', ['num_format'=>$formatNum, 'num_etime'=>time()]);
				}

				$YpsProduct = new YpsProduct();
				$table = 'yp_number a 
				JOIN yp_part AS pa ON a.partid = pa.partid
				JOIN yp_lng_des AS ld ON ld.desid = pa.desid AND ld.lngid = 1
				JOIN yp_lng_text AS lt ON lt.txtid = ld.txtid
				LEFT JOIN yp_oe_make b ON a.oe_make_id = b.oe_make_id';
				$filed = ['display, b.name oe_make,  lt.txt pro_name'];
				$res = $YpsProduct->get($table, $filed, sprintf(" and fid = 770 AND pid IN (SELECT DISTINCT pid FROM `yp_number` WHERE fid = 770 AND FORMAT IN ('%s')) GROUP BY FORMAT, a.oe_make_id, a.partid", implode("','", $formatNumArr)));
				$arr = $res['data'];
			}
			if(empty($arr)){
				//tcd
				$TcdmArt = new TcdmArt();
				$table = 'tof_article_number
				JOIN tof_articles ON arl_art_id = art_id
				JOIN tof_generic_articles ON ga_id = art_ga_id
				LEFT JOIN `tof_brands` ON arl_bra_id = bra_id';
				$filed = ['arl_number display, bra_brand oe_make, ga_name_cn pro_name'];
				$res = $TcdmArt->get($table, $filed, sprintf(" and arl_kind = 3 AND arl_format IN ('%s') GROUP BY arl_format, bra_format ORDER BY COUNT(*) DESC", implode("','", $formatNumArr)));
				$arr = $res['data'];
			}

			//aaia
			if(empty($arr)){
				$AaiaBase = new AaiaBase();
				$AaiaBase = new AaiaBase();
				$where = sprintf(" and n.format in ('%s') group by n.pid", implode("','", $formatNumArr));
				$table = 'yp_number AS n JOIN yp_factory AS fac ON fac.fid = n.fid';
				$filed = ['n.display, factory'];
				$res = $AaiaBase->get($table, $filed, $where);

				$table = 'yp_number a 
				JOIN yp_part AS pa ON a.partid = pa.partid
				LEFT JOIN yp_oe_make b ON a.oe_make_id = b.oe_make_id';
				$filed = ['a.display, b.name oe_make, pa.name as pa_name'];
				$res = $AaiaBase->get($table, $filed, sprintf(" and fid = 770 AND FORMAT IN ('%s') GROUP BY FORMAT, b.name", implode("','", $formatNumArr)));
				$arr = $res['data'];
			}
		}
		LibFc::ReturnJson(true, $arr);
	}
}