<?php
/**
  * @method 宜配车型
  * @author soul
  * @copyright 2017/9/30
  */
class YpcModel extends YpcBase
{
	/**
	  * @method 查询车型
	  * @param  $level 1 2 3
	  * @param  $fieldArr 需要查询的字段名称数组
	  * @param  $where 查询条件
	  * @param  $oneRow true|false
	  * @author soul
	  * @copyright 2016/3/30
	  * @return array(3) { ["status"]=> bool(true) ["data"]=> $OneRow=false 二维数组 ; $OneRow=true 一维数组["code"]=> int(0) } 
	  */
	public function getModel($level, $fieldArr, $where = '', $oneRow = false)
	{
		$level = (int) $level;
		switch($level)
		{
			case 1: 
				$table = 'yp_model1
					JOIN yp_make ON m1_m_id = m_id
					JOIN yp_brand ON m1_b_id = b_id';
			break;
			case 2: 
				$table = 'yp_model2
				JOIN yp_model1 ON m2_m1_id = m1_id
				JOIN yp_make ON m1_m_id = m_id
				JOIN yp_brand ON m1_b_id = b_id';
			break;
			case 3: 
				$table = 'yp_model3
				JOIN yp_model2 ON m3_m2_id = m2_id
				JOIN yp_model1 ON m2_m1_id = m1_id
				JOIN yp_make ON m1_m_id = m_id
				JOIN yp_brand ON m1_b_id = b_id';
			break;
		}
		if($table != '')
		{
			return $this->get($table, $fieldArr, $where, $oneRow);
		}
		return LibFc::ReturnData(false, 'getModel 查询提供的参数不正确。');
	}

	/**
	  * @method 查询VIN信息
	  * @param  $fieldArr 需要查询的字段名称数组
	  * @param  $where 查询条件
	  * @param  $oneRow true|false
	  * @author soul
	  * @copyright 2016/3/30
	  * @return array(3) { ["status"]=> bool(true) ["data"]=> $OneRow=false 二维数组 ; $OneRow=true 一维数组["code"]=> int(0) } 
	  */
	public function getModel3Vin($fieldArr, $where = '', $oneRow = false)
	{
		$table = 'yp_vin_model3_link
		JOIN yp_vin ON vm3_vin_id = vin_id
		JOIN yp_model3 ON vm3_m3_id = m3_id
		JOIN yp_model2 ON m3_m2_id = m2_id
		JOIN yp_model1 ON m2_m1_id = m1_id
		JOIN yp_make ON m1_m_id = m_id
		LEFT JOIN yp_brand ON m1_b_id = b_id';
		return $this->get($table, $fieldArr, $where, $oneRow);
	}

	/**
	  * @method 查询工信部型号
	  * @param  $fieldArr 需要查询的字段名称数组
	  * @param  $where 查询条件
	  * @param  $oneRow true|false
	  * @author soul
	  * @copyright 2016/3/30
	  * @return array(3) { ["status"]=> bool(true) ["data"]=> $OneRow=false 二维数组 ; $OneRow=true 一维数组["code"]=> int(0) } 
	  */
	public function getModelGxbNum($fieldArr, $where = '', $oneRow = false)
	{
		$table = 'yp_model3_gxb_num
		JOIN yp_model3 ON mg_m3_id = m3_id
		JOIN yp_model2 ON m3_m2_id = m2_id
		JOIN yp_model1 ON m2_m1_id = m1_id
		JOIN yp_make ON m1_m_id = m_id';
		return $this->get($table, $fieldArr, $where, $oneRow);
	}

	
	/**
	  * @method 通过号码查找宜配车型库的适用车型
	  * @param  $numArr array [
							[
								'factory'=>'OE',
								'display'=>'123-456-789'
							]...
						]
	  * @param  spartId               string [选填] 商城分类ID	1111_22
	  * @author soul
	  * @copyright 2016/3/30
	  * @return array(3) { ["status"]=> bool(true) ["data"]=> [1,2,3]["code"]=> int(0) } 
	  */
	public function getM3idByNum($numArr, $spartId = '')
	{
		$m3IdArr = [];
		if(empty($numArr) || !is_array($numArr)) return LibFc::ReturnData(true, $m3IdArr);
		
		//兼容之前的版本
		foreach($numArr as $k=>$v)
		{
			if(!is_array($v))
			{
				$numArr[$k] = ['factory'=>'OE', 'display'=>$v];
			}
			else
			{
				$numArr[$k]['factory'] = strtoupper(trim($v['factory']));
			}
		}
		$res = $this->getModelByYpcNum($numArr, $spartId);
		if(!empty($res['data']))
		{
			//目录能找到车型后不再处理
			return $res;
		}
		else
		{
			$uniOeNum = [];
			foreach($numArr as $k=>$v)
			{
				if($v['factory'] != 'OE') continue;
				$formatNumArr = LibFc::SearchNum($v['display']);
				foreach($formatNumArr as $format)
				{
					$uniOeNum[$format] = $format;
				}
			}
			
			if(!empty($uniOeNum))
			{
				$EtkNum = new EtkNum();
				$res = $EtkNum->getModelByNumber(implode(',', $uniOeNum), 'all');
				$m3IdArr = array_merge($m3IdArr, $res['data']);
				/*$EtkBasic = new EtkBasic();
				$table = 'data_product_search
				JOIN data_product_vins ON  ppv_pro_id = src_pro_id AND src_etk_id = ppv_etk_id
				JOIN data_vins ON vin_id=ppv_vin_id AND ppv_etk_id = vin_etk_id';
				$res = $EtkBasic->getFieldUniVal($table, 'vin_name', sprintf('and src_format in ("%s")', implode('","', $uniOeNum)));
				if(!empty($res['data']))
				{
					$vinNameArr = $res['data'];
					$codeArr = [];
					foreach($vinNameArr as $v)
					{
						if(stripos($v, '@') > 0)
							$codeArr['modcode'] = 'modcode';
						else
							$codeArr['etkcode'] = 'etkcode';
						if(count($codeArr) == 2) break;
					}
					foreach($codeArr as $codeType)
					{
						$res = $this->getMod3IdByCode($vinNameArr, $codeType);
						$m3IdArr = array_merge($m3IdArr, $res['data']);
					}
				}*/
			}
		}
		return LibFc::ReturnData(true, array_unique($m3IdArr));
	}

	
	/**
	  * @method 通过号码匹配宜配车型库号码表的适用车型
	  * @param  $numArr array [
							[
								'factory'=>'OE',
								'display'=>'123-456-789'
							]...
						]
	  * @param  spartId               string [选填] 商城分类ID	1111_22
	  * @author soul
	  * @copyright 2016/3/30
	  * @return array(3) { ["status"]=> bool(true) ["data"]=> [1,2,3]["code"]=> int(0) } 
	  */
	public function getModelByYpcNum($numArr, $spartId = '')
	{
		if(empty($numArr) || !is_array($numArr))
		{
			return LibFc::ReturnData(false, 'getM3idByNum 查询提供的参数不正确。');
		}
		$uniNum = [];
		foreach($numArr as $k=>$v)
		{
			$v['factory'] = strtoupper(trim($v['factory']));
			$formatNumArr = LibFc::SearchNum($v['display']);
			foreach($formatNumArr as $format)
			{
				$uniNum[$v['factory'].'@'.$format] = $format;
			}
		}
		$arr = [];
		$where = sprintf(" and num_format IN ('%s')", implode("','", array_values($uniNum)));
		if(!empty($spartId))
			$where .= sprintf(" AND part_partid_b2c = '%s'", LibFc::Escape($spartId));
		$res = $this->Get('yc_number join yp_factory on fac_id = num_fac_id join yc_part on part_id = num_part_id', ['num_m3_id, fac_name, num_format'], $where);
		foreach($res['data'] as $v)
		{
			$v['fac_name'] = strtoupper(trim($v['fac_name']));
			if(!empty($v['fac_name'].'@'.$v['num_format']))
			{
				$arr[] = $v['num_m3_id'];
			}
		}
		return LibFc::ReturnData(true, array_unique($arr));
	}




