<?php
/**
*rca接口
*/
class rcaAction extends baseAction
{
	
	/**
	  * @method get  号码搜索
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  word			   string [必填] 号码
	  * @param  type               string [必填] yp,tcd,aaia
	  * @author soul
	  * @copyright 2017/9/30
	  * @return 
	  {"status":true,"data": [],"code":""}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function searchNumber()
	{
		$proArr = [];
		$formatNum = LibFc::FormatNum($_GET['word']);
		if(strlen($formatNum) > 2)
		{
			$formatNumArr = LibFc::SearchNum($formatNum);
			$typeArr =  empty($_GET['type']) ? ['yp', 'tcd','aaia']: explode(',', $_GET['type']);
			$proArr = [];
			foreach($typeArr as $type)
			{
				switch($type)
				{
					case 'yp':
						$YpsBase = new YpsBase();
						$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.pid, n.display, factory'];
						$res = $YpsBase->get($table, $filed, $where);
						if(!empty($res['data']))
						{
							$YpsProduct = new YpsProduct();
							$tres = $YpsProduct->getAnyProductInfo(array_column($res['data'], 'pid'));
							$proArr[$type] = $tres['data'];
							foreach($res['data'] as $v)
							{
								$proArr[$type][$v['pid']]['num'] = [['factory'=>$v['factory'], 'display'=>$v['display']]];
							}
						}
					break;
					case 'tcd':
						$maxCount = 50;
						$TcdmArt = new TcdmArt();
						$table =  "tof_articles
						 join tof_suppliers on sup_id = art_sup_id 
						 left join ms_ga_sup_seq on gss_sup_id=art_sup_id and art_ga_id = gss_ga_id";
						$where = sprintf(" and art_id in (select distinct arl_art_id from tof_article_number where arl_format in ('%s')) order by gss_seq, sup_brand limit %d",implode("','", $formatNumArr), $maxCount);
						$res = $TcdmArt->get($table, ['art_id'], $where);
						if(!empty($res['data']))
						{
							$artArr = array_column($res['data'], 'art_id');
							$res = $TcdmArt->getProductInfo($artArr, ['para']);
							$proArr[$type] = $res['data'];
						}
					break;
					case 'aaia':
						$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.pid, n.display, factory'];
						$res = $AaiaBase->get($table, $filed, $where);
						if(!empty($res['data']))
						{
							$AaiaProduct = new AaiaProduct();
							$tres = $AaiaProduct->getAnyProductInfo(array_column($res['data'], 'pid'), ['para']);
							$proArr[$type] = $tres['data'];
							foreach($res['data'] as $v)
							{
								$proArr[$type][$v['pid']]['num'] = [['factory'=>$v['factory'], 'display'=>$v['display']]];
							}
							$where = sprintf(" and n.pid in (%s) and n.ismain=1 and n.format not in ('%s') group by n.pid", implode(',', array_keys($proArr[$type])), implode("','", $formatNumArr));
							$res = $AaiaProduct->get('yp_number AS n JOIN yp_factory AS fac ON fac.fid = n.fid', ['n.pid, n.display, factory'], $where);
							foreach($res['data'] as $v)
							{
								$proArr[$type][$v['pid']]['num'][] = ['factory'=>$v['factory'], 'display'=>$v['display']];
							}
						}
					break;
				}
			}
			foreach($proArr as $type=>$v)
			{
				$proArr[$type] = array_values($v); 
			}
		}
		LibFc::ReturnJson(true, $proArr);
	}



	/**
	  * @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;
			}
		}
		LibFc::ReturnJson(true, $proArr);
	}



	/**
	  * @method get  RCA通过品牌ID获取所有车型
	  * @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 [选填] 末级车型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 rcaModelByBrandId()
	{
		$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']))
		{
			$where = sprintf(" AND m3_id=%d", (int) $_GET['m3_id']);
		}

		$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 = [];
		foreach($modelArr as $v)
		{
			$arr[] = $v;
		}
		LibFc::ReturnJson(true, $arr);
	}


	/**
	  * @method get RCA软件的 VIN解码 
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  vin                string [必填] 17位车架号
	  * @author soul
	  * @copyright 2017/10/31
	  * @return 末级车型ID
	  {"status":true,"data": [6491,63,.... ],"code":""}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function rcaDecodeVin()
	{
		$Params = mvc::$URL_PARAMS;
		$vin = LibFc::FormatVin($Params['vin']);
		$YpcVin = new YpcVin();
		$res = $YpcVin->decodeVin($vin, 'm3ids');
		$arr = $res['data']['model'];
		$YpcVin->tongjiVin($vin, $res['data']['from']);
		LibFc::ReturnJson(true, $arr);
	}

	/**
	  * @method get RCA软件的通过OE查找宜配车型库的适用车型
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  number             string [必填] OE号码
	  * @author soul
	  * @copyright 2017/10/31
	  * @return  末级车型ID
	  {"status":true,"data": [{"m3_id":"6491", "b_id":"63"},.... ],"code":""}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function rcaModelByNumber()
	{
		$returnArr = [];
		$number = LibFc::FormatNum($_GET['number']);
        if (strlen($number) < 3) {
            LibFc::ReturnJson(false, '请提供正确的搜索号码'); exit;
        }
		// 通过OE查找宜配车型库的适用车型
        $oNum = new EtkNum();
        $aNum = $oNum->GetPidByNum([$number]);
        if (!$aNum['status'] || empty($aNum['data']))
		{
			//提供的搜索号码未搜索到记录
        }
		else
		{
			$sPid = $aNum['data'][$number];

			$oVin = new EtkVin();
			$aVin = $oVin->GetVinCodeByPid([$sPid]);
			if (!$aVin['status'] || empty($aVin['data']))
			{
				//提供的搜索号码未关联到Vin标识符
			}
			else
			{
				$aVin = $aVin['data'][$sPid];

				// 搜索宜配车型关联Etk标识符
				$oQuery = new YpcBase();
				$sWhere = sprintf('and mec_code in ("%s")', implode('","', $aVin));
				$aQuery = $oQuery->Get('yp_model3_etk_code', ['mec_m3_id'], $sWhere);
				if (!$aQuery['status'] || empty($aQuery['data']))
				{
					
				}
				else
				{
					$aColumn = array_column($aQuery['data'], 'mec_m3_id');
					$oModel = new YpcModel();
					$sWhere = sprintf('and m3_id in (%s)', implode(',', $aColumn));
					$aModel = $oModel->getModel(3, ['m3_id'], $sWhere);
					foreach($aModel['data'] as $v) 
					{
						$returnArr[] = $v['m3_id'];
					}
				}
			}
		}
		LibFc::ReturnJson(true, $returnArr);
	}


	/**
	  * @method get  RCA通过号码查询对应的factory  part
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  number             string [必填] GDB900
	  * @param  lang               string [选填] cn|en
	  * @author soul
	  * @copyright 2017/10/31
	  * @return 
	  {"status":true,"data": [{"factory":"OE", "part":"刹车片"}....],"code":""}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function rcaGetFacPartByNumber()
	{
		$number = LibFc::FormatNum($_GET['number']);
        if (strlen($number) < 3) {
            LibFc::ReturnJson(false, '请提供正确的配件号码'); exit;
        }
		$langId = isset($_GET['lang']) && $_GET['lang'] == 'en'? 2: 1;
		$YpsBase = new YpsBase();
		$table = 'yp_number AS num 
		JOIN yp_factory AS fac ON num.fid=fac.fid
		JOIN yp_part AS pa ON num.partid=pa.partid
		JOIN yp_lng_des AS ld ON ld.desid=pa.desid AND ld.lngid='.$langId.'
		JOIN yp_lng_text AS lt ON lt.txtid=ld.txtid';
		$res = $YpsBase->get($table, ['fac.factory, lt.txt AS part'], sprintf(" and num.format='%s' GROUP BY num.fid, num.partid, num.format", LibFc::Escape($number)));
		LibFc::ReturnJson(true, $res);
	}

	
	/**
	  * @method  RCA查询宝马号码的替换关系
	  * @http  POST
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  number             string [必填] 33207572424  多个逗号分隔
	  * @author soul
	  * @copyright 2019/11/23 
	  * @return {"status":true,"data":{"33207572424":[["取代","33217559076","(26.09.2005 ~ 10.04.2007)"]]},"code":0}
	  */
	public function rcaGetBmwNumberReplace()
	{
		$arr = [];
		$numArr = [];
		foreach(explode(',', $_POST['number']) as $num)
		{
			$num = LibFc::FormatNum($num);
			if(strlen($num) > 3)
				$numArr[$num] = $num;
		}
		if(!empty($numArr))
		{
			$BaseDb = new BaseDb(mvc::$cfg['DB']['YPREAL']);
			$table = 'data_product a JOIN data_product_param b ON a.pro_id = b.pma_pro_id';
			$res = $BaseDb->get($table, ['pro_realoem', 'pma_value'], sprintf(" and a.pro_etk_id = 2 AND b.pma_lab_id = 4 and pro_realoem in ('%s')", implode("','", $numArr)));
			foreach($res['data'] as $v)
			{
				$v['pma_value'] = json_decode($v['pma_value']);
				if(is_array($v['pma_value']) && count($v['pma_value']) > 1)
				{
					foreach($v['pma_value'] as $kk=>$vv)
					{
						if($kk > 0) $arr[$v['pro_realoem']][] = $vv;
					}
				}
			}
		}
		LibFc::ReturnJson(true, $arr);
	}



