<?php
/**
*宜配车型库
*/
class ypcAction extends baseAction
{
	/**
	  * @method 通过OE查找宜配车型库的适用车型
	  * @http	post
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  nums               array [必填] OE号码
	  * @author soul
	  * @copyright 2017/10/31
	  * @return  末级车型ID
	  {"status":true,"data": [11,12,.... ],"code":""}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function getM3idsByNum()
	{
		$returnArr = [];
		//通过OE查找宜配车型库的适用车型
		$YpcModel = new YpcModel();
		$res = $YpcModel->getM3idByNum($_POST['nums']);
		$returnArr = $res['data'];
		LibFc::ReturnJson(true, $returnArr);
	}

	/**
	  * @method 通过关键字获取发动机型号列表【用于输入框的自动完成】
	  * @http	get
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  word               string [必填] 发动机 至少2个字符
	  * @author soul
	  * @copyright 2019/3/19
	  * @return
	  {"status":true,"data":["BBG","BBJ"],"code":0}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function fitEngine()
	{
		$Params = mvc::$URL_PARAMS;
		$arr = [];
		$word = empty($Params['word'])? '': LibFc::FormatNum($Params['word']);
		if(strlen($word) >= 2)
		{
			$Ypc2Base = new Ypc2Base();
			$res = $Ypc2Base->get('bc_model3', ['max(mod3_engine) mod3_engine'], sprintf(" and mod3_engine_format like '%s%%' group by mod3_engine_format order by mod3_engine_format", $word));
			$arr = array_column($res['data'], 'mod3_engine');
		}
		LibFc::ReturnJson(true, $arr);
	}


	/**
	  * @method 通过发动机型号获取对应的信息
	  * @http	get
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  word               string [必填] 完整的发动机型号
	  * @author soul
	  * @copyright 2019/3/19
	  * @return
	  {"status":true,"data":[{"brand_id":"6","brand_name":"奥迪","brand_code":"AD","mod3_engine":"BBJ","mod3_kw":"160","mod3_cc":"2976","mod3_fuel":"汽油","mod3_cc_name":"3.0"},{"brand_id":"6","brand_name":"奥迪","brand_code":"AD","mod3_engine":"BBJ","mod3_kw":"162","mod3_cc":"2976","mod3_fuel":"汽油","mod3_cc_name":"3.0"}],"code":0}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function getEngineInfo()
	{
		$Params = mvc::$URL_PARAMS;
		$word = LibFc::FormatNum($Params['word']);
		$arr = [];
		if(!empty($word))
		{
			$Ypc2Base = new Ypc2Base();
			$filed = ['max(brand_id) brand_id,brand_name,max(brand_code) brand_code,max(mod3_engine) mod3_engine,mod3_kw,mod3_cc,max(mod3_fuel) mod3_fuel,max(mod3_cc_name) mod3_cc_name'];
			$whereArr = [
				 sprintf(" and mod3_engine_format = '%s'", LibFc::Escape($word)),
				 sprintf(" and mod3_engine_format like '%%%s%%'", LibFc::Escape($word)),
			];
			foreach($whereArr as $where)
			{
				$res = $Ypc2Base->get('bc_model3 join bc_brand on brand_id = mod3_brand_id', $filed, $where.' group by brand_name, mod3_kw, mod3_cc order by brand_name, mod3_kw, mod3_cc');
				if(empty($res['data'])) continue;
				$arr = $res['data'];
			}
		}
		LibFc::ReturnJson(true, $arr);
	}


	/**
	  * @method 通过发动机型号匹配车型
	  * @http	get
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  mod3_engine        string [必填] 完整的发动机型号
	  * @param  brand_id           int [必填] 品牌ID
	  * @param  mod3_kw            float [必填] 功率
	  * @param  mod3_cc            int [必填] 排量
	  * @author soul
	  * @copyright 2019/3/19
	  * @return
	  {"status":true,"data":[{"brand_id":"6","brand_etk_id":"10","brand_code":"AD","make_show_brand":0,"brand_name":"奥迪","make_name":"一汽奥迪","mod1_name":"A4","mod2_name":"A4(B7)","mod3_id":"1789","mod3_mod2_id":"414","mod3_mod1_id":"216","mod3_brand_id":"6","mod3_make_id":"34","mod3_name":"3.0L","mod3_start_year":"2005","mod3_end_year":"2006","mod3_kw":"160","mod3_cc":"2976","mod3_engine":"BBJ","mod3_transmission":"6A\/MT","mod3_fuel":"汽油","mod3_body":"4门5座三厢车","mod3_front_brake":"通风盘式","mod3_rear_brake":"盘式","mod3_parking_brake":"手刹","mod3_drive":"前置四驱","mod3_keyword":"BBJ3.0L","mod3_cc_name":"3.0"},...],"code":0}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function getModelByEngine()
	{
		$Params = mvc::$URL_PARAMS;
		$arr = [];
		if(!empty($Params['mod3_engine']) && !empty($Params['brand_id']) && !empty($Params['mod3_kw']) && isset($Params['mod3_cc']))
		{
			$where = sprintf(" and mod3_engine_format = '%s' and brand_id=%d and mod3_kw='%s' and mod3_cc=%d",
				LibFc::FormatNum($Params['mod3_engine']), (int) $Params['brand_id'], (float) $Params['mod3_kw'], (int) $Params['mod3_cc']);
			$Ypc2Model = new Ypc2Model();
			$filed = ['brand_id', 'brand_etk_id', 'brand_code', 'make_show_brand', 'brand_name', 'make_name', 'mod1_name', 'mod2_name', 'bc_model3.*'];
			$res = $Ypc2Model->getModel(3, $filed, $where);
			$arr = $res['data'];
		}
		LibFc::ReturnJson(true, $arr);
	}


	/**
	  * @method 通过工信部型号、VIN1-8查找车型信息
	  * @http	post
	  * @param  token             string [必填] 调用接口凭证 (post|get)
	  * @param  gxbcode           string [必填] 工信部型号
	  * @param  vin               string [必填] 车架号
	  * @author soul
	  * @copyright 2017/10/31
	  * @return 
	  */
	public function getGxbcodeInfo()
	{
		$Params = MVC::$URL_PARAMS;
		$YpcBase = new YpcBase();
		$where = sprintf(" and mg_code = '%s'", LibFc::Escape($Params['gxbcode']));
		if(!empty($Params['vin'])) $where .=  sprintf(" and vin_full = '%s'", substr(LibFc::FormatVin($Params['vin']), 0, 8));
		$table = 'yp_model3
			JOIN yp_model2 ON m3_m2_id = m2_id
			JOIN yp_model1 ON m2_m1_id = m1_id
			JOIN yp_brand ON m1_b_id = b_id
			JOIN yp_model3_gxb_num ON  mg_m3_id = m3_id 
			JOIN yp_vin_model3_link ON vm3_m3_id = m3_id
			LEFT JOIN yp_model3_size ON m3s_m3_id = m3_id
			JOIN yp_vin ON  vin_id = vm3_vin_id ';
		$filed = ['m3_vin_demo sma_vin, b_name sma_brand, m3_kw sma_kw, m3_cc sma_cc, m3_engine sma_engine,m3s_length sma_length,m3s_width sma_width, m3s_height sma_height, m3_weight sma_weight'];
		$res = $YpcBase->get($table, $filed, $where.' limit 1', true);
		LibFc::EchoJson($res);
	}