	/**
	 * @method    根据车型Id获取保养件id
	 * @param     [int]       $m3id [车型id]
	 * @return    [arr]             ['status'=>true,'data'=>[['cat_id'=>1],['cat_id'=>2]]]
	 * @author lu
	 * @copyright 2019-01-08
	 */
	public function getByjByM3Id($m3id,$fiels=[],$where='')
	{
		$where.=sprintf(' and cat_m3_id=%d',$m3id);
		$fiels=!empty($fiels)?$fiels:['cat_id'];
		$res=$this->get('temp_chapeijian',$fiels,$where);
		return LibFc::ReturnData($res['status'], $res['data']);
	}


	/**
	  * @method 检查这个车型是否有EPC数据
	  * @param  mod3Id 车型ID
	  * @author soul
	  * @copyright 2017/4/13
	  * @return 
	  {"status":true,"data": [],"code":""}
	  {"status":false,"data":'失败原因',"code":'error'}
	  */
	public function checkModelPart($mod3Id)
	{
		$res=$this->getModel(3, ['b_etk_id as etk_id'], sprintf(' and m3_id=%d and b_etk_id>0 and b_etk_id<999', $mod3Id),true);
		$arr = $res['data'];
		$arr['has'] = 0;
		$etkId = $arr['etk_id'];
		if(!empty(mvc::$cfg['DB']['EPC'][$etkId]))
		{
			$res = $this->get('yp_model3_etk_code', ['distinct mec_code as mec_code'], sprintf(" and mec_m3_id=%d", $mod3Id));
			$etkCodeArr = array_column($res['data'], 'mec_code');
			//宝马特殊处理取vin 4~7位 2020/3/31
			if($etkId == 2)
			{
				$EpcItem = new EpcItem($etkId);
				$res = $EpcItem->get('data_code', ['uid_id'], sprintf(" and uid_text in('%s') limit 1", implode("','", $etkCodeArr)));
				if(empty($res['data'])){
					foreach($etkCodeArr as $k=>$v){
						$etkCodeArr[$k] = strlen($v) == 17? substr($v, 3, 4): $v;
					}
				}
			}
			if($etkId == 8){
				$res = $this->get('yp_model3_modcode', ['distinct mem_code as mem_code'], sprintf(" and mem_m3_id=%d", $mod3Id));
				$etkCodeArr = array_merge($etkCodeArr, array_column($res['data'], 'mem_code'));
			}
			$EpcItem = new EpcItem($etkId);
			$res = $EpcItem->getGroup($etkCodeArr, $mod3Id);
			$arr['has'] = empty($res['data']) ? 0: 1;
		}
		return LibFc::ReturnData(true, $arr);
	}



	/**
	  * @method 通过原厂代码或者etk代码查找的适用车型ID
	  * @param  codeArr ['aa',...]
	  * @author soul
	  * @copyright 2017/4/13
	  * @return 
	  {"status":true,"data": [11,22,333...],"code":""}
	  {"status":false,"data":'失败原因',"code":'error'}
	  */
	public function getMod3IdByCode($codeArr, $codeType = 'etkcode')
	{
		$m3IdArr = [];
		$codeArr = array_values(array_unique($codeArr));
		if(!empty($codeArr) && !empty($codeArr[0]))
		{
			$YpcBase = new YpcBase();
			if($codeType == 'modcode'){
				$res = $this->get('yp_model3_modcode', ['DISTINCT mem_m3_id'], sprintf(" and mem_code in ('%s')", implode("','", $codeArr)));
				$m3IdArr = array_unique(array_column($res['data'], 'mem_m3_id'));
				//丰田特殊
				if(empty($m3IdArr) && strlen($codeArr[0]) == 17) $codeType = 'etkcode';
			}
			
			if($codeType != 'modcode'){
				$res = $this->get('yp_model3_etk_code', ['DISTINCT mec_m3_id'], sprintf(" and mec_code in ('%s')", implode("','", $codeArr)));
				$m3IdArr = array_unique(array_merge($m3IdArr, array_column($res['data'], 'mec_m3_id')));
			}
		}
		return LibFc::ReturnData(true, $m3IdArr);
	}