	/**
	  * @method 获取北美车型库
	  * @http  get
	  * @param  token              string [必填] 调用接口凭证 (post|get)			
	  * @author soul
	  * @copyright 2020/7/18
	  * @return 文件下载  aaiaMOdel.json
	  */
	public function getAiaaModel()
	{
		ini_set('memory_limit', '512M');
		set_time_limit(0);
		$file = mvc::$cfg['PATH_CACHE'].'aaiaMOdel.php';
		$arr = [];
		//缓存1小时
		if(!file_exists($file) || (filemtime($file) < (time()-3600)))
		{
			$AaiaBase = new AaiaBase();
			$table = '`yp_aaia_model3` AS m3
			JOIN `yp_aaia_model2` AS m2 ON m3.`model2_id`= m2.`model2_id`
			JOIN `yp_aaia_model1` AS m1 ON m3.`model1_id`= m1.`model1_id`
			JOIN `yp_make` AS m ON m3.`make_id` = m.`make_id`';
			$filed = ['m.`make_id`, m.name AS make_name, m1.`model1_id` AS mod1_id, m1.name AS mod1_name, m2.`model2_id` AS mod2_id, m2.name AS mod2_name, m2.start_year AS mod2_start_year, m2.end_year AS mod2_end_year, m3.`model3_id` AS mod3_id, m3.name AS mod3_name,  m3.start_year AS mod3_start_year, m3.end_year AS mod3_end_year'];
			$res = $AaiaBase->get($table, $filed, 'ORDER BY make_name, mod1_name, mod2_name, mod3_name, mod3_start_year');
			$arr = $res['data'];
			LibFc::ArraySave($arr, $file);
		}
		else
		{//括起来为了防止读取文件失败
			$arr = include($file);
		}
		header("Content-type:application/octet-stream");
		header('Content-Disposition: attachment;filename="aaiaMOdel.json"');
		header('Cache-Control: max-age=0');
		echo json_encode($arr);
	}


	/**
	  * @method 通过OE查找北美车型库的适用车型
	  * @http  POST
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  number             string [必填] OE号码,多个号码英文逗号分隔
	  * @author soul
	  * @copyright 2020/7/18
	  * @return  {"status":true,"data":["1314553","1441443"],"code":0,"runtime":30}
	  */
	public function rcaAiaaModelByNumber()
	{
		$arr = [];
		$numArr = [];
		foreach(explode(',', $_REQUEST['number']) as $num)
		{
			$num = LibFc::FormatNum($num);
			if(strlen($num) > 3)
				$numArr[$num] = $num;
		}
		if(!empty($numArr))
		{
			$AaiaBase = new AaiaBase();
			$where = sprintf(" and pid in (select distinct pid from yp_number where format in  ('%s'))", implode("','", $numArr));
			$res = $AaiaBase->get('yp_aaia_model3_pro_link', ['DISTINCT model3_id as mod3_id'], $where);
			$arr = array_column($res['data'], 'mod3_id');
		}
		LibFc::ReturnJson(true, $arr);
	}

}