	/**
	  * @method get  通过号码反查宜配车型号码表的适用车型
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  nums               array [必填] [
												[
	  												'factory'=>'OE',
	  												'display'=>'123-456-789'
												]...
											]
	  * @param  spartId               string [必填] 商城分类ID								
	  * @author soul
	  * @copyright 2017/9/30
	  * @return 
	  {"status":true,"data": [],"code":""}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function getModelByYpcNum()
	{
		$YpcModel = new YpcModel();
		//$res = $YpcModel->getModelByYpcNum($_POST['nums'], $_POST['spartId']);
		//2020/5/9
		$res = $YpcModel->getM3idByNum($_POST['nums'], $_POST['spartId']);
		LibFc::EchoJson($res);
	}

	/**
	  * @method 车型的号码参数
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  m3ids              array [必填] [1,2,3...]
	  * @param  nums               array [必填] [
												[
	  												'factory'=>'OE',
	  												'display'=>'123-456-789'
												]...
											]
	  * @param  spartId               string [必填] 商城分类ID		
	  * @author soul
	  * @copyright 2016/3/30
	  * @return 
	  */
	public function getModelNumberPara()
	{
		$YpcModel = new YpcModel();
		$res = $YpcModel->getModelNumberPara($_POST['m3ids'], $_POST['nums'], $_POST['spartId']);
		LibFc::EchoJson($res);
	}