	/**
	  * @method 车型的号码参数
	  * @param  modIdArr              array [必填] [1,2,3...]
	  * @param  $numArr [
							[
								'factory'=>'OE',
								'display'=>'123-456-789'
							]...
						]
	  * @param  spartId               string [必填] 商城分类ID	1111_22
	  * @author soul
	  * @copyright 2016/3/30
	  * @return array(3) { ["status"]=> bool(true) ["data"]=> [1,2,3]["code"]=> int(0) } 
	  */
	public function getModelNumberPara($modIdArr, $numArr, $spartId)
	{
		$arr = [];
		if(empty($modIdArr) || empty($numArr) || !is_array($numArr)) return LibFc::ReturnData(true, $arr);
		foreach($modIdArr as $k=>$v)
		{
			$modIdArr[$k] = (int) $v;
		}
		$modIdArr = array_unique($modIdArr);
		$uniNum = [];
		foreach($numArr as $k=>$v)
		{
			$v['factory'] = strtoupper(trim($v['factory']));
			$formatNumArr = LibFc::SearchNum($v['display']);
			foreach($formatNumArr as $format)
			{
				$uniNum[$v['factory'].'@'.$format] = $format;
			}
		}
		$where = sprintf(" and num_m3_id in (%s) AND part_partid_b2c = '%s' and num_format IN ('%s') and num_info !=''", implode(',', $modIdArr), LibFc::Escape($spartId), implode("','", array_values($uniNum)));
		$res = $this->Get('yc_number join yp_factory on fac_id = num_fac_id join yc_part on part_id = num_part_id', ['num_m3_id, fac_name, num_display, num_format, num_info'], $where);
		foreach($res['data'] as $v)
		{
			$v['fac_name'] = strtoupper(trim($v['fac_name']));
			if(!empty($v['fac_name'].'@'.$v['num_format']))
			{
				$arr['p'.$v['num_m3_id']][] = [
					'factory'=>$v['fac_name'],
					'display'=>$v['num_display'],
					'info'=>$v['num_info']
				];
			}
		}
		return LibFc::ReturnData(true, $arr);
	}


	
	/**
	  * @method 本地车型库数据同步到线上（仅车型部分）
	  * @author soul
	  * @copyright 2020/6/12
	  * @return 
	  */
	public function updateYpcModelByLocal()
	{
		//当前线上DB $this
		//本地DB
		$localBaseDb67 = new BaseDb(mvc::$cfg['DB']['YPCAR67']);
		$btime = time();
		//检查配置
		if($localBaseDb67->BaseDb->configs['db_host'] == $this->YpcDb->configs['db_host'] 
			|| stripos($this->YpcDb->configs['db_host'], '.67')
			|| stripos($this->YpcDb->configs['db_host'], '97.159')
		) return LibFc::ReturnData(false, '本地或者线上数据库配置有误');
		
		$this->YpcDb->Begin();
		//数据少的表
		$fastTableArr = ['yp_brand', 'yp_make', 'yp_model1', 'yp_model2', 'yp_vin_wmi', 'yp_model3_tcdcn_link', 'yp_model_word', 'yp_model_word_link', 'yp_image_gxb', 'yc_part'];
		foreach($fastTableArr as $table)
		{
			echo $table, '<br>';
			$locRes = $localBaseDb67->get($table, ['*']);
			$localArr = $locRes['data'];
			if(!is_array($localArr)) return LibFc::ReturnData(false, $table.' 数据记录有误，同步失败');
			if(!empty($localArr))
			{	
				//不能用 truncate table 不纳入事务
				$this->del($table, ' and 1=1');
				$this->addAny($table, array_keys($localArr[0]), $localArr);
			}
			echo (time()-$btime).'s ok', '<br>';
		}

		$fastTableArr = [
			'yp_model3'=>['pk'=>'m3_id', 'per'=>300],
			'yp_model3_etk_code'=>['pk'=>'mec_id', 'per'=>600],
			'yp_model3_gxb_num'=>['pk'=>'mg_id', 'per'=>600],
			'yp_model3_img'=>['pk'=>'m3i_id', 'per'=>600],
			'yp_model3_modcode'=>['pk'=>'mem_id', 'per'=>600],
			'yp_vin'=>['pk'=>'vin_id', 'per'=>600],
			'yp_vin_model3_link'=>['pk'=>'vm3_id', 'per'=>600],
			'zp_mod32_link'=>['pk'=>'zml_id', 'per'=>1000],
			'zp_vin_model'=>['pk'=>'zvm_id', 'per'=>100],
			'yp_model3_size'=>['pk'=>'m3s_id', 'per'=>1000],
			'yc_number'=>['pk'=>'num_id', 'per'=>1000],
		];
		foreach($fastTableArr as $table=>$cfg)
		{
			echo $table, '<br>';
			//不能用 truncate table 不纳入事务
			$this->del($table, ' and 1=1');
			for($page = 1; $page <= 10000; $page++)
			{
				$locRes = $localBaseDb67->get($table, ['*'], sprintf(" order by %s limit %d,%d", $cfg['pk'], ($page-1)*$cfg['per'], $cfg['per']));
				$localArr = $locRes['data'];
				if(!is_array($localArr)) return LibFc::ReturnData(false, $table.' 数据记录有误，同步失败');
				if(!empty($localArr))
				{	
					if($table == 'yc_number'){
						foreach($localArr as $tk=>$tv){
							if(isset($tv['num_epc']) && empty($tv['num_epc'])) $localArr[$tk]['num_epc'] = '[]';
						}
					}
					$this->addAny($table, array_keys($localArr[0]), $localArr);
				}
				else
				{
					break;
				}
			}
			echo (time()-$btime).'s ok', '<br>';
		}
		$this->YpcDb->End();
		$this->initB2cCar();
		$PjltjReport = new PjltjReport();
		$PjltjReport->updateYpcModelToTjdb();
		$LibHttp = new LibHttp();
		$LibHttp->fetch('https://admin.paojd.cn/ypcCar/updateYpcarGxbcode');
		echo '初始化商城库<br>', (time()-$btime).'s ok', '<br>';
		return LibFc::ReturnData(true, (time()-$btime).'s ok');
	}


	/**
	  * @method 重新初始化数据到商城车型库
	  * @author soul
	  * @copyright 2020/6/12
	  * @return 
	  */
	public function initB2cCar()
	{
		$btime = time();
		$mod3Arr = [];
		
		//图片mod3_imgs
		$res = $this->get('yp_model3_img', ["m3i_m3_id, m3i_img"], ' and m3i_ismain=1');
		foreach($res['data'] as $V)
		{
			$mod3Arr[$V['m3i_m3_id']]['mod3_imgs'] = mvc::$cfg['FILE_CENTER']['b2c']['url_get'].'&c=model&f='.str_replace('/small/', '/', $V['m3i_img']).mvc::$cfg['FILE_CENTER']['b2c']['get_uri'];
		}

		$res = $this->get('yp_model3_gxb_num JOIN yp_image_gxb ON gxb_code = mg_code', ["mg_m3_id, CONCAT(gxb_path, '/', gxb_name) as mod3_imgs"], 'GROUP BY mg_m3_id');
		foreach($res['data'] as $V)
		{
			if(empty($mod3Arr[$V['mg_m3_id']]['mod3_imgs']))
				$mod3Arr[$V['mg_m3_id']]['mod3_imgs'] = 'https://3thpics.paojd.cn/etk/'.$V['mod3_imgs'];
		}
		$mod3field = ['mod3_imgs'];
		$initTableArr = [
			[
				'table'=>'bc_brand',
				'fields'=>[
					'b_id'      => 'brand_id',
					'b_name'    => 'brand_name',
					'b_keyword' => 'brand_keyword',
					'b_seq'     => 'brand_seq',
					'b_code'     => 'brand_code',
					'b_initial' => 'brand_initial',
					'b_etk_id' => 'brand_etk_id',
				],
				'ftable'=>'yp_brand',
				'fwhere'=>' order by b_id'
			],
			[
				'table'=>'bc_make',
				'fields'=>[
					'm_id'      => 'make_id',
					'm_name'    => 'make_name',
					'm_keyword' => 'make_keyword',
					'm_seq'     => 'make_seq',
					'm_initial' => 'make_initial',
					'm_show_brand' => 'make_show_brand',
				],
				'ftable'=>'yp_make',
				'fwhere'=>' order by m_id'
			],
			[
				'table'=>'bc_model1',
				'fields'=>[
					'm1_id'     => 'mod1_id',
					'm1_name'    => 'mod1_name',
					'm1_b_id'   => 'mod1_brand_id',
					'm1_m_id'   => 'mod1_make_id',
					'm1_keyword'=> 'mod1_keyword',
					'm1_hasepc'=> 'mod1_hasepc'
				],
				'ftable'=>'yp_model1',
				'fwhere'=>' order by m1_id'
			],
			[
				'table'=>'bc_model2',
				'fields'=>[
					'm2_id'     => 'mod2_id',
					'm2_name'    => 'mod2_name',
					'm1_id'     => 'mod2_mod1_id',
					'm1_b_id'   => 'mod2_brand_id',
					'm1_m_id'   => 'mod2_make_id',
					'm2_start_year'=> 'mod2_start_year',
					'm2_end_year' => 'mod2_end_year',
					'm2_keyword'=> 'mod2_keyword',
					'm2_pc'=>'mod2_pc',
					'm2_cv'=>'mod2_cv',
				],
				'ftable'=>'yp_model2
						join yp_model1 on m2_m1_id = m1_id',
				'fwhere'=>' order by m2_id'
			],
			[
				'table'=>'bc_model3',
				'fields'=>[
					'm3_id'     => 'mod3_id',
					'm3_name'    => 'mod3_name',
					'm2_id'     => 'mod3_mod2_id',
					'm1_id'     => 'mod3_mod1_id',
					'm1_b_id'   => 'mod3_brand_id',
					'm1_m_id'   => 'mod3_make_id',
					'm3_start_year'=> 'mod3_start_year',
					'm3_start_month'=> 'mod3_start_month',
					'm3_end_year'=> 'mod3_end_year',
					'm3_end_month'=> 'mod3_end_month',
					'm3_kw'     => 'mod3_kw',
					'm3_cc'     => 'mod3_cc',
					'm3_cc_name' => 'mod3_cc_name',
					'm3_engine' => 'mod3_engine',
					'm3_engine_format' => 'mod3_engine_format',
					'm3_transmission'=>'mod3_transmission',
					'm3_fuel'=>'mod3_fuel',
					'm3_body'=>'mod3_body',
					'm3_front_brake'=>'mod3_front_brake',
					'm3_rear_brake'=>'mod3_rear_brake',
					'm3_parking_brake'=>'mod3_parking_brake',
					'm3_drive'=>'mod3_drive',
					'm3_drive_short'=>'mod3_drive_short',
					'm3_start_stop'=>'mod3_start_stop',
					'm3_chassis'=>'mod3_chassis',
					'm3_keyword'=> 'mod3_keyword',
					'm3_atime'=> 'mod3_atime',
					'm3_etime'=> 'mod3_etime',
				],
				'ftable'=>'yp_model3
						join yp_model2 on m3_m2_id = m2_id
						join yp_model1 on m2_m1_id = m1_id',
				'fwhere'=>' order by m3_id'
			]
		];
		
		$maxRow = 1000;
		$Ypc2Base = new Ypc2Base();
		$Ypc2Model = new Ypc2Model();
		$Ypc2Base->YPC2Db->Begin();
		
		foreach($initTableArr as $tablev)
		{
			$Ypc2Base->del($tablev['table'], ' and 1=1');
			$ypRes = $this->get($tablev['ftable'], array_keys($tablev['fields']), $tablev['fwhere']);
			$allAddData = $ypRes['data'];
			$addData = [];
			$fields = array_values($tablev['fields']);
			if($tablev['table'] == 'bc_model3')
			{
				$fields  = array_merge($mod3field, $fields);
			}
			foreach($allAddData as $dk=>$row)
			{
				$addArr = [];
				if($tablev['table'] == 'bc_model3')
				{
					foreach($mod3field as $field)
					{
						$addArr[$field] = isset($mod3Arr[$row['m3_id']][$field]) ? $mod3Arr[$row['m3_id']][$field] : '';
					}
				}
				foreach($tablev['fields'] as $kk=>$vv)
				{
					switch($vv)
					{
						case 'mod2_keyword':
							$addArr[$vv] = LibFc::formatStr($row['m2_keyword'].','.$row['m2_name'], 1);
						break;
						case 'mod3_keyword':
							$addArr[$vv] = LibFc::formatStr($row['m3_keyword'].','.$row['m3_name'], 1);
						break;
						default:
							$addArr[$vv] = $row[$kk];
						break;
					}
				}
				$addData[] = $addArr;

				if(count($addData) == $maxRow || ($dk+1) == count($allAddData))
				{
					$Ypc2Base->addAny($tablev['table'], array_unique($fields), $addData);
					$addData = [];
				}
			}
		}

		//直接复制数据
		$sqlArr = [
			"delete from yp_model_word",
			sprintf("insert into yp_model_word select * from %s.yp_model_word", $this->YpcDb->configs['db_name']),	
			"delete from yp_model_word_link",	
			sprintf("insert into yp_model_word_link select * from %s.yp_model_word_link", $this->YpcDb->configs['db_name']),
			"UPDATE `bc_brand` SET brand_pc = 1 WHERE brand_id IN (SELECT mod2_brand_id FROM `bc_model2` WHERE mod2_pc =1)",
			"UPDATE `bc_brand` SET brand_cv = 1 WHERE brand_id IN (SELECT mod2_brand_id FROM `bc_model2` WHERE mod2_cv =1)",
			"UPDATE `bc_model1` SET mod1_pc = 1 WHERE mod1_id IN (SELECT mod2_mod1_id FROM `bc_model2` WHERE mod2_pc =1)",
			"UPDATE `bc_model1` SET mod1_cv = 1 WHERE mod1_id IN (SELECT mod2_mod1_id FROM `bc_model2` WHERE mod2_cv =1)"
		];
		foreach($sqlArr as $sql)
		{
			$Ypc2Base->query($sql);
		}
		
		//底盘件模式车型
		$field = ['mod3_id, mod2_id, mod3_cc_name,mod3_engine_format, mod3_engine, mod3_kw, mod3_cc, mod3_cc_name, mod3_transmission, mod3_fuel, mod3_drive, mod3_chassis,mod3_atime,mod3_etime'];
		$mres = $Ypc2Model->getModel(3, $field, '');
		$tmodArr = [];
		$tmodMod3IdArr = [];
		$chassis = [];
		foreach($mres['data'] as $mod)
		{
			$codeby = [
				'mod2_id'=>$mod['mod2_id'],
				'mod3_engine_format'=>$mod['mod3_engine_format'],
				'mod3_kw'=>$mod['mod3_kw'],
				'mod3_cc'=>$mod['mod3_cc'],
				'mod3_transmission'=>$mod['mod3_transmission'],
				'mod3_drive'=>$mod['mod3_drive'],
			];
			ksort($codeby);
			$codeby = json_encode($codeby, JSON_UNESCAPED_UNICODE);
			$code = md5($codeby);
			if(empty($tmodArr[$code]))
			{
				$tmodArr[$code] = [
					'mch_code'=>$code,
					'mch_mod2_id'=>$mod['mod2_id'],
					'mch_engine'=>$mod['mod3_engine'],
					'mch_engine_format'=>$mod['mod3_engine_format'],
					'mch_kw'=>$mod['mod3_kw'],
					'mch_cc'=>$mod['mod3_cc'],
					'mch_cc_name'=>$mod['mod3_cc_name'],
					'mch_transmission'=>$mod['mod3_transmission'],
					'mch_drive'=>$mod['mod3_drive'],
					'mch_chassis'=>'',
					'mch_fuel'=>$mod['mod3_fuel'],
					'mch_codeby'=>$codeby,
					'mch_atime'=>$mod['mod3_atime'],
					'mch_etime'=>$mod['mod3_etime'],
				];
			}
			if(!empty($mod['mod3_chassis'])) $chassis[$code][] = $mod['mod3_chassis'];
			if($mod['mod3_atime'] < $tmodArr[$code]['mch_atime']) $tmodArr[$code]['mch_atime'] = $mod['mod3_atime'];
			if($mod['mod3_etime'] > $tmodArr[$code]['mch_etime']) $tmodArr[$code]['mch_etime'] = $mod['mod3_etime'];
			
			$tmodMod3IdArr[$code.'@'.$mod['mod3_id']] = [
				'mcm_mch_code'=>$code,
				'mcm_mod3_id'=>$mod['mod3_id']
			];
		}
		
		//车型
		$tmodArr = array_values($tmodArr);
		$Ypc2Base->del('bc_modchassis', ' and 1=1');
		$addData = [];
		foreach($tmodArr as $k=>$v)
		{
			if(!empty($chassis[$v['mch_code']])) $v['mch_chassis'] = implode(',', array_unique($chassis[$v['mch_code']]));
			$addData[] = $v;
			if($k % 1000 == 999 || ($k +1) == count($tmodArr))
			{
				$Ypc2Base->addAny('bc_modchassis', array_keys($addData[0]), $addData);
				$addData = [];
			}
		}

		//车型关联
		$tmodMod3IdArr = array_values($tmodMod3IdArr);
		$Ypc2Base->del('bc_modchassis_mod3', ' and 1=1');
		$addData = [];
		foreach($tmodMod3IdArr as $k=>$v)
		{
			$addData[] = $v;
			if($k % 1000 == 999 || ($k +1) == count($tmodMod3IdArr))
			{
				$Ypc2Base->addAny('bc_modchassis_mod3', array_keys($addData[0]), $addData);
				$addData = [];
			}
		}


		//发动机件模式车型
		$field = ['mod3_id, mod2_id, mod3_cc_name,mod3_engine_format, mod3_engine, mod3_kw, mod3_cc, mod3_cc_name, mod3_fuel,mod3_atime,mod3_etime'];
		$mres = $Ypc2Model->getModel(3, $field, '');
		$tmodArr = [];
		$tmodMod3IdArr = [];
		foreach($mres['data'] as $mod)
		{
			$codeby = [
				'mod2_id'=>$mod['mod2_id'],
				'mod3_engine_format'=>$mod['mod3_engine_format'],
				'mod3_kw'=>$mod['mod3_kw'],
				'mod3_cc'=>$mod['mod3_cc']
			];
			ksort($codeby);
			$codeby = json_encode($codeby, JSON_UNESCAPED_UNICODE);
			$code = md5($codeby);
			if(empty($tmodArr[$code]))
			{
				$tmodArr[$code] = [
					'men_code'=>$code,
					'men_mod2_id'=>$mod['mod2_id'],
					'men_engine'=>$mod['mod3_engine'],
					'men_engine_format'=>$mod['mod3_engine_format'],
					'men_kw'=>$mod['mod3_kw'],
					'men_cc'=>$mod['mod3_cc'],
					'men_cc_name'=>$mod['mod3_cc_name'],
					'men_fuel'=>$mod['mod3_fuel'],
					'men_codeby'=>$codeby,
					'men_atime'=>$mod['mod3_atime'],
					'men_etime'=>$mod['mod3_etime'],
				];
			}

			if($mod['mod3_atime'] < $tmodArr[$code]['men_atime']) $tmodArr[$code]['men_atime'] = $mod['mod3_atime'];
			if($mod['mod3_etime'] > $tmodArr[$code]['men_etime']) $tmodArr[$code]['men_etime'] = $mod['mod3_etime'];

			$tmodMod3IdArr[$code.'@'.$mod['mod3_id']] = [
				'mem_men_code'=>$code,
				'mem_mod3_id'=>$mod['mod3_id']
			];
		}
		
		//车型
		$tmodArr = array_values($tmodArr);
		$Ypc2Base->del('bc_modengine', ' and 1=1');
		$addData = [];
		foreach($tmodArr as $k=>$v)
		{
			$addData[] = $v;
			if($k % 1000 == 999 || ($k +1) == count($tmodArr))
			{
				$Ypc2Base->addAny('bc_modengine', array_keys($addData[0]), $addData);
				$addData = [];
			}
		}

		//车型关联
		$tmodMod3IdArr = array_values($tmodMod3IdArr);
		$Ypc2Base->del('bc_modengine_mod3', ' and 1=1');
		$addData = [];
		foreach($tmodMod3IdArr as $k=>$v)
		{
			$addData[] = $v;
			if($k % 1000 == 999 || ($k +1) == count($tmodMod3IdArr))
			{
				$Ypc2Base->addAny('bc_modengine_mod3', array_keys($addData[0]), $addData);
				$addData = [];
			}
		}
		$Ypc2Base->YPC2Db->End();

		$Ypc2Elastic = new Ypc2Elastic();
		$Ypc2Elastic->updateItemWord();
		
		//重新初始化底盘件、发动机件模式车型的末级车型
		$LibHttp = new LibHttp();
		$LibHttp->fetch('https://admin.paojd.cn/shop/initModelByOthModType');
		
		return LibFc::ReturnData(true, (time()-$btime).'s ok');
	}