	/**
	  * @method 获取车型的常用分类
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  mod3_id        int [必填] 宜配车型ID
	  * @author soul
	  * @copyright 2019/9/20
	  * @return { "status": true, "data": [ { "spartid": "4021_4960", "part_name": "前刹车片", "part_img": "http://192.168.1.115:8096/static/images/spart/4021_4960.jpg"}, ...],"code": 0}
	  */
	public function getModelCyjSpart()
	{
		$Params = mvc::$URL_PARAMS;
		$arr = [];
		$mod3_id = (int) $Params['mod3_id'];
		if($mod3_id > 0)
		{
			$spartIdArr = [];
			$YpcBase = new YpcBase();
			$res = $YpcBase->Get('yc_part', ['part_partid_b2c as spartid, part_name'], " order by part_seq and part_partid_b2c!=''");
			$partArr = array_column($res['data'], null, 'spartid');

			//车型库号码
			$table = 'yc_number 
			JOIN yc_part ON num_part_id = part_id 
			JOIN yc_number_match ON num_fac_id = nm_num_fac_id AND num_format = nm_num_format AND num_part_id = nm_num_part_id';
			$res = $YpcBase->Get($table, ['DISTINCT part_partid_b2c'], sprintf(" and num_m3_id = %d", $mod3_id));
			$spartIdArr = array_column($res['data'], 'part_partid_b2c');
			
			//商城
			$B2cBase = new B2cBase();
			$table = sprintf("bc_product_model3_link 
			join bc_product on pml3_pro_id=pro_id and pro_show_pjl =1 and pro_status =1
			join sh_shop on pro_shop_id=shop_id and shop_status = 1", $shopid, time(), time());
			$where = sprintf(" and pml3_mod3_id = %d and concat(pro_part_id, '_', pro_pas_id) in ('%s')", $mod3_id, implode("','", array_keys($partArr)));
			$res = $B2cBase->get($table, ["distinct concat(pro_part_id, '_', pro_pas_id) as spartid"], $where);
			$spartIdArr = array_merge($spartIdArr, array_column($res['data'], 'spartid'));
			foreach($partArr as $k=>$v)
			{
				if(in_array($k, $spartIdArr))
				{
					$v['part_img'] = mvc::$cfg['urls']['b2c'].'static/images/spart/'.$v['spartid'].'.jpg';
					$arr[] = $v;
				}
			}
		}
		LibFc::ReturnJson(true, $arr);
	}


	/**
	  * @method 获取车型的某常用分类的配件列表
	  * @http  GET
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  mod3_id        int [必填] 宜配车型ID
	  * @param  spartid        string [必填] 商城子分类ID
	  * @author soul
	  * @copyright 2019/9/20
	  * @return {"status":true,"data":{"cankao":[{"base":{"num_id":"65601","num_info":""},"items":[{"type":"yp","pro_id":"58682","pro_url":"http:\/\/www.yiparts.com\/mercedes_benz,brake_pad_set,0054200820,cn.html","pro_name":"刹车片(前轮)","pic":["http:\/\/www.yiparts.com\/Files\/ProFile\/Image\/000455\/25\/\/52fe25849e890.jpg"],"num":[{"factory":"OE","display":"007420 55 20"}],"pro_price":{"title":"销售价","price":"0.00"},"para":[{"name":"位置","val":"前轮","unit":""},{"name":"制动系统","val":"TRW","unit":""},{"name":"宽度","val":"146.2","unit":"mm"},{"name":"高度","val":"71.5","unit":"mm"},{"name":"厚度","val":"20.6","unit":"mm"}],"parastr":""},...],"pjd":[{"pro_id":"119802","prb_name":"FREY","pro_status":"1","pro_name":"FREY(菲尔)品牌奔驰W204 W212 E200 E220 E250A207前刹车片","pro_shop_id":"224467","pro_sale_price":"600.00","pro_count":"128","pro_user_discount":"Y","pro_sold_count":"0","pro_part_id":"4021","pri_code":"745505401","pri_weight":"0.000","pri_frt_id":"2199","pro_sel_des":"","pri_invoice":"0","pri_warranty":"1","pri_return_promise":"1","price":"600.00","price_type":1,"pro_price":{"title":"销售价","price":"600.00"},"pic":[],"num":[{"factory":"FREY","display":"745505401"},{"factory":"OE","display":"0054200820"}]},...]},"code":0}
	  */
	public function getModelCyjSpartItem()
	{
		$Params = mvc::$URL_PARAMS;
		$arr = [];
		$mod3_id = (int) $Params['mod3_id'];
		$spartid = LibFc::Escape($Params['spartid']);
		if($mod3_id > 0 && $spartid != '')
		{
			//车型库号码
			$YpcBase = new YpcBase();
			$table = 'yc_number 
			JOIN yc_part ON num_part_id = part_id 
			JOIN yp_factory ON fac_id = num_fac_id
			JOIN yc_number_match ON num_fac_id = nm_num_fac_id AND num_format = nm_num_format AND num_part_id = nm_num_part_id';
			$res = $YpcBase->Get($table, ['num_id, num_info, fac_name, num_display, nm_type, nm_pro_id'], sprintf(" and num_m3_id = %d and part_partid_b2c='%s' order by nm_seq", $mod3_id, $spartid));
			if(!empty($res['data']))
			{
				$typeProArr = [];
				$tempProArr = [];
				$allProArr = [];
				$dataType = ['para'];
				$sdFlag = false;
				foreach($res['data'] as $v)
				{
					$typeProArr[$v['nm_type']][] = $v['nm_pro_id'];
					$tempProArr[$v['num_id']]['base'] = ['num_id'=>$v['num_id'], 'num_info'=>$v['num_info'], 'fac'=>$v['fac_name'], 'display'=>$v['num_display']];
					$tempProArr[$v['num_id']]['items'][] = ['type'=>$v['nm_type'], 'pro_id'=>$v['nm_pro_id']];
					
					//胜地特殊处理 2020/5/7
					if(!$sdFlag && stripos($spartid, '2996_') === 0)
					{
						$sdFlag = true;
						$B2cBase = new B2cBase();
						$table = sprintf("bc_product_model3_link 
						join bc_product on pml3_pro_id=pro_id and pro_show_pjl =1 and pro_status =1
						join sh_shop on pro_shop_id=shop_id and shop_status = 1 and shop_id=226678", $shopid, time(), time());
						$where = sprintf(" and pml3_mod3_id = %d and concat(pro_part_id, '_', pro_pas_id) = '%s'", $mod3_id, $spartid);
						$res = $B2cBase->get($table, ["distinct pro_id"], $where);
						if(!empty($res['data']))
						{
							$B2cProduct = new B2cProduct();
							$res = $B2cProduct->getAnyProductInfo(array_column($res['data'], 'pro_id'), $Params['uid'], ['picMain','numMain', 'para'], $mod3_id);
							foreach($res['data'] as $pjdv)
							{
								$tempProArr[$v['num_id']]['items'][] = ['type'=>'pjd', 'pro_id'=>$pjdv['pro_id']];
								$allProArr['pjd'][$pjdv['pro_id']] = $pjdv;
							}
						}
					}
				}

				foreach($typeProArr as $type=>$proIdArr)
				{
					switch($type)
					{
						case 'yp':
							$YpsProduct = new YpsProduct();
							$res = $YpsProduct->getAnyProductInfo($proIdArr, $dataType);
							$allProArr[$type] = $res['data'];
						break;
						case 'tcd':
							$TcdmArt = new TcdmArt();
							$res = $TcdmArt->getProductInfo($proIdArr, $dataType, $mod3Id);
							$allProArr[$type] = $res['data'];
						break;
						case 'aaia':
							$AaiaProduct = new AaiaProduct();
							$res = $AaiaProduct->getAnyProductInfo($proIdArr, $dataType);
							$allProArr[$type] = $res['data'];
						break;
						case 'zhipei':
							$OthProduct = new OthProduct();
							$res = $OthProduct->getZhipeiAnyProductInfo($proIdArr, $dataType);
							$allProArr[$type] = $res['data'];
						break;
						default:
							if(stripos($type, 'oth') === 0)
							{
								$OthProduct = new OthProduct();
								$res = $OthProduct->getOthSiteAnyProductInfo($type, $proIdArr, $dataType);
								$allProArr[$type] = $res['data'];
							}
						break;
					}
				}

				foreach($tempProArr as $numId=>$tv)
				{
					if(count($tempProArr) < 2)
					{
						$tv['base']['fac'] = '';
						$tv['base']['display'] = '';
					}
					foreach($tv['items'] as $tkk=>$tvv)
					{
						if(!empty($allProArr[$tvv['type']][$tvv['pro_id']]))
						{
							$tpro = $allProArr[$tvv['type']][$tvv['pro_id']];
							$tv['items'][$tkk] = array_merge($tvv, $tpro);
						}
						else
						{
							unset($tv['items'][$tkk]);
						}
					}
					$tv['items'] = array_values($tv['items']);
					$tempProArr[$numId] = $tv;
				}
				$arr['cankao'] = array_values($tempProArr);
			}

			//商城
			$B2cBase = new B2cBase();
			$table = sprintf("bc_product_model3_link 
			join bc_product on pml3_pro_id=pro_id and pro_show_pjl =1 and pro_status =1
			join sh_shop on pro_shop_id=shop_id and shop_status = 1", $shopid, time(), time());
			$where = sprintf(" and pml3_mod3_id = %d and concat(pro_part_id, '_', pro_pas_id) = '%s'", $mod3_id, $spartid);
			$res = $B2cBase->get($table, ["distinct pro_id"], $where);
			if(!empty($res['data']))
			{
				$B2cProduct = new B2cProduct();
				$res = $B2cProduct->getAnyProductInfo(array_column($res['data'], 'pro_id'), $Params['uid'], ['picMain','numMain'], $mod3_id);
				if(!empty($res['data']))
				{
					$arr['pjd'] = array_values($res['data']);
				}
			}
		}
		LibFc::ReturnJson(true, $arr);
	}


	/**
	  * @method 从车架号基本表中取车架号信息
	  * @http	get
	  * @param  token              string [必填] 调用接口凭证 (post|get)
	  * @param  vin1_8             string [必填] 车架号前8
	  * @author soul
	  * @copyright 2019/3/19
	  * @return
	  {"status":true,"data":[{"brand_id":"6","brand_name":"奥迪","brand_code":"AD","mod3_engine":"BBJ","mod3_kw":"160","mod3_cc":"2976","mod3_fuel":"汽油","mod3_cc_name":"3.0"},{"brand_id":"6","brand_name":"奥迪","brand_code":"AD","mod3_engine":"BBJ","mod3_kw":"162","mod3_cc":"2976","mod3_fuel":"汽油","mod3_cc_name":"3.0"}],"code":0}
	  {"status":false,"data":'失败原因',"code":''}
	  */
	public function getVinFromBaseVin()
	{
		if(is_array($_POST['filed']) && !empty($_POST['where']))
		{
			$oneRow = isset($_POST['oneRow'])? $_POST['oneRow']: false;
			$YpwBase = new YpwBase();
			$res = $YpwBase->Get('yp_allvin_base join yp_vin_year on left(alb_vin10_11, 1) = vin_10', $_POST['filed'], $_POST['where'], $oneRow);
			echo json_encode($res);
		}
		else
		{
			LibFc::ReturnJson(false, '参数错误');
		}
	}


	/**
	  * @method 宜配产品和tcd产品的国内车型库ID
	  * @http  post
	  * @param  type  string  产品类型 yp|tcd
	  * @param  proIds array 产品ID数组
	  * @author soul 
	  * @copyright 2020/6/11
	  * @return json
	  */
	public function getItemYpcModelIds()
	{
		$arr = [];
		if(!empty($_POST['proIds']) && is_array($_POST['proIds']) && !empty($_POST['type']))
		{
			switch($_POST['type'])
			{
				case 'etk':
					
					$etkId = isset($_POST['etkId'])? (int) $_POST['etkId']: 0;
					if(!empty(mvc::$cfg['DB']['EPC'][$etkId])){
						$EpcItem = new EpcItem($etkId);
						
						foreach(array_unique($_POST['proIds']) as $proId)
						{
							
							$res = $EpcItem->getItemMod3Id($proId, $_POST['grp2_id']);
							if(!empty($res['data'])) $arr[$proId] = $res['data'];
						}
					}
				break;
				case 'yp':
					$YpsProduct = new YpsProduct();
					foreach(array_unique($_POST['proIds']) as $proId)
					{
						$res = $YpsProduct->getYpcModelId($proId);
						if(!empty($res['data'])) $arr[$proId] = $res['data'];
					}
				break;
				case 'tcd':
					$TcdmArt = new TcdmArt();
					foreach(array_unique($_POST['proIds']) as $proId)
					{
						$res = $TcdmArt->getYpcModelId($proId);
						if(!empty($res['data'])) $arr[$proId] = $res['data'];
					}
				break;
			}
		}
		LibFc::ReturnJson(true, $arr);
	}


	/**
	  * @method 通过型号更新卡车尺寸统计报表的VIN数和年份统计字段
	  * @http  post
	  * @param  gxbs  string  多个逗号分隔
	  * @author soul 
	  * @copyright 2023/5/23
	  * @return json
	  */
	public function updateKczjSizeTj()
	{
		$YpcKczj = new YpcKczj();
		$res = $YpcKczj->updateKczjSizeTj(explode(',', $_POST['gxbs']));
		LibFc::EchoJson($res);
	}

	/**
	  * @method 将型号纳入到卡车尺寸统计表
	  * @http  post
	  * @param  gxbs  string  多个逗号分隔
	  * @author soul 
	  * @copyright 2023/5/23
	  * @return json
	  */
	public function addGxbsToKczjSizeTj()
	{
		$YpcKczj = new YpcKczj();
		$res = $YpcKczj->initSizeTj(explode(',', $_POST['gxbs']));
		LibFc::EchoJson($res);
	}
}