	/**
	  * @method 整理车辆的启动标识
	  * @author soul
	  * @copyright 2023/10/24
	  * @return 
	  */
	public function updateMod3StartStop($m3id = 0)
	{
		//重置自动的 UPDATE yp_model3 SET m3_start_stop = '' WHERE m3_id NOT IN (SELECT ymc_dataid FROM `yp_model_change` WHERE ymc_by ='manual' AND ymc_change->'$.m3_start_stop' IS NOT NULL)
		$localBaseDb67 = new BaseDb(mvc::$cfg['DB']['YPCAR67']);
		$CarBase = new BaseDb(mvc::$cfg['DB']['CARLOC']);
		
		if(empty($m3id)){
			//纯电车
			$localBaseDb67->set('yp_model3', ['m3_start_stop'=>'无'], " and m3_start_stop='' and m3_fuel='纯电动'");

			//商用车
			$localBaseDb67->set('yp_model3', ['m3_start_stop'=>'无'], " and m3_start_stop='' and (m3_from ='kcauto' or m3_body like '%货车%' or m3_body like '%微面%')");
			
			//有汽车之家ID的
			$cres = $localBaseDb67->get('yp_model3 join yp_model2 on m3_m2_id = m2_id', ['m3_id', 'm3_qczj_id'], sprintf(" and m3_start_stop='' and m3_qczj_id > 0"));
			$count = 0;
			foreach(array_chunk($cres['data'], 1000) as $rows)
			{
				$res = $CarBase->get('model2 left join para_value on m2_id = pv_m2_id and pv_pl_id=53', ['m2_id', 'max(pv_value) startstop'], sprintf(" and m2_id in (%s) group by m2_id", implode(',', array_column($rows, 'm3_qczj_id'))));
				$sstArr = [];
				foreach($res['data'] as $rv){
					$sstArr[$rv['m2_id']] = $rv['startstop'] == '●'? '有': '无';
				}
				$setArr = ['无'=>[], '有'=>[]];
				foreach($rows as $row)
				{
					if(!isset($sstArr[$row['m3_qczj_id']])) continue;
					$setArr[$sstArr[$row['m3_qczj_id']]][] = $row['m3_id'];
				}
				foreach($setArr as $val=>$ids){
					if(!empty($ids)) $localBaseDb67->set('yp_model3', ['m3_start_stop'=>$val], sprintf(" and m3_id in (%s)", implode(',', $ids)));
				}
			}
			$chkWhere = sprintf(" and m3_start_stop=''");
		}else{
			$chkWhere = sprintf(" and m3_id=%d", $m3id);
		}
		$fields = ['b_id', 'b_name', 'm_id', 'm_name', 'm1_id','m1_name','m2_id','m2_name','m3.*'];
		$cres = $localBaseDb67->get('yp_model3 m3 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_make on m1_m_id = m_id', $fields, $chkWhere);
		foreach($cres['data'] as $cv)
		{
			$startStop = '';
			$cv['tran'] = $this->formatModelAttr('tran', $cv['m3_transmission']);
			$cv['drive'] = $this->formatModelAttr('drive', $cv['m3_drive_short']);
			$cv['niankuan'] = $this->formatModelAttr('niankuan', $cv['m3_name']);
			$cv['banben'] = $this->formatModelAttr('banben', $cv['m3_name']);
			$cv['name'] = preg_replace('/\d+\.?\d?[TL][A-Z]*/i', '', $cv['m3_name']);
			$cv['name'] = preg_replace('/\d{2,}改?款/iu', '', $cv['name']);
			if(!empty($cv['tran'])) $cv['name'] = str_replace($cv['tran'], '', $cv['name']);
			if(!empty($cv['drive'])) $cv['name'] = str_replace($cv['drive'], '', $cv['name']);
			$cv['name'] = trim($cv['name']);

			$qmodeArr = [];
			foreach(['size', 'bind', 'mod1', 'mod1_2'] as $type)
			{
				$swhere = '';
				if($type == 'size'){//汽车之家尺寸
					$sizeArr = [];
					$res = $localBaseDb67->get('yp_model3_size', ['m3s_length, m3s_width, m3s_height'], sprintf(" and m3s_m3_id=%d", $cv['m3_id']));
					if(!empty($res['data'])){
						$sizeArr = $res['data'];
					}else{
						//型号 
						$YpwBase = new YpwBase();
						$res = $localBaseDb67->get('yp_model3_gxb_num', ['mg_code'], sprintf(" and mg_m3_id=%d", $cv['m3_id']));
						if(!empty($res['data'])){
							$gxbWhere = sprintf(" and gs_gb_id in (select distinct gb_id from gxb_base where gb_gxb_code in ('%s') and gb_type='gxb') group by gs_length,gs_width,gs_height", implode("','", array_column($res['data'], 'mg_code')));
							$res = $YpwBase->get('gxb_size',['gs_length m3s_length,gs_width m3s_width,gs_height m3s_height'], $gxbWhere);
							if(!empty($res['data'])) $sizeArr = $res['data'];
						}

						if(empty($sizeArr)){//VIN8 找尺寸
							$res = $localBaseDb67->get('yp_vin_model3_link JOIN yp_vin ON vin_id = vm3_vin_id', ['distinct vin_full'], sprintf(" and vm3_m3_id=%d", $cv['m3_id']));
							if(!empty($res['data'])){
								$gxbWhere = sprintf(" and gs_gb_id in (select distinct gp_gb_id from gxb_params where gp_gl_code='vin18' AND gp_value in ('%s')) group by gs_length,gs_width,gs_height", implode("','", array_column($res['data'], 'vin_full')));
								$res = $YpwBase->get('gxb_size',['gs_length m3s_length,gs_width m3s_width,gs_height m3s_height'], $gxbWhere);
								if(!empty($res['data'])) $sizeArr = $res['data'];
							}
						}
					}
					if(!empty($sizeArr)){
						$twhere = [];
						foreach($sizeArr as $tv){
							$twhere[] = sprintf("(m2_length=%d and m2_width=%d and m2_height=%d)", $tv['m3s_length'], $tv['m3s_width'], $tv['m3s_height']);
						}
						$swhere = sprintf(" and (%s)", implode(' or ', $twhere));
					}
				}else if($type == 'bind'){//已绑的ID车系反射
					$res = $localBaseDb67->get('yp_model3', ['m3_qczj_id'], sprintf(" and m3_m2_id=%d and m3_qczj_id > 0", $cv['m3_m2_id']));
					if(!empty($res['data'])){
						$swhere = sprintf(" and m2_m1_id in (select distinct m2_m1_id from model2 where m2_id in (%s))", implode(',',array_column($res['data'], 'm3_qczj_id')));
					}else{
						$res = $localBaseDb67->get('yp_model3 JOIN yp_model2 ON m2_id = m3_m2_id', ['m3_qczj_id'], sprintf(" and m2_m1_id=%d and m3_qczj_id > 0", $cv['m2_m1_id']));
						if(!empty($res['data'])){
							$swhere = sprintf(" and m2_m1_id in (select distinct m2_m1_id from model2 where m2_id in (%s))", implode(',',array_column($res['data'], 'm3_qczj_id')));
						}
					}
				}else if($type == 'mod1'){//车系名称
					$stwhere = sprintf("(b_name='%s' or replace(b_name, '集团', '') ='%s')", $cv['b_name'], $cv['b_name']);
					if(stripos($cv['m_name'], '进口') !== false){//911
						$stwhere .= sprintf(" and (maf_name like '%%进口%%' or maf_name=b_name) and (m1_name = '%s' or m1_name = '%s' or replace(replace(m1_name, b_name, ''), '(进口)', '') ='%s')", $cv['m1_name'], $cv['m2_name'], $cv['m1_name']);
					}else{
						$stwhere .= sprintf(" and maf_name not like '%%进口%%' and (m1_name = '%s' or m1_name = '%s' or replace(m1_name, b_name, '') = '%s')", $cv['m1_name'], $cv['m2_name'], $cv['m1_name']);
					}
					$swhere =" and m2_id in (select distinct m2_id from model2 JOIN model1 ON m2_m1_id = m1_id JOIN brand ON b_id = m2_b_id JOIN manufacturer ON maf_id = m2_maf_id 
					where {$stwhere})";
				}else if($type == 'mod1_2'){//车系名称
					$stwhere = sprintf("(maf_name='%s')", $cv['m_name']);
					if(stripos($cv['m_name'], '进口') !== false){//911
						$stwhere .= sprintf(" and (maf_name like '%%进口%%' or maf_name=b_name) and (m1_name = '%s' or m1_name = '%s' or replace(replace(m1_name, b_name, ''), '(进口)', '') ='%s' or m1_name = '%s')", $cv['m1_name'], $cv['m2_name'], $cv['m1_name'], strtr($cv['m1_name'], ['级'=>'','系列'=>'','级'=>'系']));
					}else{
						$stwhere .= sprintf(" and maf_name not like '%%进口%%' and (m1_name = '%s' or m1_name = '%s' or replace(m1_name, b_name, '') = '%s' or m1_name = '%s')", $cv['m1_name'], $cv['m2_name'], $cv['m1_name'], strtr($cv['m1_name'], ['级'=>'','系列'=>'','级'=>'系']));
					}
					$swhere =" and m2_id in (select distinct m2_id from model2 JOIN model1 ON m2_m1_id = m1_id JOIN brand ON b_id = m2_b_id JOIN manufacturer ON maf_id = m2_maf_id 
					where {$stwhere})";
				}
				
				if(empty($swhere)) continue;
				if(!empty($cv['m3_wheel'])) $swhere .= sprintf(" and m2_wheelbase=%d", $cv['m3_wheel']);
				if(!empty($cv['m3_cc'])) $swhere .= sprintf(" and m2_id in (select distinct pv_m2_id from para_value where pv_pl_id=125 and pv_value between '%s' and '%s')", $cv['m3_cc']-10, $cv['m3_cc']+10);
				$table = 'model2 join model1 on m2_m1_id = m1_id 
				left join para_value p1 on m2_id=p1.pv_m2_id and p1.pv_pl_id=53
				left join para_value p2 on m2_id=p2.pv_m2_id and p2.pv_pl_id=54
				left join para_value p3 on m2_id=p3.pv_m2_id and p3.pv_pl_id=179
				left join para_value p4 on m2_id=p4.pv_m2_id and p4.pv_pl_id=244';
				$res = $CarBase->get($table, ['m2_id, m1_name, m2_name, m2_year, max(p2.pv_value) m2_engine, max(p1.pv_value) startstop, max(p3.pv_value) tran, max(p4.pv_value) drive'], $swhere." group by m2_id");
				//echo $swhere, '<br>';
				if(empty($res['data'])) continue;
				$qmodeArr = $res['data'];
				break;
			}
			//var_dump($qmodeArr);
			if(!empty($qmodeArr)){
				$hasArr = [];
				foreach($qmodeArr as $tv){
					if(empty($tv['m2_engine'])) $tv['m2_engine'] = '';
					if(empty($tv['startstop'])) $tv['startstop'] = '○';
					//车系相识度
					similar_text($cv['m2_name'], $tv['m1_name'], $percent);
					if($percent < 10) continue;
					$tv['m1_percent'] = $percent;
					//变速箱
					$tv['tran'] = $this->formatModelAttr('tran', $tv['tran']);
					$tv['drive'] = $this->formatModelAttr('drive', $tv['drive']);
					$tv['niankuan'] = $this->formatModelAttr('niankuan', $tv['m2_name']);
					$tv['banben'] = $this->formatModelAttr('banben', $tv['m2_name']);
					if(($cv['tran'] == '手动' && $tv['tran'] == '自动') || ($cv['tran'] == '自动' && $tv['tran'] == '手动')) continue;
					if(($cv['drive'] == '两驱' && $tv['drive'] == '四驱') || ($cv['drive'] == '四驱' && $tv['drive'] == '两驱')) continue;
					$hasArr[$tv['m2_id']] = $tv;
				}
				
				if(!empty($hasArr))
				{
					foreach(['hasyear', 'noyear'] as $my)
					{
						if(!empty($startStop)) break;
						foreach(['all', 'null_banben', 'null_niankuan', 'banben'] as $regType)
						{
							if(!empty($startStop)) break;
							$matchArr = [];
							foreach($hasArr as $tk=>$tv)
							{
								if($my == 'hasyear'){
									if(!empty($tv['m2_year']) && !empty($cv['m3_start_year'])){
										if($tv['m2_year'] >= $cv['m3_start_year'] && ($tv['m2_year'] <= $cv['m3_end_year'] || empty($cv['m3_end_year']))){
										}else{
											continue;
										}
									}
								}
								switch($regType)
								{
									case 'all'://变速箱 驱动 年款 版本 一致的
										if(!empty($cv['tran']) && $cv['tran'] == $tv['tran']
											&& !empty($cv['drive']) && $cv['drive'] == $tv['drive']
											&& !empty($cv['niankuan']) && $cv['niankuan'] == $tv['niankuan']
											&& !empty($cv['banben']) && $cv['banben'] == $tv['banben']
										){
											$matchArr[$tk] = $tv;
										}
									break;
									case 'null_banben':
										if(!empty($cv['tran']) && $cv['tran'] == $tv['tran']
											&& !empty($cv['drive']) && $cv['drive'] == $tv['drive']
											&& !empty($cv['niankuan']) && $cv['niankuan'] == $tv['niankuan']
											&& empty($cv['banben'])
										){
											$matchArr[$tk] = $tv;
										}
									break;
									case 'null_niankuan':
										if(!empty($cv['tran']) && $cv['tran'] == $tv['tran']
											&& !empty($cv['drive']) && $cv['drive'] == $tv['drive']
											&& empty($cv['niankuan'])
											&& !empty($cv['banben']) && $cv['banben'] == $tv['banben']
										){
											$matchArr[$tk] = $tv;
										}
									break;
									case 'banben':
										if(!empty($cv['tran']) && $cv['tran'] == $tv['tran']
											&& !empty($cv['drive']) && $cv['drive'] == $tv['drive']
											&& !empty($cv['banben']) && $cv['banben'] == $tv['banben']
										){
											$matchArr[$tk] = $tv;
										}
									break;
								}
							}
							if(!empty($matchArr)) $startStop = $this->getStartStop(array_column($matchArr, 'startstop'));
						}
					}
				}

				if(empty($startStop) && !empty($hasArr)){
					foreach($hasArr as $tk=>$tv){
						if(!empty($tv['m2_year']) && !empty($cv['m3_start_year'])){
							if($tv['m2_year'] >= $cv['m3_start_year'] && ($tv['m2_year'] <= $cv['m3_end_year'] || empty($cv['m3_end_year']))){
							}else{
								unset($hasArr[$tk]);
								continue;
							}
						}
					}
					if(empty($startStop) && !empty($hasArr)) $startStop = $this->getStartStop(array_column($hasArr, 'startstop'));
					if(empty($startStop) && !empty($hasArr) && !in_array($cv['m3_id'], [953,1046,2339,2338,4035]) && strlen($cv['name']) > 3){
						//var_dump($cv, $hasArr);exit;
					}
				}
				
				//智配 必须有版本
				/*if(empty($startStop) && !empty($cv['m3_vin_demo'])){
					$res = $localBaseDb67->get('zp_vin_model join zp_catch on zc_vin=zvm_vin and zc_id=zvm_zc_id', ['zvm_model', 'zc_html'], sprintf(" and zvm_status in(1,2) and zvm_vin='%s' order by zvm_id desc limit 1", $cv['m3_vin_demo']), true);
					if(!empty($res['data']))
					{
						$zpArr = $res['data'];
						$info = json_decode($zpArr['zc_html'], true);
						$info = $info['Body'];
						$info['banben'] = '';
						//var_dump($info['jYAutoByVin']['vinAutos'][0]);exit;
						if(!empty($info['jYAutoByVin']['vinAutos'][0]['autoParamList'])){//有版本
							$paras = array_column($info['jYAutoByVin']['vinAutos'][0]['autoParamList'], 'paramValue', 'paramName');
							if(!empty($cv['banben']) && !empty($paras['配置级别']) && !empty($paras['发动机启停技术']))
							{
								similar_text($cv['banben'], $paras['配置级别'], $percent);
								if($percent > 50){
									if($paras['发动机启停技术'] == '有'){
										$startStop = '有';
									}else if(in_array($paras['发动机启停技术'], ['无', '非启停'])){
										$startStop = '无';
									}
								}else{
									
									var_dump($cv, $paras);exit;
								}
							}
						}else if(!empty($info['autoParamGroups'][0]['AutoParamList'])){
							$paras = array_column($info['autoParamGroups'][0]['AutoParamList'], 'ParamValue', 'ParamName');
							if(empty($cv['banben']) && !empty($paras['发动机启停技术'])){
								if($paras['发动机启停技术'] == '有'){
									$startStop = '有';
								}else if(in_array($paras['发动机启停技术'], ['无', '非启停'])){
									$startStop = '无';
								}
							}
						}
					}
				}*/
			}

			if(empty($startStop)){//品牌+车系是否全部一致
				$stwhere = sprintf("(b_name='%s' or replace(b_name, '集团', '') ='%s' or maf_name='%s')", $cv['b_name'], $cv['b_name'], $cv['m_name']);
				$stwhere .= sprintf(" and (m1_name = '%s' or m1_name = '%s' or replace(replace(m1_name, b_name, ''), '(进口)', '') ='%s')", $cv['m1_name'], $cv['m2_name'], $cv['m1_name']);
				$swhere =" and m2_id in (select distinct m2_id from model2 JOIN model1 ON m2_m1_id = m1_id JOIN brand ON b_id = m2_b_id JOIN manufacturer ON maf_id = m2_maf_id 
				where {$stwhere})";
				$table = 'model2 join model1 on m2_m1_id = m1_id left join para_value p1 on m2_id=p1.pv_m2_id and p1.pv_pl_id=53';
				$res = $CarBase->get($table, ['m2_id, m1_name, m2_name, m2_year, max(p1.pv_value) startstop'], $swhere." group by m2_id");
				$hasArr = $res['data'];
				foreach($hasArr as $tk=>$tv){
					if(empty($tv['startstop'])) $hasArr[$tk]['startstop'] = '○';
				}
				if(!empty($hasArr)){
					$startStop = $this->getStartStop(array_column($hasArr, 'startstop'));
					if(empty($startStop) && !empty($hasArr)){
						foreach($hasArr as $tk=>$tv){
							if(!empty($tv['m2_year']) && !empty($cv['m3_start_year'])){
								if($tv['m2_year'] >= $cv['m3_start_year'] && ($tv['m2_year'] <= $cv['m3_end_year'] || empty($cv['m3_end_year']))){
								}else{
									unset($hasArr[$tk]);
									continue;
								}
							}
						}
						if(empty($startStop) && !empty($hasArr)) $startStop = $this->getStartStop(array_column($hasArr, 'startstop'));
					}
				}
			}

			if(!empty($startStop)){
				$localBaseDb67->set('yp_model3', ['m3_start_stop'=>$startStop], sprintf(" and m3_id=%d", $cv['m3_id']));
			}
		}
		return LibFc::ReturnData(true);
	}

	private function getStartStop($vals)
	{
		$startStop = '';
		$tvals = array_unique($vals);
		if(!empty($vals) && count($tvals) == 1){
			if($vals[0] == '●'){
				$startStop = '有';
			}else if($vals[0]== '○'){
				$startStop = '无';
			}
		}
		return $startStop;
	}

	private function formatModelAttr($type, $str)
	{
		$estr = '';
		switch($type)
		{
			case 'tran':
				if(stripos($str, '手动') !== false || preg_match('/\dMT/u', $str, $match)){
					$estr = '手动';
				}else if(stripos($str, '自动') !== false || stripos($str, 'CVT') !== false || stripos($str, 'DCT') !== false || stripos($str, 'AT') !== false 
				|| stripos($str, '单速') !== false || stripos($str, '双离合') !== false || stripos($str, '无极') !== false || stripos($str, '手自一体') !== false || preg_match('/A\/?MT/', $str, $match)
				){
					$estr = '自动';
				}
			break;
			case 'drive':
				if(stripos($str, '后驱') !== false || stripos($str, '前驱') !== false || stripos($str, '两驱') !== false || stripos($str, '4×2') !== false){
					$estr = '两驱';
				}else if(stripos($str, '四驱') !== false || stripos($str, '全驱') !== false || stripos($str, '4×4') !== false){
					$estr = '四驱';
				}
			break;
			case 'banben':
				if(preg_match('/ ([^ ]{2,})版/u', $str, $match) 
					|| preg_match('/ ([^ ]{2,})型 /u', $str, $match) 
					|| preg_match('/ ([^ ]{2,})型$/u', $str, $match)
					|| preg_match('/ (手动[^ ]{2,}) /u', $str, $match)
					|| preg_match('/ (手动[^ ]{2,})$/u', $str, $match)
					|| preg_match('/ (自动[^ ]{2,}) /u', $str, $match)
					|| preg_match('/ (自动[^ ]{2,})$/u', $str, $match)
				){
					$estr = $match[1];
				}
			break;
			case 'niankuan':
				if(preg_match('/(\d{2,4})改?款/u', $str, $match)){
					$estr = $match[1] < 100? '20'.$match[1]: $match[1];
				}
				if($estr != '' && stripos($str, '改款') !== false) $estr .= '改款';
			break;
		}
		return $estr;
	}
}