<?php
class ypcCarAction extends baseAction
{
    function standSyncLocal()
    {
        if (!isset($_POST['othsma']) || !$_POST['othsma']) {
            LibTpl::Error('没有传递VIN信息过来。');
        }
        
        $YpwBase = new YpwBase();
        $res = $YpwBase->get('stand_model_any',
            ['sma_id', 'sma_vin', 'sma_gxb_code', 'sma_gxb_code_show', 'sma_brand', 'sma_engine', 'sma_engine6', 'sma_year', 'sma_etime'],
            sprintf('and sma_id in (%s)', $_POST['othsma'])
        );
        if (!$res['data']) {
            LibTpl::Error('没有查询到600w信息。');
        }
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://crm.yiparts.com:3009/Admin/index.php/SearchVin/resByOnline');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ['data' => json_encode($res['data'])]);
        $content = curl_exec($ch);
        curl_close($ch);
        
        ($content == '程序执行完成') ?  LibTpl::Success('程序执行完成') :  LibTpl::Error('程序执行失败');
    }
    
	/**
	 * @method    其它VIN解码管理
	 * @author soul
	 * @copyright 2019/1/22
	 */
	function standModelAny()
	{
		LibRule::Check('CA01');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$where = '';
		$YpwBase = new YpwBase();
		$othsfileds = [
			'sma_cc'=>['name'=>'排量', 'size'=>4],
			'sma_tran'=>['name'=>'变速箱', 'size'=>8],
			'sma_weight'=>['name'=>'整备质量', 'size'=>4],
			'sma_passenger'=>['name'=>'载客', 'size'=>3],
			'sma_vtype'=>['name'=>'车辆类型', 'size'=>8],
			'sma_year'=>['name'=>'生产日期', 'size'=>8],
			'sma_jkyear'=>['name'=>'进口日期', 'size'=>8],
			'sma_xuhang'=>['name'=>'续航', 'size'=>8],
		];
		$showMoreSearch = false;
		$ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
		$table = "stand_model_any 
		left join stand_gxb_base on sma_gxb_code = sgb_gxb_code
		left join stand_model_ypgxb on gxb_vin1_8 = sma_vin1_8 and gxb_code = sma_gxb_code 
		left join stand_gxb_v8info on sgv_vin1_8 = sma_vin1_8  and sma_gxb_code = sgv_gxb_code and ((left(sma_vin1_8, 1) NOT in ('L', 'H') and sgv_org_brand=sma_brand) or left(sma_vin1_8, 1) in ('L', 'H'))";
		if(!empty($_POST['sma_vin']))
		{
			$perPage = null;
			LibTpl::Set('hidePage', 1);
			$Params = $_POST;
		}
		foreach($Params as $K=>$V)
		{
			$V = trim(strtr($V, ['！'=>'!', '＝'=>'=']));
			if($V == '') continue;
			switch($K)
			{
				case 'vin1':
					if($V == '!L')
					{
						$res = $YpwBase->get('stand_model_any', ['distinct sma_vin1_3'], " and sma_vin1_3 NOT LIKE 'L%' and sma_vin1_3 NOT like 'H%'");
						if(!empty($res['data']))
						{
							$where .= sprintf(" and sma_vin1_3 in ('%s')", implode("','", array_column($res['data'], 'sma_vin1_3')));
						}
						else
						{
							$where .= ' and 1 = 0';
						}
					}
					else if(empty($Params['sma_vin']))
					{
						$where .= " AND (sma_vin1_3 like 'L%' OR sma_vin1_3 like 'H%')";
					}
				break;
				case 'sma_vin':
					$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($V))));
					if(count($anyNum) > 1)
					{
						foreach($anyNum as $kk=>$vv)
						{
							$anyNum[$kk] = LibFc::FormatVin($vv);
						}
						$where .= sprintf(" and sma_vin IN ('%s')", implode("','", $anyNum));
					}
					else
					{
						$V = LibFc::FormatNum(strtr($V, $ReLike), '%_');
						if(strlen($V) <= 8)
							$where .= sprintf(" AND sma_vin1_8 like '%s%%'", $V);
						else
							$where .= sprintf(" AND sma_vin like '%s%%'", $V);
					}
				break;
				case 'sma_gxb_code':
					$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($V))));
					if(count($anyNum) > 1)
					{
						foreach($anyNum as $kk=>$vv)
						{
							$anyNum[$kk] = LibFc::FormatNum($vv);
						}
						$where .= sprintf(" and sma_gxb_code IN ('%s')", implode("','", $anyNum));
					}
					else
					{
						if($V == '=')
							$where .= " and {$K}=''";
						else if($V == '!')
							$where .= " and {$K} !=''";
						else	
							$where .= sprintf(" AND sma_gxb_code like '%s'", LibFc::FormatNum(strtr($V, $ReLike), '%_'));
					}
				break;
				case 'sma_vin10':
					$where .= sprintf(" and sma_vin10 IN ('%s')", implode("','", str_split($V)));
				break;
				case 'sma_gtype':
					if($V == '=')
						$where .= " and {$K}=''";
					else if($V == '!')
						$where .= " and {$K} !=''";
					else	
						$where .= sprintf(" and sma_gtype IN ('%s')", implode("','", str_split($V)));
				break;
				case 'sma_length':
				case 'sma_width':
				case 'sma_height':
				case 'sma_wheel':
					if($V == '='){
						$where .= " and {$K}=0";
					}else if($V == '!'){
						$where .= " and {$K} > 0";
					}else if(preg_match('/\d+/', $V, $Match)){
						if(LibFc::Int($V) !== false) $V = '='.$V;
						$where .= ' AND '.$K.' '.$V;
					}
				break;
				case 'sma_engine':
				case 'sma_brand':
				case 'sma_kw':
				case 'sma_from':
					if($V == '=')
						$where .= " and {$K}=''";
					else if($V == '!')
						$where .= " and {$K} !=''";
					else
						$where .= sprintf(" AND %s like '%s'", $K, strtr($V, $ReLike));
				break;
				case 'engstatus': 
					if($V == 1){
						$where .= " and sma_engine != ''";
					}else if($V == -1){
						$where .= " and sma_engine = ''";
					}
				break;
				case 'yearstatus': 
					if($V == 1){
						$where .= " and sma_year != ''";
					}else if($V == -1){
						$where .= " and sma_year = ''";
					}
				break;
				case 'hasmake': 
					if($V == 1){
						$where .= " and sma_brand != ''";
					}else if($V == -1){
						$where .= " and sma_brand = ''";
					}
				break;
				case 'ypcar':
					if($V == 'Y1'){
						$where .= " and gxb_vin1_8 is not null and gxb_manual = 1";
					}else if($V == 'Y3'){
						$where .= " and gxb_vin1_8 is not null and gxb_kcauto = 1";
					}else if($V == 'Y1Y3'){
						$where .= " and gxb_vin1_8 is not null and gxb_manual = 1 and gxb_kcauto = 1";
					}else if($V == 'Y2'){
						$where .= " and gxb_vin1_8 is null and sgv_model != '' AND sgv_brand != ''";
					}else if($V == 'Y'){
						$where .= " and (gxb_vin1_8 is not null or (sgv_model != '' AND sgv_brand != ''))";
					}else if($V == 'N'){
						$where .= " and gxb_vin1_8 is null and (sgv_model is null or sgv_model = '' or sgv_brand = '')";
					}
				break;
				case 'dpcar':
					if($V == 1){
						$where .= ' and sma_gxb_code in (select distinct sgd_gxb_code from stand_gxb_dipan join stand_model_ypgxb on gxb_code = sgd_dpgxb_code)';
					}else if($V == -1){
						$where .= " and sma_gxb_code in (select distinct sgd_gxb_code from stand_gxb_dipan where sgd_dpgxb_code not in (select gxb_code from stand_model_ypgxb))";
					}
				break;
				case 'sgb_rname':
					$where .= sprintf(" and (sgb_rname like '%%%s%%' or sgv_model like '%%%s%%')", $V, $V);
				break;
				case 'addTime': $where .= sprintf(" and sma_etime >= %d", strtotime($V)); break;
				case 'endTime': $where .= sprintf(" and sma_etime <= %d", strtotime($V.' 23:59:59')); break;
				case 'min1217': $where .= sprintf(" and sma_vin12_17 >= '%s'", $V); break;
				case 'max1217': $where .= sprintf(" and sma_vin12_17 <= '%s'", $V); break;
				case 'minym':
					if(preg_match('/(\d{4})[^\d]*(\d{1,2})/', $V, $match))
					{
						$ym = date('Y-m', strtotime($match[1].'-'.$match[2].'-01'));
						$where .= sprintf(" and LEFT(sma_year, 7) >= '%s'", $ym); 
					}
				break;
				case 'maxym': 
					if(preg_match('/(\d{4})[^\d]*(\d{1,2})/', $V, $match))
					{
						$ym = date('Y-m', strtotime($match[1].'-'.$match[2].'-01'));
						$where .= sprintf(" and LEFT(sma_year, 7) <= '%s'", $ym); 
					}
				break;
				case 'hasimg':
					if($V) $where .= sprintf(" and EXISTS (SELECT 1 FROM stand_vin_imgs WHERE sma_vin = vii_vin)");
				break;
				default:
					if(!empty($othsfileds[$K])){
						$showMoreSearch = true;
						if($V == '=')
							$where .= " and {$K}=''";
						else if($V == '!')
							$where .= " and {$K} !=''";
						else
							$where .= sprintf(" AND %s like '%s'", $K, strtr($V, $ReLike));
					}
				break;
			}
		}
		
		$vinArr = [];
		$hasModGxb = [];
		if(!empty($where) || !empty($Params['group']))
		{
			if(!empty($Params['group']))
			{
				$Res = $YpwBase->get($table, ['distinct sma_gxb_code'], $where);
				$tgxbArr = array_column($Res['data'], 'sma_gxb_code');
				$Count = count($tgxbArr);
				if($perPage === null) $perPage = $Count;
				$Page = LibPage::show($Count, $perPage);
				if($Count > 0)
				{
					$Res = $YpwBase->get($table, ['*', 'max(sma_xuhang) sma_xuhang','count(*) as vin_count'], sprintf("%s and sma_gxb_code in ('%s') group by sma_gxb_code LIMIT %d,%d", $where, implode("','", $tgxbArr), ($nowPage-1)*$perPage,$perPage));
					$vinArr = $Res['data'];
				}
			}
			else if(!empty($Params['minmax']))
			{
				$Res = $YpwBase->get($table, ['*'], $where.' order by sma_vin10_12, sma_vin13_17 limit 100');
				foreach($Res['data'] as $v)
				{
					$vinArr[$v['sma_vin1_8'].$v['sma_vin10_12'].$v['sma_vin13_17']] = $v;
				}

				$Res = $YpwBase->get($table, ['*'], $where.' order by sma_vin10_12 desc, sma_vin13_17 desc limit 100');
				foreach($Res['data'] as $v)
				{
					$vinArr[$v['sma_vin1_8'].$v['sma_vin10_12'].$v['sma_vin13_17']] = $v;
				}
				ksort($vinArr);
				$Count = count($vinArr);
				$Page = LibPage::show($Count, $Count);
			}
			else
			{
				$Res = $YpwBase->get($table, array('count(1) as count'), $where, true);
				$Count = $Res['data']['count'];
				if($perPage === null) $perPage = $Count;
				$Page = LibPage::show($Count, $perPage);
				if($Count > 0)
				{
					$Res = $YpwBase->get($table, ['*'], sprintf("%s order by sma_vin10_11, sma_vin12_17 LIMIT %d,%d", $where, ($nowPage-1)*$perPage,$perPage));
					$vinArr = $Res['data'];
				}
			}

			if(!empty($vinArr) && ($Params['hasimg'] || $Params['img']))
			{
				$PjlBase= new PjlBase();
				$res = $YpwBase->get('stand_vin_imgs', ['vii_vin', 'vii_imghost', 'vii_img'], sprintf(" and vii_vin in ('%s')", implode("','", array_column($vinArr, 'sma_vin'))));
				$viiArr = [];
				foreach($res['data'] as $v)
				{
					$v['vii_img'] = mvc::$cfg['HOST']['vinimg_'.$v['vii_imghost']].$v['vii_img'];
					$viiArr[$v['vii_vin']] = $v;
				}
				LibTpl::Set('viiArr', $viiArr);
			}
			LibTpl::Set('Page', $Page);
			
			$gxbArr = [];
			$dpGxbArr = [];
			$hasJkRq = false;
			$epcVins = [];
			foreach($vinArr as $k=>$v)
			{
				if(!empty($v['sma_gxb_code'])) $gxbArr[] = $v['sma_gxb_code'];
				if(!empty($v['sma_jkyear'])) $hasJkRq = true;
				if(in_array($v['sma_vin1_3'], ['LFM', 'LVG']) && $v['sma_vyear'] >= 2020) $epcVins[] = $v['sma_vin'];
			}
			$gxbArr = array_unique($gxbArr);
			$hasJkRq = false;
			if(!empty($gxbArr))
			{
				$res = $YpwBase->get('stand_gxb_dipan', ['sgd_gxb_code,sgd_dpgxb_code,sgd_dpgxb_code_show'], sprintf(" and sgd_gxb_code in ('%s')", implode("','", $gxbArr)));
				$gxbDpArr = array_column($res['data'], null, 'sgd_gxb_code');
				LibTpl::Set('gxbDpArr', $gxbDpArr);
				
				$dpGxbArr = array_unique(array_column($res['data'], 'sgd_dpgxb_code'));
				LibTpl::Set('dpGxbArr', $dpGxbArr);
				
				foreach($vinArr as $k=>$v)
				{
					if(!empty($v['sma_jkyear'])) $hasJkRq = true;
				}

				//底盘型号
				$hasDpModArr = [];
				if(!empty($dpGxbArr))
				{
					$res = $YpwBase->get('stand_model_ypgxb', ['distinct gxb_code'], sprintf(" and gxb_code in ('%s')", implode("','", $dpGxbArr)));
					$hasDpModArr = array_column($res['data'], 'gxb_code');
				}
				LibTpl::Set('hasDpModArr', $hasDpModArr);
			}

			if($epcVins){
				$res = $YpwBase->get('stand_vin_epccode', ['vie_vin, vie_unicode'], sprintf(" and vie_vin in ('%s')", implode("','", $epcVins)));
				LibTpl::Set('epcCodes', array_column($res['data'], 'vie_unicode', 'vie_vin'));
			}
		}
		LibTpl::Set('smaFromArr', ['ocr'=>'OCR','org'=>'原有', 'manual'=>'人工', 'catch'=>'采集', 'ZDAPI'=>'泽达', 'wdsp'=>'外调', 'epc'=>'epc', 'buy01'=>'buy01', 'buy02'=>'buy02','rgany'=>'自加']);
		LibTpl::Set('showMoreSearch', $showMoreSearch);
		LibTpl::Set('othsfileds', $othsfileds);
		LibTpl::Set('vinArr', $vinArr);
		LibTpl::Set('hasJkRq', $hasJkRq);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','其它VIN解码管理');
		LibTpl::Put();
	}

	/**
	 * @method    添加其它VIN解码
	 * @author soul
	 * @copyright 2019/1/22
	 */
	function standModelAnyAdd()
	{
		LibRule::Check('CA09');
		$Params = MVC::$URL_PARAMS;

		$h = date('H');
		$engine6Work = $h < 7 || $h >= 20? false: true;
		
		//超级权限
		$rule = LibRule::Check('CA04', false);
		//$Params['ignore'] = !isset($Params['ignore']) || $Params['ignore'] == -1 || !$rule? 1: -1;
		if(!$rule)
		{
			unset($Params['uid']);
			unset($Params['wmis']);
		}

		$YpwBase = new YpwBase();
		$PjlBase= new PjlBase();
		$ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
		if(!empty($_POST['vin']))
		{
            $sma_vin = LibFc::FormatNum($_POST['vin']['sma_vin']);
			if(!in_array(substr($sma_vin, 0, 1), ['L', 'H']) && empty($_POST['vin']['sma_id']) && !$rule)
				LibTpl::Error('非L、H开头的车架号不需要处理。如果是车架号错误，可以点改刷功能纠正。');

			$YpwUser = new YpwUser();
			$res = $YpwUser->saveStandModelAny($Params, $_POST);
			$Params = $res['data']['Params'];

			//VIN识别，直接跳转到下一个
			if(!empty($Params['vii_id']))
			{
				unset($Params['last_time']);
				$viiWhere = '';
				if(stripos($Params['vin'], "\r\n")){

				}else{
					$Params['vin'] = LibFc::FormatNum(strtr($Params['vin'], $ReLike), '%_');
					//查询条件有指定WMI
					if(preg_match('/^([0-9A-Z]{3})/', $Params['vin'], $match))
					{
						$wmiW = $match[0];
						if(preg_match('/^([0-9A-Z]{8})/', $Params['vin'], $match))
						{
							$viiWhere .= sprintf(" and vii_vin1_8 = '%s'", $match[0]);
						}
						else
						{
							$viiWhere .=sprintf(" and vii_vin1_3 = '%s'", $wmiW);
						}
						//有忽略
						if($Params['ignore'] == 1)
						{
							$res = $YpwBase->get('stand_vin_imgs_ignore', ['viig_byear, viig_eyear'], sprintf(" and viig_wmi='%s'", $wmiW), true);
							if(!empty($res['data']))
							{
								if($res['data']['viig_byear'] > 0) $viiWhere .= sprintf(" and vii_year < %d", $res['data']['viig_byear']);
								if($res['data']['viig_eyear'] > 0) $viiWhere .= sprintf(" and vii_year > %d", $res['data']['viig_eyear']);
								//全部忽略
								if($res['data']['viig_byear'] == 0 && $res['data']['viig_eyear'] == 0) $viiWhere .= ' and 1=0';
							}
						}

						$res = $YpwBase->get('stand_vin_imgs_task_user JOIN stand_vin_imgs_task ON vta_wmi = vtu_vta_wmi', ['*'], sprintf(" and vta_status = 1 AND vtu_uid=%d and vta_wmi = '%s'", $_SESSION['admin_userid'], $wmiW), true);
						if(!empty($res['data']))
						{
							$tarArr = $res['data'];
							if(!$rule)
							{
								if(!empty($Params['vii_istask']))
								{
									$viiWhere.= $tarArr['vta_js']? ' and vii_istask > 0': ' and 1=0';
								}
								else
								{
									if(!empty($tarArr['vta_wait'])) $viiWhere .= sprintf(" and vii_atime < %d", time()-$tarArr['vta_wait']*60);
									if(!empty($tarArr['vta_only']))
									{
										$tor = [];
										foreach(explode(',', $tarArr['vta_only']) as $reg)
										{
											$tor[] = sprintf(" vii_vin like '%s'", $reg);
										}
										$viiWhere .= sprintf(" and (%s)", implode(' or ', $tor));
									}
									else if(!empty($tarArr['vta_ignore']))
									{
										foreach(explode(',', $tarArr['vta_ignore']) as $reg)
										{
											$viiWhere .= sprintf(" and vii_vin not like '%s'", $reg);
										}
									}

									if($tarArr['vta_byear'] > 0 && (empty($Params['byear']) || $Params['byear'] < $tarArr['vta_byear']))
									{
										$Params['byear'] = $tarArr['vta_byear'];
									}
									if($tarArr['vta_eyear'] > 0 && (empty($Params['eyear']) || $Params['eyear'] > $tarArr['vta_eyear']))
									{
										$Params['eyear'] = $tarArr['vta_eyear'];
									}
								}
							}
						}
						else if(!$rule)
						{
							LibTpl::Error($wmiW.'任务已处理完毕或者尚未分配');
						}
					}
					else
					{
						if(!$rule)
						{
							if($Params['vii_istask']){
							}else{
								$tArr = [];
								$res = $YpwBase->get('stand_vin_imgs_task_user JOIN stand_vin_imgs_task ON vta_wmi = vtu_vta_wmi', ['group_concat(vta_wmi) AS vta_wmi, vta_byear, vta_eyear, vta_ignore, vta_only, vta_wait'], sprintf(" and vta_status = 1 and vtu_uid=%d group by vta_byear, vta_eyear, vta_ignore, vta_only, vta_wait", $_SESSION['admin_userid']));
								foreach($res['data'] as $v)
								{
									$t = sprintf(" (vii_vin1_3 in ('%s')", implode("','", explode(',', $v['vta_wmi'])));
									if(!empty($v['vta_wait'])) $t .= sprintf(" and vii_atime < %d", time()-$v['vta_wait']*60);
									if(!empty($v['vta_only']))
									{
										$tor = [];
										foreach(explode(',', $v['vta_only']) as $reg)
										{
											$tor[] = sprintf(" vii_vin like '%s'", $reg);
										}
										$t .= sprintf(" and (%s)", implode(' or ', $tor));
									}
									else if(!empty($v['vta_ignore']))
									{
										foreach(explode(',', $v['vta_ignore']) as $reg)
										{
											$t .= sprintf(" and vii_vin not like '%s'", $reg);
										}
									}
									if($v['vta_byear'] > 0) $t .= ' and vii_year >='.$v['vta_byear'];
									if($v['vta_eyear'] > 0) $t .= ' and vii_year <='.$v['vta_eyear'];
									$tArr[] = $t.')';
								}
								if(empty($tArr))
								{
									$viiWhere .= sprintf(" and vii_status =1 and vii_check_uid=%d", $_SESSION['admin_userid']);
								}
								else
								{
									$viiWhere .= sprintf(" and ((vii_status =1 and vii_check_uid=%d) OR (vii_status != 1 and (%s)))", $_SESSION['admin_userid'], implode(' OR ', $tArr));
								}
							}
						}
						else
						{
							//过滤忽略
							$ignorWhere = '';
							if($Params['ignore'] == 1)
							{
								$res =  $YpwBase->get('stand_vin_imgs_ignore', ['group_concat(viig_wmi) AS viig_wmi, viig_byear, viig_eyear'], ' group by viig_byear, viig_eyear');
								foreach( $res['data'] as $v)
								{
									if($v['viig_byear'] == 0 && $v['viig_eyear'] == 0)
									{
										$ignorWhere .= ' and vii_vin1_3 not in (select viig_wmi from stand_vin_imgs_ignore where viig_byear = 0 and viig_eyear = 0)';
									}
									else
									{
										$ignorWhere .= sprintf(" and vii_id NOT IN (SELECT vii_id FROM stand_vin_imgs WHERE vii_vin1_3 in ('%s')", implode("','", explode(',', $v['viig_wmi'])));
										if($v['viig_byear'] > 0) $ignorWhere .= ' and vii_year >='.$v['viig_byear'];
										if($v['viig_eyear'] > 0) $ignorWhere .= ' and vii_year <='.$v['viig_eyear'];
										$ignorWhere .= ')';
									}
								}
							}
							$viiWhere .= $ignorWhere;
						}
					}
				}
				$table = 'stand_vin_imgs';
				foreach($Params as $k=>$v)
				{
					$v = trim($v);
					if($v == '') continue;
					switch($k)
					{
						case 'uid':
							$viiWhere.=sprintf(' and vii_check_uid=%d', (int) $v);
						break;
						case 'vin':
							if(stripos($v, "\r\n"))
							{
								$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($v))));		
								foreach($anyNum as $kk=>$vv)
								{
									$anyNum[$kk] = LibFc::FormatVin($vv);
								}
								$where .= sprintf(" and vii_vin IN ('%s')", implode("','", $anyNum));
							}
							else if(preg_match('/^([0-9A-Z]{3})\%?$/', $v, $match) || preg_match('/^([0-9A-Z]{8})\%?$/', $v, $match))
							{}
							else
							{
								$viiWhere.=sprintf(" and vii_vin LIKE '%s%%'", rtrim($v, '%'));
							}
						break;
						case 'vii_imgocr':
							$v = str_replace('　',' ',$v);
							foreach(explode(' ', $v) as $tv)
							{
								$tv = trim($tv);
								if(!empty($tv))
									$viiWhere.=sprintf(" and vii_imgocr like '%%%s%%' AND vii_vin not like '%%%s%%'", LibFc::Escape($tv), LibFc::Escape($tv));
							}
						break;
						case 'status':
							$viiWhere.=sprintf(' and vii_status=%d', (int) $v);
						break;
						case 'vii_imgtype':
							$viiWhere.=sprintf(' and vii_imgtype=%d', (int) $v);
						break;
						case 'vin1':
							if($v == 'L') $viiWhere.= " and (vii_vin1_3 LIKE 'L%' OR vii_vin1_3 LIKE 'H%')";
							else if($v == '!L') $viiWhere.= " AND vii_vin1_3 NOT LIKE 'L%' AND vii_vin1_3 NOT LIKE 'H%'";
						break;
						case 'byear':
							if($v > 1949) $viiWhere.=sprintf(' and vii_year >= %d', $v);
						break;
						case 'eyear':
							if($v > 1949) $viiWhere.=sprintf(' and vii_year <= %d', $v);
						break;
						case 'wmis':
							$viiWhere.= sprintf(" and left(vii_vin, 3) in ('%s')", implode("','", explode(',', $v)));
						break;
						case 'betime':
							$t = explode(' ~ ', $v);
							$viiWhere .= sprintf(" and vii_atime >= %d and vii_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
						break;
						case 'vii_anygxb':
							if(!empty($v) && stripos($viiWhere, 'vii_anygxb') === false) $viiWhere.= ' and vii_anygxb=1';
						break;
						case 'vii_istask':
							if(!empty($v) && stripos($viiWhere, 'vii_istask') === false) 
								$viiWhere.= $rule? ' and vii_istask > 0': sprintf("  and vii_istask > 0 and vii_vin1_3 in (select vta_wmi from stand_vin_imgs_task_user JOIN stand_vin_imgs_task ON vta_wmi = vtu_vta_wmi where vtu_uid=%d and vta_js =1)", $_SESSION['admin_userid']);
						break;
						case 'smayear': 
							if(empty($Params['vin'])) break;
							$twhereArr = [];
							$smawhere = sprintf(" and sma_vin LIKE '%s%%' AND sma_year != ''", rtrim($Params['vin'], '%'));
							if(!empty($Params['byear'])) $smawhere .=sprintf(' and sma_vyear >= %d', $Params['byear']);
							if(!empty($Params['eyear'])) $smawhere .=sprintf(' and sma_vyear <= %d', $Params['eyear']);
							$sres = $YpwBase->get('stand_model_any',['sma_vin1_8, sma_vin10, LEFT(sma_year, 7) syear, MIN(RIGHT(sma_vin, 7)) min1317, MAX(RIGHT(sma_vin, 7)) max1317'], $smawhere." GROUP BY sma_vin1_8, sma_vin10, syear ORDER BY sma_vin1_8, sma_vin10_12, min1317, syear");
							if(empty($sres['data'])) break;
							$hasvin812 = [];
							foreach($sres['data'] as $sv)
							{
								$tkey = $sv['sma_vin1_8'].$sv['sma_vin10'];
								if(empty($hasvin812Arr[$tkey])) $hasvin812Arr[$tkey] = ['base'=>$sv, 'items'=>[]];
								$hasvin812Arr[$tkey]['items'][] = $sv;
							}
							foreach($hasvin812Arr as $tkey=>$svs)
							{
								$scomwhere = sprintf("vii_vin1_8='%s' and vii_vin10_12 like'%s%%'", $svs['base']['sma_vin1_8'], $svs['base']['sma_vin10']);
								$items = $svs['items'];
								$itemCount = count($items);
								if($itemCount == 1)
								{
									//$twhereArr[] = sprintf("(%s and (RIGHT(vii_vin, 7) < '%s' OR RIGHT(vii_vin, 7) >'%s'))", $scomwhere, $items[0]['min1317'], $items[0]['max1317']);
									continue;
								}

								foreach($items as $sk=>$sv)
								{
									if($sk+1 == $itemCount)
									{
										//$twhereArr[] = sprintf("(%s and RIGHT(vii_vin, 7) > '%s')", $scomwhere, $sv['max1317']);
									}
									else
									{
										/*if($sk == 0)
											$twhereArr[] = sprintf("(%s and RIGHT(vii_vin, 7) < '%s')", $scomwhere, $sv['min1317']);*/
										if($sv['syear'] == $items[$sk+1]['syear']) continue;
										if(date('Y-m', strtotime('+1 month', strtotime($sv['syear'].'-01'))) == $items[$sk+1]['syear']) continue;
										$twhereArr[] = sprintf("(%s and RIGHT(vii_vin, 7) > '%s' and RIGHT(vii_vin, 7) < '%s')", $scomwhere, $sv['max1317'], $items[$sk+1]['min1317']);
									}
								}
							}
							if(!empty($twhereArr))
							{
								$table .= ' left join yp_allvin_base on vii_vin = alb_vin';
								$viiWhere .= " and alb_vin is null";
								$viiWhere .= sprintf(" and (%s)", implode(" or ", $twhereArr));
							}
							else
							{
								$viiWhere .= ' and 1=0';
							}
						break;
					}
				}
				if(!$rule && (date('H') >= 20 || date('H') < 8)) $viiWhere .= " and vii_imgtype != 1";

				$orderArr=[
					'null'=>['','不排序'],
					'vin'=>['order by vii_vin1_8,vii_vin10_12,vii_vin13_17','车架号'],
					'yearvin'=>['order by vii_year desc,vii_vin1_8,vii_vin10_12,vii_vin13_17', '综合排序'],
					'chktime'=>['order by vii_check_time desc', '处理时间'],
					'new'=>['order by vii_id desc', '添加新到旧'],
					'old'=>['order by vii_id asc', '添加旧到新'],
				];
				LibTpl::Set('orderArr', $orderArr);
				if(empty($orderArr[$Params['order']])) $Params['order'] = 'null';
				
				//特殊情况下 limit 1慢
				$viiWhere .=sprintf(' %s limit %d', $orderArr[$Params['order']][0], rand(20,200));
				$res = $YpwBase->get($table, ['vii_id'], $viiWhere, true);
				if(!empty($res['data']))
				{
					$nextParams = $Params;
					$nextParams['vii_id'] = $res['data']['vii_id'];
					unset($nextParams['smaId']);
					$url = mvc::$cfg['ADMIN_URI'].'ypcCar/standModelAnyAdd?'.http_build_query($nextParams);
					LibFc::Go($url);
				}
			}
			LibTpl::Success('操作成功',  mvc::$cfg['ADMIN_URI'].'ypcCar/standModelAnyAdd?'.http_build_query($Params));
		}
		if(!empty($Params['smaId']))
		{
			$res = $YpwBase->get('stand_model_any', ['*'], sprintf(" and sma_id=%d", $Params['smaId']), true);
			$data = $res['data'];
		}
		if(!empty($Params['vin']))
		{
			$res = $YpwBase->get('stand_model_any', ['*'], sprintf(" and sma_vin='%s'", LibFc::FormatNum($Params['vin'])), true);
			$data = $res['data'];
		}

		$statusArr = [
			0=>'待处理',
			1=>'已处理【有效】',	
			-1=>'待处理【无效】',	
			-2=>'待处理【疑难】',
			-3=>'待处理【有日期】',	
			-4=>'重复[待删]',	
		];
		LibTpl::Set('statusArr', $statusArr);
		
		$imgUrl = '';
		if(!empty($Params['ve_id']) || !empty($data))
		{
			//用户纠错
			$where = !empty($Params['ve_id']) ? sprintf(" and ve_id=%d", $Params['ve_id']): sprintf(" and ve_vin='%s'", $data['sma_vin']);
			$res = $PjlBase->get('pl_vin_error', ['*'], $where, true);
			$vinErr = $res['data'];
			$vinErr['ve_imgs'] = empty($vinErr['ve_imgs'])? []: explode(',', $vinErr['ve_imgs']);
			foreach($vinErr['ve_imgs'] as $ik=>$iv)
			{
				$vinErr['ve_imgs'][$ik] = ['img'=>mvc::$cfg['FILE_CENTER']['pjl']['url_get'].'&c=oth&f='.$iv.mvc::$cfg['FILE_CENTER']['pjl']['get_uri'], 'words'=>''];
			}
			$vinErr['ve_check'] = json_decode($vinErr['ve_check'],true);
			if(empty($data) && !empty($vinErr))
			{
				$res = $YpwBase->get('stand_model_any', ['*'], sprintf(" and sma_vin='%s' limit 1", $vinErr['ve_vin']), true);
				$data = $res['data'];
			}
			LibTpl::Set('vinErr', $vinErr);
		}
		
		if(!empty($Params['vii_id']) || !empty($data))
		{
			//VIN识别图片
			$where = !empty($Params['vii_id']) ? sprintf(" and vii_id=%d", $Params['vii_id']): sprintf(" and vii_vin='%s'", $data['sma_vin']);
			$res = $YpwBase->get('stand_vin_imgs', ['*'], $where, true);
			$vinOcrImg = $res['data'];
			$uid = $vinOcrImg['vii_check_uid'];
			if(!empty($vinOcrImg['vii_img'])) $vinOcrImg['vii_img'] = mvc::$cfg['HOST']['vinimg_'.$vinOcrImg['vii_imghost']].$vinOcrImg['vii_img'];
			$vinOcrImg['ve_check'] = json_decode($vinOcrImg['ve_check'],true);
			$ocrWords = $vinOcrImg['vii_imgocr'];
			$ocrAi = [];
			if(!empty($vinOcrImg['vii_id']))
			{
				$res = $YpwBase->get('stand_vin_imgs_ocrai', ['*'], sprintf(" and via_vii_id=%d", $vinOcrImg['vii_id']), true);
				$ocrAi = $res['data'];
			}
			if(empty($data) && !empty($vinOcrImg['vii_vin']))
			{
				$res = $YpwBase->get('stand_model_any', ['*'], sprintf(" and sma_vin='%s' limit 1", $vinOcrImg['vii_vin']), true);
				$data = $res['data'];
			}
			LibTpl::Set('vinOcrImg', $vinOcrImg);
			LibTpl::Set('ocrAi', $ocrAi);
		}

		$LibYpApi = new LibYpApi();
		if($uid > 0)
		{
			$B2cBase = new B2cBase();
			$uid = (int) $uid;
			$res = $B2cBase->get('an_user', ['au_uid', 'au_name'], ' and au_uid='.$uid);
			LibTpl::Set('userArr', array_column($res['data'], 'au_name', 'au_uid'));
		}

		//反查有可能的工信部型号
		if(!empty($data['sma_vin']))
			$vin = $data['sma_vin'];
		else if(!empty($vinOcrImg['vii_vin'])) 
			$vin = $vinOcrImg['vii_vin'];
		else if(!empty($vinErr['ve_vin']))
			$vin = $vinErr['ve_vin'];

		if(strlen($vin) != 17) LibTpl::Error('车架号长度不对或者数据不存在！');
		$vin = strtoupper($vin);
		$isJinkou = in_array(substr($vin, 0, 1), ['L','H'])? false: true;
		$vinCatchGxb = [];
		$vin13 = substr($vin, 0, 3);
		$vin18 = substr($vin, 0, 8);
		$v10_11 = substr($vin, 9, 2);
		$v10_12 = substr($vin, 9, 3);
		$v12_17 = substr($vin, 11, 6);
		$v13_17 = substr($vin, 12, 5);

		//是否有处理权限
		if(!$rule && !empty($vinOcrImg) && $vinOcrImg['vii_status'] != 1)
		{
			$res = $YpwBase->get('stand_vin_imgs_task_user JOIN stand_vin_imgs_task ON vta_wmi = vtu_vta_wmi', ['vta_wmi'], sprintf(" and vta_wmi='%s' and vta_status = 1 and vtu_uid=%d", $vin13, $_SESSION['admin_userid']));
			if(empty($res['data'])) LibTpl::Error('此任务已经处理完毕或者车架号不存在！');
		}
		
		$vinDecode = [];
		if($rule)
		{
			$res = $LibYpApi->Get('vin/getVinBaseInfo', ['vin'=>$vin, 'type'=>'onlydate']);
			$vinDecode = $res['data'];
		}
		
		if(!empty($vin) && empty($data['sma_gxb_code_show']))
		{
			$res = $LibYpApi->Get('vin/getVinGxbCode', ['vin'=>$vin]);
			if(!empty($res['data']))
			{
				foreach($res['data'] as $v)
				{
					$data['sma_gxb_code_show'] = $v['gxb'];
					$vinCatchGxb[LibFc::formatNum($v['gxb'])] = $v;
				}
			}
			else
			{
				$whereArr = [
					['sma_vin13_17', $v13_17, sprintf(" and sma_vin1_8='%s' and sma_vin10_12='%s' and sma_gxb_code != ''", $vin18, $v10_12)],
					['sma_vin12_17', $v12_17, sprintf(" and sma_vin1_8='%s' and sma_vin10_11='%s' and sma_gxb_code != ''", $vin18, $v10_11)]
				];
				$minGxb = '';
				foreach($whereArr as $tv)
				{
					//绝对值 取最近
					$temp = [];
					$sort = [];
					$filed = ['sma_gxb_code_show as gxb, 0 as islike, sma_vin, '.$tv[0].' as xlz'];
					$res = $YpwBase->get('stand_model_any', $filed, $tv[2].sprintf(" and %s <= '%s' order by %s desc limit 1", $tv[0], $tv[1], $tv[0]), true);
					if(!empty($res['data'])) $temp[] = $res['data'];
					
					$res = $YpwBase->get('stand_model_any', $filed, $tv[2].sprintf(" and %s >= '%s' order by %s asc limit 1", $tv[0], $tv[1], $tv[0]), true);
					if(!empty($res['data'])) $temp[] = $res['data'];

					if(!empty($temp))
					{
						foreach($temp as $gkk=>$gvv)
						{
							$gvv['xl'] = abs((int)$gvv['xlz'] - (int)$tv[1]);
							$sort['xl'][$gkk] = $gvv['xl'];
							$temp[$gkk] = $gvv;
						}
						array_multisort($sort['xl'], SORT_ASC, $temp);

						foreach($temp as $tvv)
						{
							if(empty($minGxb)) $minGxb = $tvv['gxb'];
							if(empty($vinCatchGxb[LibFc::formatNum($tvv['gxb'])])) $vinCatchGxb[LibFc::formatNum($tvv['gxb'])] = $tvv;
						}
						break;
					}
				}
			}
		}


		//相邻找匹配年月
		$data['match_date'] = [];
		
		//日期总表查询
		if(empty($data['sma_year'])){
			$res = $YpwBase->get('yp_allvin_base', ['alb_date', 'alb_from'], sprintf(" and alb_vin = '%s' and length(alb_date) > 4", $vin), true);
			if(!empty($res['data']['alb_date'])){
				if($res['data']['alb_from'] == 'epc'){
					$data['sma_year'] = $res['data']['alb_date'];
				}else if(!empty($Params['smaId'])){
					$data['match_date'][$res['data']['alb_date']] = $res['data']['alb_date'];
				}else{
					$data['sma_year'] = $res['data']['alb_date'];
				}
			}
		}

		if(empty($data['sma_year']) && empty($data['match_date']))
		{
			$whereArr = [
				['sma_vin13_17', $v13_17, sprintf(" and sma_vin1_8='%s' and sma_vin10_12='%s' and sma_year != ''", $vin18, $v10_12)],
				['sma_vin12_17', $v12_17, sprintf(" and sma_vin1_8='%s' and sma_vin10_11='%s' and sma_year != ''", $vin18, $v10_11)]
			];
			foreach($whereArr as $tv)
			{
				$res = $YpwBase->get('stand_model_any', ['sma_year'], $tv[2].sprintf(" and %s <= '%s' order by %s desc limit 1", $tv[0], $tv[1], $tv[0]), true);
				if(!empty($res['data']['sma_year'])) $data['match_date'][$res['data']['sma_year']] = $res['data']['sma_year'];

				$res = $YpwBase->get('stand_model_any', ['sma_year'], $tv[2].sprintf(" and %s >= '%s' order by %s asc limit 1", $tv[0], $tv[1], $tv[0]), true);
				if(!empty($res['data']['sma_year'])) $data['match_date'][$res['data']['sma_year']] = $res['data']['sma_year'];

				if(!empty($data['match_date'])) break;
			}

			//找不到，wmi+10+11
			/*if(empty($data['match_date']))
			{
				$res = $YpwBase->get('stand_model_any', ['sma_year'], sprintf(" and sma_vin1_8 like '%s%%' and sma_vin10_11='%s' and sma_year != '' limit 1", $vin13, $v10_11), true);
				if(!empty($res['data']['sma_year'])) $data['match_date'][$res['data']['sma_year']] = $res['data']['sma_year'];
			}*/
		}
		
		$hasLike = false;
		$reocrWords = $ocrWords.' '.strtr($ocrWords, ['o'=>'0', 'O'=>'0', 'i'=>'1', 'I'=>'1', 'l'=>'1']);
		if(!empty($ocrWords))
		{
			$res = $YpwBase->get('tj_sma_vin12', ['sma_gxb_code_show as gxb, "" sma_vin, 0 as islike'], sprintf(" and sma_vin1_8='%s' and sma_vin10_12='%s' order by length(sma_gxb_code) desc", $vin18, $v10_12));
			foreach($res['data'] as $vv)
			{
				if(stripos($reocrWords, $vv['gxb']) !== false || stripos($reocrWords, strtr($vv['gxb'], [' '=>''])) !== false)
				{
					$vv['islike'] = 1;
					$hasLike = true;
					$vinCatchGxb[LibFc::formatNum($vv['gxb'])] = $vv;
					break;
				}
			}
		}
		
		//OCR检测工信部型号
		if(empty($data['sma_gxb_code_show']) && !empty($ocrWords) && !empty($vinCatchGxb))
		{
			foreach($vinCatchGxb as $kk=>$vv)
			{
				if(empty($vv['islike']) && (stripos($reocrWords, $vv['gxb']) !== false ||  stripos($reocrWords, strtr($vv['gxb'], [' '=>''])) !== false))
				{
					$hasLike = true;
					$vinCatchGxb[$kk]['islike'] = 1;
				}
			}
		}


		if(!$hasLike){
			$res = $YpwBase->get("gxb_params JOIN `gxb_base` ON gb_id = gp_gb_id AND gp_gl_code = 'vin18'", ['gb_gxb_code_show as gxb, "" sma_vin, 0 as islike'], sprintf(" and gp_value='%s' group by gb_gxb_code order by length(gb_gxb_code) desc", $vin18));
			foreach($res['data'] as $vv)
			{
				if(stripos($reocrWords, $vv['gxb']) !== false || stripos($reocrWords, strtr($vv['gxb'], [' '=>''])) !== false)
				{
					$vv['islike'] = 1;
					$hasLike = true;
					$vinCatchGxb[LibFc::formatNum($vv['gxb'])] = $vv;
					break;
				}
			}
			if(!$hasLike && $isJinkou){
				$res = $YpwBase->get("stand_gxb_v8info", ['sgv_gxb_code_show as gxb, "" sma_vin, 0 as islike', 'sgv_org_brand', 'sgv_company'], sprintf(" and sgv_vin1_8='%s' group by sgv_gxb_code, sgv_org_brand order by length(sgv_gxb_code) desc", $vin18));
				foreach($res['data'] as $vv){
					if(stripos($reocrWords, $vv['gxb']) !== false || stripos($reocrWords, strtr($vv['gxb'], [' '=>''])) !== false){
						$vv['islike'] = 1;
						$hasLike = true;
						$vinCatchGxb[LibFc::formatNum($vv['gxb'])] = $vv;
						break;
					}
				}
				if(!$hasLike){
					$tGxb = [];
					$same = [];
					$treArr = [' '=>'', '集团'=>'', '有限'=>'', '公司'=>'', '责任'=>'', '汽车'=>'', '股份'=>'', '服务'=>''];
					$tempTxt = strtr($reocrWords, $treArr);
					foreach($res['data'] as $vv){
						$formatGxb = LibFc::formatNum($vv['gxb']);
						$vv['similar'] = 0;
						foreach(['gxb'=>'gxb', 'company'=>'sgv_company', 'brand'=>'sgv_org_brand'] as $tkk=>$tvv){
							$tval = strtr($vv[$tvv], $treArr);
							$vv['rate'][$tkk] = 0;
							if(strlen($tval) >= 2){
								if($tkk == 'company' || $tkk == 'brand'){	
									$sres = LibFc::textRate($tempTxt, $tval);
									if($sres['same_count'] > 1 && $sres['rate'] > 0.6) $vv['rate'][$tkk] = round($sres['rate'], 2);
								}else{
									$vv['rate'][$tkk] = round(similar_text($tempTxt, $tval) / strlen($tval), 2);
								}
								if($vv['rate'][$tkk]) $vv['similar'] += $vv['rate'][$tkk] == 1? $vv['rate'][$tkk] * 1.2: $vv['rate'][$tkk];
							}
						}
						if($vv['rate']['gxb'] == 1 || $vv['rate']['company'] == 1 || $vv['rate']['brand'] == 1){
							$same[] = $formatGxb;
							$vinCatchGxb[$formatGxb] = $vv;
						}else{
							$tGxb[$formatGxb] = $vv;
							if(isset($vinCatchGxb[$formatGxb])) $vinCatchGxb[$formatGxb] = array_merge($vinCatchGxb[$formatGxb], $vv);
						}
					}
					// 还需要补充的数量
					$remainCount = max(0, 5 - count($same));
					if ($remainCount > 0) {
						uasort($tGxb, function ($a, $b) {
							return $b['similar'] <=> $a['similar'];
						});
						$vinCatchGxb += array_slice($tGxb, 0, $remainCount, true);
					}
				}
			}
		}

		$similar = []; $slike = [];
		foreach($vinCatchGxb as $uk=>$uv){
			$vinCatchGxb[$uk]['similar'] = $uv['similar']?? similar_text($reocrWords, $uv['gxb']);
			$slike[$uk] = (int) $uv['islike'];
			$similar[$uk] = $vinCatchGxb[$uk]['similar'];
		}
		array_multisort($slike, SORT_DESC, $similar, SORT_DESC, $vinCatchGxb);

		$lasetParams = $Params;
		$where = sprintf(" and vii_status = 1 and vii_check_uid=%d", $_SESSION['admin_userid']);
		$where .= empty($Params['last_time'])? '': sprintf(" and vii_check_time < %d", $Params['last_time']);
		$res = $YpwBase->get('stand_vin_imgs', ['vii_id', 'vii_check_time'], $where.' order by vii_check_time desc limit 1', true);
		$lasetParams['vii_id'] = $res['data']['vii_id'];
		$lasetParams['last_time'] = $res['data']['vii_check_time'];
		unset($lasetParams['last_vii_id']);
		unset($lasetParams['smaId']);
		LibTpl::Set('lasetParams', $lasetParams);
		$vinYear = LibFc::VinYear($vin);
		$showEngine6 = $vinYear >= 2017? true: false;
		
		//批量修改
		$othsma = '';
		if(!empty($_POST['othsma']))
		{
			LibRule::Check('CA02');
			$othsma = $_POST['othsma'];
		}

		$othvii = '';
		if(!empty($_POST['othvii']))
		{
			LibRule::Check('CA02');
			$othvii = $_POST['othvii'];
		}

		//需要完整日期的wmi, 其他的全部格式化为年月方便录入
		$data['match_date'] = array_values($data['match_date']);
		$YmdWmiArr = ['LFV', 'L8A', 'LA9', 'LCN', 'LG1', 'LGA', 'LGD', 'LJ8', 'LJU', 'LLV', 'LNJ', 'LNP', 'LNV', 'LNY', 'LRH',
			'LS4', 'LS5', 'LS6', 'LSC', 'LTA', 'LVB', 'LWL', 'LWU', 'LZ0', 'LZ9'
		];
		//if($vinYear >= 2017 && !in_array($vin13, $YmdWmiArr) && !empty($data['match_date']))
		if($vinYear >= 2010 && !in_array($vin13, $YmdWmiArr) && !empty($data['match_date'])){
			foreach($data['match_date'] as $dk=>$dv){
				if(strlen($dv) > 7) $data['match_date'][$dk] = date('Y-m', strtotime($dv));
			}
			$data['match_date'] = array_unique($data['match_date']);
		}

		sort($data['match_date']);
		$months = $data['match_date'];
		for ($i = 0; $i < count($months) - 1; $i++) {
			$current = $months[$i];
			$next = $months[$i + 1];
			if(strlen($current) == 7 && strlen($next) == 7){//相差一个月
				$curDate = DateTime::createFromFormat('Y-m', $current);
				$nextDate = DateTime::createFromFormat('Y-m', $next);
				$diff = (($nextDate->format('Y') - $curDate->format('Y')) * 12) + ($nextDate->format('m') - $curDate->format('m'));
				if ($diff == 2) {
					$curDate->modify('+1 month');
					$data['match_date'][] = $curDate->format('Y-m');
				}
			}else if(strlen($current) > 7 && strlen($next) > 7){//相差一天
				$curDate = DateTime::createFromFormat('Y-m-d', $current);
				$nextDate = DateTime::createFromFormat('Y-m-d', $next);
				$diff = (int)$nextDate->diff($curDate)->format('%a');
				if ($diff == 2) {
					$curDate->modify('+1 day');
					$data['match_date'][] = $curDate->format('Y-m-d');
				}
			}
		}
		$data['match_date'] = array_unique($data['match_date']);
		sort($data['match_date']);

		//其他图片
		$where = !empty($vinOcrImg['vii_id'])? sprintf(" and vii_vin ='%s' and vii_id != %d", $vin, $vinOcrImg['vii_id']): sprintf(" and vii_vin ='%s'", $vin);
		$res = $YpwBase->get('stand_vin_imgs', ['vii_imghost', 'vii_img'], $where);
		$othImgArr = [];
		foreach($res['data'] as $v)
		{
			$othImgArr[] = mvc::$cfg['HOST']['vinimg_'.$v['vii_imghost']].$v['vii_img'];
		}
		
		$where = !empty($vinErr['ve_id'])? sprintf(" and ve_vin='%s' and ve_id !=%d", $vin, $vinErr['ve_id']): sprintf(" and ve_vin='%s'", $vin);
		$res = $PjlBase->get('pl_vin_error', ['*'], $where);
		foreach($res['data'] as $v)
		{
			foreach(explode(',', $v['ve_imgs']) as $im)
			{
				if(!empty($im)) 
					$othImgArr[] = mvc::$cfg['FILE_CENTER']['pjl']['url_get'].'&c=oth&f='.$im.mvc::$cfg['FILE_CENTER']['pjl']['get_uri'];
			}
		}
		LibTpl::Set('othImgArr', array_unique($othImgArr));
		
		$isEpccode = in_array($vin13, ['LFM', 'LVG']) && $vinYear >= 2020;
		LibTpl::Set('isEpccode', $isEpccode);
		if($isEpccode){
			$res = $YpwBase->get('stand_vin_epccode', ['vie_unicode'], sprintf(" and vie_vin='%s'", $vin), true);
			LibTpl::Set('epccode', $res['data']['vie_unicode']?? '');
		}
		$res = $YpwBase->get('stand_vin_file', ['vf_url'], sprintf(" and vf_vin='%s' order by vf_id desc limit 2", $vin));
		LibTpl::Set('vinFile', $res['data']);
		LibTpl::Set('smaFromArr', ['ocr'=>'OCR','org'=>'原有', 'manual'=>'人工', 'catch'=>'采集', 'ZDAPI'=>'泽达', 'wdsp'=>'外调', 'epc'=>'epc', 'buy01'=>'buy01', 'buy02'=>'buy02','rgany'=>'自加']);
		LibTpl::Set('imgtypeArr', ['1'=>'证件','2'=>'铭牌', '0'=>'普通']);
		LibTpl::Set('othvii', $othvii);
		LibTpl::Set('othsma', $othsma);
		LibTpl::Set('minGxb', $minGxb);
		LibTpl::Set('rule', $rule);
		LibTpl::Set('vinYear', $vinYear);
		LibTpl::Set('ocrWords', $ocrWords);
		LibTpl::Set('vin', $vin);
		LibTpl::Set('showEngine6', $showEngine6);
		LibTpl::Set('engine6Work', $engine6Work);
		LibTpl::Set('vinDecode', $vinDecode);
		LibTpl::Set('vinCatchGxb', $vinCatchGxb);
		LibTpl::Set('isJinkou', $isJinkou);
		LibTpl::Set('data', $data);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','管理其它VIN解码');
		LibTpl::Put();
	}

	/**
	 * @method  管理卡车尺寸统计
	 * @author soul
	 * @copyright 2023/5/6
	 */
	function standModelAnySet()
	{
		LibRule::Check('CA01');
		$YpwUser = new YpwUser();
		$res = $YpwUser->standModelAnySet($_POST);
		LibFc::ajaxJsonEncode($res);
	}


	/**
	 * @method 删除AIOCR记录
	 * @author zhengweihua
	 * @copyright 2026/8/24
	 */
	function standVinImgsOcraiDel()
	{
		LibRule::Check('CA09');
		$viiId = (int) $_POST['vii_id'];
		if($viiId < 1)
		{
			LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'vii_id不能为空']);
		}
		$YpwBase = new YpwBase();
		$res = $YpwBase->del('stand_vin_imgs_ocrai', sprintf(" and via_vii_id=%d", $viiId));
		LibFc::ajaxJsonEncode($res);
	}

	// Third-party VIN gxb lookup
	function getVinGxbByOth()
	{
		LibRule::Check('CA09');
		$Params = MVC::$URL_PARAMS;
		$spGxbArr = [];
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('vin/catchAnyVinfromWdspApi', [], ['vins'=>$Params['vin'], 'addToSma'=>0]);
		if(!empty($res['data'][$Params['vin']]['sgs_gxb_soupei']))
		{
			$spGxbArr = explode(',', $res['data'][$Params['vin']]['sgs_gxb_soupei']);
		}
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$spGxbArr]);
	}


	/**
	 * @method    删除其它VIN解码
	 * @author soul
	 * @copyright 2019/1/22
	 */
	function standModelAnyDel()
	{
		LibRule::Check('CA05');
		$YpwBase = new YpwBase();
		if(!empty($_POST['smaIds']))
		{
			$res = $YpwBase->get('stand_model_any', ['sma_vin'], sprintf(" and sma_id in (%s)", implode(',', $_POST['smaIds'])));
			if(!empty($res['data']))
			{
				$vins = array_column($res['data'], 'sma_vin');
				$YpwBase->del('yp_allvin_base', sprintf(" and alb_vin in ('%s') and alb_from ='manual'", implode("','", $vins)));
				$YpwBase->set('stand_vin_imgs', ['vii_status'=>'0'],sprintf(" and vii_vin in ('%s') and vii_status=1", implode(',', $vins)));
				$YpwBase->del('stand_model_any', sprintf(" and sma_id in (%s)", implode(',', $_POST['smaIds'])));
			}
		}
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>true]);
	}

	//文本匹配型号生产厂
	function getGxbCompany()
	{
		$arr = [];
		if($_POST['ocrtxt']){
			$ocrtxt = $_POST['ocrtxt'];
			$arr['company'] = [];
			$YpwBase = new YpwBase();
			$res = $YpwBase->get("stand_gxb_v8info", ['sgv_country', 'sgv_company'], " and sgv_org_brand != '' and sgv_country != '' group by sgv_company");
			$treArr = [' '=>'', '集团'=>'', '有限'=>'', '公司'=>'', '责任'=>'', '汽车'=>'', '股份'=>'', '服务'=>''];
			$tempTxt = strtr($ocrtxt, $treArr);
			foreach($res['data'] as $vv){
				$vv['similar'] = 0;
				foreach(['company'=>'sgv_company'/*, 'country'=>'sgv_country'*/] as $tkk=>$tvv){
					$tval = strtr($vv[$tvv], $treArr);
					if(strlen($tval) >= 2){
						$sres = LibFc::textRate($tempTxt, $tval);
						if($sres['same_count'] > 1 && $sres['rate'] > 0.6){
							$vv['rate'][$tkk] = round($sres['rate'], 2);
							$vv['similar'] += $vv['rate'][$tkk] == 1? $vv['rate'][$tkk] * 1.2: $vv['rate'][$tkk];
						}
					}else{
						$vv['rate'][$tkk] = 0;
					}
				}
				if($vv['similar'] > 0.5){
					$arr['company'][] = $vv;
				}
			}
			uasort($arr['company'], function ($a, $b) {
				return $b['similar'] <=> $a['similar'];
			});
			
			$arr['company'] = array_values($arr['company']);
			if($arr['company'][0]['rate']['company'] == 1 && $arr['company'][0]['rate']['country'] == 1){
				$arr['company'] = array_slice($arr['company'], 0, 1, true);
			}else{
				$arr['company'] = array_slice($arr['company'], 0, 2, true);
			}
		}
		LibFc::ReturnJson(true, $arr);
	}

	/**
	 * @method   查询工信部型号的基本信息
	 * @author soul
	 * @copyright 2019/1/22
	 */
	function getGxbcodeInfo()
	{
		$Params = $_POST;
		$YpwBase = new YpwBase();
		$arr = [];
		if(!empty($Params['gxbcode']))
		{
			$vin = LibFc::FormatVin($Params['vin']);
			$isJinkou = in_array(substr($vin, 0, 1), ['L','H'])? false: true;
			$vin18 = !empty($Params['vin']) ? substr($vin, 0, 8): '';
			$vin18 = LibFc::FormatNum($vin18);
			$gxbAllMatch = !empty($Params['gxbAllMatch']) ? 1: 0;
			$gxbNum = $Params['gxbcode'];
			$formatGxbNum = LibFc::FormatNum($gxbNum);
			$othArr = [];
			if(!$gxbAllMatch)
			{
				if(!empty($Params['sma_weight'])) $othArr['sma_weight'] = $Params['sma_weight'];
				if(!empty($Params['max_weight'])) $othArr['max_weight'] = $Params['max_weight'];
			}

			$isCnGxb = true;
			if($isJinkou)
			{
				if($gxbAllMatch){
					$res = $YpwBase->get('gxb_base JOIN gxb_params ON gb_id = gp_gb_id and gb_type="gxb"', ['gb_gxb_code'], sprintf(" AND gb_gxb_code='%s' and gp_gl_code='vin18' and gp_value='%s'", $formatGxbNum, $vin18));
				}else{
					$res = $YpwBase->get('gxb_base', ['gb_gxb_code'], sprintf(" and gb_type='gxb' AND gb_gxb_code='%s'", $formatGxbNum));
				}
				if(empty($res['data'])) $isCnGxb = false;
			}

			//进口
			if(!empty($vin18) && !$isCnGxb)
			{
				$ocrtxt = $Params['ocrtxt'] ?? '';
				$where = sprintf(" and sma_vin1_8 ='%s' and sma_brand != '' AND sma_gxb_code = '%s' GROUP BY sma_brand, sma_engine, sma_kw, sma_cc, sma_passenger ORDER BY sma_brand, sma_engine DESC, sma_kw DESC, sma_cc DESC, sma_passenger DESC", $vin18, $formatGxbNum);
				$table = 'stand_model_any left join stand_gxb_v8info on sma_brand=sgv_org_brand and sgv_vin1_8=sma_vin1_8 and sma_gxb_code = sgv_gxb_code';
				$res = $YpwBase->get($table, ['sma_id,sma_gxb_code_show,sma_brand,sma_engine,sma_kw,sma_cc,sma_passenger, max(sgv_country) sgv_country, max(sgv_company) sgv_company'], $where);
				if(!empty($res['data']))
				{
					foreach($res['data'] as $tv)
					{
						$unikey = md5($tv['sma_brand'].'@'.$tv['sma_engine'].'@'.$tv['sma_kw'].'@'.$tv['sma_cc']);
						$tv['url'] = 'https://admin.paojd.cn/ypcCar/standModelAnyAdd?smaId='.$tv['sma_id'];
						if(empty($tv['sma_passenger'])) $tv['sma_passenger'] = '';
						if(empty($vals[$unikey]))
						{
							$vals[$unikey] = $tv;
						}
						else if(!empty($tv['sma_passenger']))
						{//合并座位数
							if(empty($vals[$unikey]['sma_passenger']))
							{
								$vals[$unikey]['sma_passenger'] = $tv['sma_passenger'];
							}
							else if(stripos(','.$vals[$unikey]['sma_passenger'].',', ','.$tv['sma_passenger'].',') === false)
							{
								$vals[$unikey]['sma_passenger'] .= ','.$tv['sma_passenger'];
							}
						}
					}
					
					if($ocrtxt){
						$treArr = [' '=>'', '集团'=>'', '有限'=>'', '公司'=>'', '责任'=>'', '汽车'=>'', '股份'=>'', '服务'=>''];
						$tempTxt = strtr($ocrtxt, $treArr);
						$sort = [];
						$i =0;
						foreach($vals as $uk=>$uv){
							$i++;
							$pos = 0;
							if($uv['sma_brand']){	
								$sres = LibFc::textRate($tempTxt, strtr($uv['sma_brand'], $treArr));
								if($sres['same_count'] > 1 && $sres['rate'] > 0.6) $pos += round($sres['rate'], 2)*1.5;
								//$pos += similar_text($ocrtxt, $uv['sma_brand'])*1.5;
							}
							if(strlen($uv['sma_engine']) >= 3){
								$sres = LibFc::textRate($tempTxt, strtr($uv['sma_engine'], $treArr));
								if($sres['same_count'] > 2 && $sres['rate'] > 0.6) $pos += round($sres['rate'], 2);
								//$pos += similar_text($ocrtxt, $uv['sma_engine']);
							}
							if($uv['sgv_company']){
								$sres = LibFc::textRate($tempTxt, strtr($uv['sgv_company'], $treArr));
								if($sres['same_count'] > 1 && $sres['rate'] > 0.6) $pos += round($sres['rate'], 2);
								//$pos += similar_text($ocrtxt, $uv['sgv_company']);
							}
							if($uv['sgv_country']){
								$sres = LibFc::textRate($tempTxt, strtr($uv['sgv_country'], $treArr));
								if($sres['same_count'] > 1 && $sres['rate'] > 0.6) $pos += round($sres['rate'], 2)*1.2;
								//$pos += similar_text($ocrtxt, $uv['sgv_country'])*1.2;
							}
							$vals[$uk]['sort'] = $pos;
							$sort[$uk] = $pos;
						}
						array_multisort($sort, SORT_DESC, $vals);
						$vals = array_values($vals);
					}
					if(!empty($Params['sma_brand'])){
						$newVals = [];
						$newVals2 = [];
						$reArr = [' '=>''];
						$smaBrand = strtoupper(strtr($Params['sma_brand'], $reArr));
						foreach($vals as $uk=>$uv)
						{
							if(strtoupper(strtr($uv['sma_brand'], $reArr)) == $smaBrand){
								$newVals[$uk] = $uv;
							}else{
								$newVals2[$uk] = $uv;
							}
						}
						foreach($newVals2 as $uk=>$uv){
							$newVals[$uk] = $uv;
						}
						$vals = array_values($newVals);
					}
					$arr['site']['sma'] = [
						'name'=>'600W',
						'vals'=>$vals
					];
				}
			}
			else
			{
				$LibYpApi = new LibYpApi();
				$res = $LibYpApi->Get('vin/catchGxbcodeInfo', [], ['gxbNum'=>$gxbNum, 'gxbAllMatch'=>$gxbAllMatch, 'vin'=>$vin, 'othArr'=>json_encode($othArr)]);
				$arr = $res['data'];
				if($Params['ocrtxt'] && stripos($arr['merge']['sma_weight'], ',') !== false){
					$res = $LibYpApi->Get('vin/matchAnyByVinGxbTxt', [], ['gxbNum'=>$gxbNum, 'ocrtxt'=>$Params['ocrtxt'], 'vin'=>$vin, 'comFileds'=>'sma_weight']);
					 if($res['data']['sma_weight']) $arr['sma_weight'] = $res['data']['sma_weight'];
				}
			}
			$flag = false;
			if($_SESSION['ad_user_name'] == 'yiparts' || (!empty($_SESSION['admin_rule']) && in_array('CA02', $_SESSION['admin_rule']))){
				$flag =true;
			}
			$arr['edit'] = $flag;
			$arr['edit_url'] = mvc::$cfg['HOST']['hubloc'].'gxb/updateHtml';
			$arr['year'] = LibFc::VinYear($vin);
			$arr['isnew'] = abs(date('Y') - $arr['year']) < 2? 1: 0;
			//查找是否有规则 工信部型号+vin1-8+vin10-12
			$res = $YpwBase->get('stand_model_reg', ['smr_id'], sprintf(" and smr_gxb_code='%s' and smr_vin1_8='%s' and smr_vin10_12='%s' limit 1", LibFc::FormatNum($gxbNum), $vin18, substr($vin, 9, 3)), true);
			$arr['reg'] = $res['data'];
			if(empty($arr['reg'])){
				//验证车架号是否正确
				$h = date('H');
				$engine6Work = $h < 7 || $h >= 20? false: true;
				if($engine6Work && empty($Params['engine6']) && $arr['year'] >= 2017){
					$LibYpApi = new LibYpApi();
					$res = $LibYpApi->Get('vin/catchVinQingdan', ['engine6'=>'000000', 'vin'=>$vin], [], true);
					if(stripos($res['data'], '不符') !== false){
						$arr['chkvin'] = 'ok';
					}
				}
				
				//型号是否为最新一年内采集的
				if($arr['isnew']){
					$res = $YpwBase->get('gxb_base', ['max(gb_pici) gb_pici', 'max(gb_publish) gb_publish'], sprintf(" AND gb_gxb_code='%s' and gb_pici >= (SELECT min(gb_pici) FROM gxb_base WHERE gb_publish > %d) limit 1", $formatGxbNum, date('Ymd', strtotime('-1year'))), true);
					$arr['chkgxb'] = $res['data'];
				}
			}
		}
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$arr]);
	}



	function textSimilarity($str1, $str2, $maxGap = 1)
	{
		$source = preg_split('//u', $str1, -1, PREG_SPLIT_NO_EMPTY);
		$target = preg_split('//u', $str2, -1, PREG_SPLIT_NO_EMPTY);

		if ($source === false || $target === false) {
			return array(
				'similarity' => 0,
				'same_count' => 0,
				'same_chars' => '',
				'matched_text' => ''
			);
		}

		$sourceCount = count($source);
		$targetCount = count($target);
		$maxGap = max(0, (int) $maxGap);

		if ($sourceCount === 0 || $targetCount === 0) {
			return array(
				'similarity' => 0,
				'same_count' => 0,
				'same_chars' => '',
				'matched_text' => ''
			);
		}

		$calculateMatches = function ($segment) use ($target, $maxGap) {
			$segmentCount = count($segment);
			$targetCount = count($target);
			$dp = array();

			for ($i = 0; $i <= $segmentCount; $i++) {
				for ($j = 0; $j <= $targetCount; $j++) {
					$dp[$i][$j] = array_fill(0, $maxGap + 1, null);
				}
			}

			$dp[0][0][0] = array(
				'count' => 0,
				'chars' => array()
			);

			for ($i = 0; $i <= $segmentCount; $i++) {
				for ($j = 0; $j <= $targetCount; $j++) {
					for ($gap = 0; $gap <= $maxGap; $gap++) {
						$current = $dp[$i][$j][$gap];

						if ($current === null) {
							continue;
						}

						// 正常逐字比较
						if ($i < $segmentCount && $j < $targetCount) {
							$next = $current;

							if ($segment[$i] === $target[$j]) {
								$next['count']++;
								$next['chars'][] = $target[$j];
							}

							$old = $dp[$i + 1][$j + 1][$gap];

							if ($old === null || $next['count'] > $old['count']) {
								$dp[$i + 1][$j + 1][$gap] = $next;
							}
						}

						if ($gap < $maxGap) {
							// str1 多了一个字，跳过 str1 当前字
							if ($i < $segmentCount) {
								$old = $dp[$i + 1][$j][$gap + 1];

								if (
									$old === null ||
									$current['count'] > $old['count']
								) {
									$dp[$i + 1][$j][$gap + 1] = $current;
								}
							}

							// str1 漏了一个字，跳过 str2 当前字
							if ($j < $targetCount) {
								$old = $dp[$i][$j + 1][$gap + 1];

								if (
									$old === null ||
									$current['count'] > $old['count']
								) {
									$dp[$i][$j + 1][$gap + 1] = $current;
								}
							}
						}
					}
				}
			}

			$best = array(
				'count' => 0,
				'chars' => array()
			);

			for ($gap = 0; $gap <= $maxGap; $gap++) {
				$result = $dp[$segmentCount][$targetCount][$gap];

				if ($result !== null && $result['count'] > $best['count']) {
					$best = $result;
				}
			}

			return $best;
		};

		$best = array(
			'count' => 0,
			'chars' => array(),
			'text'  => ''
		);

		$minLength = max(1, $targetCount - $maxGap);
		$maxLength = min($sourceCount, $targetCount + $maxGap);

		// 在 str1 中寻找最相似的局部文本
		for ($length = $minLength; $length <= $maxLength; $length++) {
			for (
				$start = 0;
				$start + $length <= $sourceCount;
				$start++
			) {
				$segment = array_slice($source, $start, $length);
				$result = $calculateMatches($segment);

				if ($result['count'] > $best['count']) {
					$best['count'] = $result['count'];
					$best['chars'] = $result['chars'];
					$best['text'] = implode('', $segment);
				}
			}
		}

		return array(
			'similarity'  => $best['count'] / $targetCount,
			'percent'     => round($best['count'] / $targetCount * 100, 2),
			'same_count'  => $best['count'],
			'same_chars'  => implode('', $best['chars']),
			'matched_text'=> $best['text']
		);
	}


	
	//通过发动机后6位获取车架号的工信部型号和生产日期
	function getVinByEngine6()
	{
		$Params = MVC::$URL_PARAMS;
		$LibYpApi = new LibYpApi();
		$reArr = ['？'=>'?', '！'=>'!'];
		$engine6 = strtr($Params['engine6'], $reArr);
		if(stripos(strtr($engine6, ['?'=>'算', '%'=>'算', '!'=>'算']), '算') !== false)
		{//计算可能号码
			$Params['vin'] = LibFc::FormatNum($Params['vin']);
			$bstr = strlen($engine6) > 6? substr($engine6, 0, strlen($engine6) - 6): '';
			$estr = strlen($engine6) > 6? substr($engine6, - 6): $engine6;
			$engine6Arr = [];
			//?[数字]  %[字母]  ![字符]
			$charArr = [
				'?'=>'0123456789',
				'%'=>'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
				'!'=>'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
			];
			$ebArr = str_split($estr);
			foreach($ebArr as $k=>$v)
			{
				if(empty($charArr[$v])) continue;
				$vb = $k > 0 ? substr($estr, 0, $k) : '';
				$ve = $k < 6 ? substr($estr, $k+1) : '';
				$YpwBase = new YpwBase();
				$where = sprintf(" and sma_vin1_8='%s' and sma_vin10_12='%s' and sma_engine6 like '%%%s_%s' group by cb order by count(*) desc", substr($Params['vin'], 0, 8), substr($Params['vin'], 9, 3), $vb, $ve);
				$res = $YpwBase->get('stand_model_any', ['distinct substring(right(sma_engine6,6), '.($k+1).',1) cb'], $where);
				$isChars = array_column($res['data'], 'cb');
				foreach(str_split($charArr[$v]) as $cv)
				{
					if(!in_array($cv, $isChars)) $isChars[] = $cv;
				}
				foreach($isChars as $ch)
				{
					$engine6Arr[] = $bstr.$vb.$ch.$ve;
				}
				break;
			}
		}
		else
		{
			$engine6Arr = [$engine6];
		}
		$arr = [];
		foreach($engine6Arr as $ek=>$e6)
		{
			$res = $LibYpApi->Get('vin/catchVinQingdan', ['engine6'=>$e6, 'vin'=>$Params['vin']], [], true);
			//还有其他发动机编码，错了继续
			if($ek+1 != count($engine6Arr) && !$res['status'] && stripos($res['data'], '不符') !== false)
				continue;
			LibFc::ajaxJsonEncode($res);
		}
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$arr]);
	}

	
	function catchGgcar()
	{
		$Params = MVC::$URL_PARAMS;
		$arr = [];
		switch($Params['site'])
		{
			case 'chinacar':
				if(preg_match('/id\=([0-9a-zA-Z]+)/', $Params['url'], $match))
				{
					$res = $this->getChinacarGg([$match[1]]);
					$arr = $res[$match[1]];
				}
			break;
			case 'cn357':
				if(preg_match('/(notice[^"]+)/', $Params['url'], $match))
				{
					$res = $this->getCn357Gg([$match[1]]);
					$arr = $res[$match[1]];
				}
			break;
		}
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$arr]);
	}


	/**
	 * @method  号码规则
	 * @author soul
	 * @copyright 2019/12/9
	 */
	function standModelReg()
	{
		LibRule::Check('CA06');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$where = '';
		$YpwBase = new YpwBase();
		
		$ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
		$orderArr = [
			'ord1'=>['order by FIELD(smr_status, 0, 1, -1), smr_gxb_code, smr_vin1_8, smr_vin10_12', '综合'],
			'ord2'=>['order by smr_add_time desc', '添加时间'],
			'ord3'=>['order by smr_check_time desc', '审核时间']
		];
		LibTpl::Set('orderArr', $orderArr);
		$order = empty($Params['order']) || empty($orderArr[$Params['order']]) ? 'ord1': $Params['order'];
		$order = $orderArr[$order][0];

		foreach($Params as $K=>$V)
		{
			$V = trim($V);
			if($V == '') continue;
			switch($K)
			{
				case 'smr_status':
					$where .= sprintf(" AND smr_status =%d", $V);
				break;
				case 'smr_vin1_8':
				case 'smr_vin10_12':
				case 'sma_kw':
				case 'smr_add_user':
					$where .= sprintf(" AND %s like '%s'", $K, strtr($V, $ReLike));
				break;
				case 'smr_gxb_code':
					$where .= sprintf(" AND %s like '%s'", $K, LibFc::FormatNum(strtr($V, $ReLike), '%_'));
				break;
				case 'addTime': $where .= sprintf(" and smr_add_time >= %d", strtotime($V)); break;
				case 'endTime': $where .= sprintf(" and smr_add_time <= %d", strtotime($V.' 23:59:59')); break;
			}
		}
		$vinArr = [];
		$Res = $YpwBase->get('stand_model_reg', array('count(*) as count'), $where, true);
		$Count = $Res['data']['count'];
		$Page = LibPage::show($Count, $perPage);
		
		if($Count > 0)
		{
			$Res = $YpwBase->get('stand_model_reg', ['*'], sprintf("%s %s LIMIT %d,%d", $where, $order, ($nowPage-1)*$perPage,$perPage));
			$vinArr = $Res['data'];
		}
		LibTpl::Set('Page', $Page);
		

		$statusArr = [
			0=>'待核对',
			1=>'已核对',	
			-1=>'无效'	
		];
		LibTpl::Set('statusArr', $statusArr);

		LibTpl::Set('vinArr', $vinArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','VIN规则');
		LibTpl::Put();
	}


	/**
	 * @method VIN规则删除、审核
	 * @author soul
	 * @copyright 2019/1/22
	 */
	function standModelRegEdit()
	{
		LibRule::Check('CA06');
		$YpwBase = new YpwBase();
		$res=['status'=>true,'data'=>''];
		if(!empty($_POST['smrIds']) && !empty($_POST['act']))
		{
			$where = sprintf(" and smr_id in (%s)", implode(',', $_POST['smrIds']));
			if($_POST['act'] == 'ok')
			{
				$res = $YpwBase->set('stand_model_reg', ['smr_status'=>1, 'smr_check_user'=>mvc::$cfg['LOGUSER']['urname'], 'smr_check_time'=>time()], $where);
			}
			else if($_POST['act'] == 'err')
			{
				$res = $YpwBase->set('stand_model_reg', ['smr_status'=>-1, 'smr_check_user'=>mvc::$cfg['LOGUSER']['urname'], 'smr_check_time'=>time()], $where);
			}
			else if($_POST['act'] == 'del')
			{
				$res = $YpwBase->del('stand_model_reg', $where);
			}
		}
		LibFc::ajaxJsonEncode($res);
	}



	//审核VIN规则
	function checkVinReg()
	{
		LibRule::Check('CA06');
		$Params = MVC::$URL_PARAMS;
		$YpwBase = new YpwBase();
		$PjlBase= new PjlBase();
		if(!empty($_POST['smr_id']) && !empty($_POST['smr_status']))
		{
			unset($Params['last_time']);
			$YpwUser = new YpwUser();
			$YpwUser->checkVinReg($_POST['smr_id'], $_POST['smr_status']);
			
			$where = ' and smr_status = 0';
			foreach($Params as $K=>$V)
			{
				$V = trim($V);
				if($V == '') continue;
				switch($K)
				{
					case 'smr_vin1_8':
					case 'smr_vin10_12':
					case 'sma_kw':
					case 'sma_kw':
						$where .= sprintf(" AND %s like '%s'", $K, strtr($V, $ReLike));
					break;
					case 'smr_gxb_code':
						$where .= sprintf(" AND %s like '%s'", $K, LibFc::FormatNum(strtr($V, $ReLike), '%_'));
					break;
					case 'addTime': $where .= sprintf(" and smr_add_time >= %d", strtotime($V)); break;
					case 'endTime': $where .= sprintf(" and smr_add_time <= %d", strtotime($V.' 23:59:59')); break;
				}
			}
			$res = $YpwBase->get('stand_model_reg', ['smr_id'], $where.' order by smr_gxb_code, smr_vin1_8, smr_vin10_12', true);
			if(!empty($res['data']))
			{
				$Params['smr_id'] = $res['data']['smr_id'];
				LibFc::Go(mvc::$cfg['ADMIN_URI'].'ypcCar/checkVinReg?'.http_build_query($Params));
			}
			else
			{
				LibTpl::Success('操作成功');
			}
			exit();
		}

		$res = $YpwBase->get('stand_model_reg', ['*'], sprintf(" and smr_id=%d", $Params['smr_id']), true);
		if(empty($res['data']))
		{
			LibTpl::Error('规则不存在！');
		}
		$regArr = $res['data'];
		
		$regArr['vin'] = [];
		$comWhere = sprintf(" and sma_gxb_code='%s' and sma_vin1_8='%s' and sma_vin10_12='%s'", $regArr['smr_gxb_code'], $regArr['smr_vin1_8'], $regArr['smr_vin10_12']);

		$res = $YpwBase->get('stand_model_any', ['count(*) as count'], $comWhere, true);
		$regArr['vin_count'] = $res['data']['count'];


		$res = $YpwBase->get('stand_model_any', ['*'], $comWhere.' order by sma_vin13_17 asc limit 1', true);
		if(!empty($res['data']))
		{
			$tArr = $res['data'];
			$tArr['type'] = '最小';
			$regArr['vin'][$tArr['sma_vin']] = $tArr;
			if(empty($tArr['sma_year']))
			{
				//最小年月
				$res = $YpwBase->get('stand_model_any', ['*'], $comWhere." and sma_year != '' order by sma_year asc limit 1", true);
				if(!empty($res['data']))
				{
					$tArr = $res['data'];
					$tArr['type'] = '最小年';
					$regArr['vin'][$tArr['sma_vin']] = $tArr;
				}
			}
		}
		
		$res = $YpwBase->get('stand_model_any', ['*'], $comWhere.' order by sma_vin13_17 desc limit 1', true);
		if(!empty($res['data']))
		{
			$res['data']['type'] = '最大';
			$regArr['vin'][$res['data']['sma_vin']] = $res['data'];
			if(empty($tArr['sma_year']))
			{
				//最小年月
				$res = $YpwBase->get('stand_model_any', ['*'], $comWhere." and sma_year != '' order by sma_year desc limit 1", true);
				if(!empty($res['data']))
				{
					$tArr = $res['data'];
					$tArr['type'] = '最大年';
					$regArr['vin'][$tArr['sma_vin']] = $tArr;
				}
			}
		}

		$mergeFiled = ['sma_vin', 'sma_brand', 'sma_engine', 'sma_cc', 'sma_kw', 'sma_length', 'sma_width', 'sma_height', 'sma_wheel', 'sma_axle', 'sma_weight', 'sma_passenger', 'sma_vtype', 'sma_year'];
		foreach($mergeFiled as $filed)
		{
			$vals = [];
			foreach($regArr['vin'] as $v)
			{
				if(!empty($v[$filed])) $vals[] = $v[$filed];
			}
			$vals = array_unique($vals);
			sort($vals);
			$regArr['merge'][$filed] = $vals;
		}

		
		if(!empty($regArr['vin']))
		{
			//找图片
			$res = $YpwBase->get('stand_vin_imgs', ['*'], sprintf(" and vii_vin in ('%s') and vii_img != '' and vii_status=1 order by right(vii_vin, 5)", implode("','", array_keys($regArr['vin']))));
			foreach($res['data'] as $v)
			{
				$v['ve_check'] = json_decode($v['ve_check'],true);
				$v['vii_img'] = mvc::$cfg['HOST']['vinimg_'.$v['vii_imghost']].$v['vii_img'];
				$regArr['vinimgs'][$v['vii_vin']] = $v;
			}
		}


		$lasetParams = $Params;
		$where = ' and smr_status != 0';
		$where .= empty($Params['last_time'])? '': sprintf(" and smr_check_time < %d", $Params['last_time']);
		$res = $YpwBase->get('stand_model_reg', ['smr_id', 'smr_check_time'], $where.' order by smr_check_time desc limit 1', true);
		$lasetParams['smr_id'] = $res['data']['smr_id'];
		$lasetParams['last_time'] = $res['data']['smr_check_time'];
		LibTpl::Set('lasetParams', $lasetParams);


		$statusArr = [
			0=>'待审核',
			1=>'已审核【有效】',	
			-1=>'已审核【无效】'
		];
		LibTpl::Set('statusArr', $statusArr);

		LibTpl::Set('regArr', $regArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','审核VIN规则');
		LibTpl::Put();
	}


	//更新本地车型工信部型号到线上
	function updateYpcarGxbcode()
	{
		//LibRule::Check('CA06');
		$YpwUser = new YpwUser();
		$res = $YpwUser->updateYpcarGxbcode();
		echo 'ok';
	}

	//vin 统计
	public function standModelAnyTj()
    {
        LibRule::Check('CA13');
        $Params = mvc::$URL_PARAMS;
        $nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
        $where = '';
        $YpwBase = new YpwBase();
		$res = $YpwBase->get("yp_vin_year",['vin_year, vin_10'],' ORDER BY vin_year');
		$vin10YearArr = array_column($res['data'], 'vin_10','vin_year');
		
        //最大的结束时间
        $maxYear = $YpwBase->get("stand_model_tj",['max(smt_eyear) as smt_eyear'],'',true);
        //最小的开始时间
        $minYear = $YpwBase->get("stand_model_tj",['min(smt_byear) as smt_byear'],'',true);
        $yearSelect = range($minYear['data']['smt_byear'] ?: 0,$maxYear['data']['smt_eyear'] ?: 0);
        arsort($yearSelect);
        LibTpl::Set('yearSelect',$yearSelect);
        $ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
        $orderBy = 'smt_vin_count desc';
        foreach($Params as $K=>$V)
        {
            $V = trim($V);
            if($V == '') continue;
            switch($K)
            {
				case 'vin1':
					$where .= $V == '!L'? " AND smt_vin1_8 not like 'L%' AND smt_vin1_8 not like 'H%'": " AND (smt_vin1_8 like 'L%' OR smt_vin1_8 like 'H%')";
				break;
                case 'smt_vin':
                    $anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($V))));
                    if(count($anyNum) > 1)
                    {
                        foreach($anyNum as $kk=>$vv)
                        {
                            $anyNum[$kk] = LibFc::FormatVin($vv);
                        }
                        $where .= sprintf(" and smt_vin1_8 IN ('%s')", implode("','", $anyNum));
                    }
                    else
                    {
                        $V = LibFc::FormatNum(strtr($V, $ReLike), '%_');
                        if(strlen($V) <= 8)
                            $where .= sprintf(" AND smt_vin1_8 like '%s%%'", $V);
                        else
                            $where .= sprintf(" AND smt_vin1_8 like '%s%%'", $V);
                    }
                    break;
                case 'smt_gxb_code':
                    $anyNum = array_unique(explode("\r\n", strtr(trim($V), [';'=>"\r\n", ','=>"\r\n"])));
                    if(count($anyNum) > 1)
                    {
                        foreach($anyNum as $kk=>$vv)
                        {
                            $anyNum[$kk] = LibFc::FormatNum($vv);
                        }
                        $where .= sprintf(" and smt_gxb_code IN ('%s')", implode("','", $anyNum));
                    }
                    else
                    {
                        $where .= sprintf(" AND smt_gxb_code like '%s'", LibFc::FormatNum(strtr($V, $ReLike), '%_'));
                    }
                    break;
				case 'ypvin8':
					$ypcardb_name = mvc::$cfg['DB']['YP_CAR']['db_name'];
					if($V == 'Y'){
						$where .= sprintf(" and smt_vin1_8 in (SELECT DISTINCT vin_full FROM %s.yp_vin_model3_link JOIN %s.yp_model3 ON M3_ID = vm3_m3_id JOIN %s.yp_vin ON vin_id = vm3_vin_id GROUP BY vin_full)",$ypcardb_name, $ypcardb_name, $ypcardb_name);
					}else if($V == 'N'){
						$where .= sprintf(" and smt_vin1_8 not in (SELECT DISTINCT vin_full FROM %s.yp_vin_model3_link JOIN %s.yp_model3 ON M3_ID = vm3_m3_id JOIN %s.yp_vin ON vin_id = vm3_vin_id GROUP BY vin_full)",$ypcardb_name, $ypcardb_name, $ypcardb_name);
					}
				break;
				case 'ypcar': 
					if($V == 'Y1'){
						$where .= " and gxb_vin1_8 is not null and gxb_manual = 1";
					}else if($V == 'Y3'){
						$where .= " and gxb_vin1_8 is not null and gxb_kcauto = 1";
					}else if($V == 'Y1Y3'){
						$where .= " and gxb_vin1_8 is not null and gxb_manual = 1 and gxb_kcauto = 1";
					}else if($V == 'Y2'){
						$where .= " and gxb_vin1_8 is null and sgv_model != '' AND sgv_brand != ''";
					}else if($V == 'Y'){
						$where .= " and (gxb_vin1_8 is not null or (sgv_model != '' AND sgv_brand != ''))";
					}else if($V == 'N'){
						$where .= " and gxb_vin1_8 is null and (sgv_model is null or sgv_model = '' or sgv_brand = '')";
					}
				break;
				case 'dpcar':
					if($V == 1){
						$where .= ' and smt_gxb_code in (select distinct sgd_gxb_code from stand_gxb_dipan join stand_model_ypgxb on gxb_code = sgd_dpgxb_code)';
					}else if($V == -1){
						$where .= " and smt_gxb_code in (select distinct sgd_gxb_code from stand_gxb_dipan where sgd_dpgxb_code not in (select gxb_code from stand_model_ypgxb))";
					}
				break;
				case 'smt_brand':
				case 'smt_vtype':
					$where .= sprintf(" AND %s like '%s'", $K, strtr($V, $ReLike));
				break;
				case 'smt_gtype':
					$where .= sprintf(" and smt_gtype IN ('%s')", implode("','", str_split($V)));
				break;
				case 'smt_gtype':
					$where .= sprintf(" and smt_gtype IN ('%s')", implode("','", str_split($V)));
				break;
				case 'sgb_rname':
					$where .= sprintf(" and (sgb_rname like '%%%s%%' or sgv_model like '%%%s%%')", $V, $V);
				break;
                case 'smt_eyear':
                    $where .= sprintf(" and smt_eyear >= '%s'",$V);
                    break;
				case 'sgv_ispxjk':
					if($V == 1){
						$where .= " and sgv_ispxjk = 1";
					}else if($V == -1){
						$where .= " and (sgv_ispxjk != 1 or sgv_ispxjk is null)";
					}
                    break;
				case 'hasmake': 
					if($V == 1){
						$where .= " and smt_brand != ''";
					}else if($V == -1){
						$where .= " and smt_brand = ''";
					}
				break;
                case "sort":
                    if($V == 1){
                        $orderBy = 'smt_vin1_8 asc';
                    } elseif ($V == 2){
                        $orderBy = 'smt_vin1_8 desc';
                    } elseif ($V == 3){
                        $orderBy = 'smt_vin_count asc';
                    }else{
                        $orderBy = 'smt_vin_count desc';
                    }
                break;
				case 'sma_vin10':
					$tw = [];
					foreach(str_split($V) as $tv)
					{
						if(trim($tv) != '')
						{
							$tw[] = sprintf(" smt_vin10 like '%%%s%%'", $tv);
						}
					}
					if(!empty($tw))
						$where .= sprintf(" and (%s)", implode(" or ", $tw));
				break;
				case 'yearerr':
					$where .= sprintf(" and locate(smt_vin10, '%s') = 0", implode(',', $vin10YearArr));
				break;
            }
        }
        $table = "stand_model_tj 
		left join stand_gxb_base on smt_gxb_code = sgb_gxb_code
		left join stand_model_ypgxb on smt_gxb_code = gxb_code and gxb_vin1_8 = smt_vin1_8
		left join stand_gxb_v8info on sgv_vin1_8 = smt_vin1_8  and smt_gxb_code = sgv_gxb_code and ((left(smt_vin1_8, 1) NOT in ('L', 'H') and sgv_org_brand=smt_brand) or left(smt_vin1_8, 1) in ('L', 'H'))";
        $vinArr = [];
        $Count = $YpwBase->YpwDb->One(sprintf('select count(*) as count from (select count(*) from %s where 1=1 %s group by smt_id) as tt ',$table, $where));
        if((int) $Count <= 0){
        	$Count = 0;
        }else{
        	$Count = (int) $Count;
        }
        $Page = LibPage::show($Count, $perPage);
        if($Count > 0)
        {
            $Res = $YpwBase->get($table, ['*', 'max(smt_xuhang) smt_xuhang'], sprintf("%s group by smt_id order by %s LIMIT %d,%d", $where, $orderBy,($nowPage-1)*$perPage,$perPage));
            $vinArr = $Res['data'];
        }

        LibTpl::Set('Page', $Page);


		$gxbArr = [];
		foreach($vinArr as $k=>$v)
		{
			if(!empty($v['smt_gxb_code'])) $gxbArr[] = $v['smt_gxb_code'];
		}
		$gxbArr = array_unique($gxbArr);

		if(!empty($gxbArr))
		{
			$res = $YpwBase->get('stand_gxb_dipan', ['sgd_gxb_code,sgd_dpgxb_code,sgd_dpgxb_code_show'], sprintf(" and sgd_gxb_code in ('%s')", implode("','", $gxbArr)));
			$gxbDpArr = array_column($res['data'], null, 'sgd_gxb_code');
			LibTpl::Set('gxbDpArr', $gxbDpArr);
			
			$dpGxbArr = array_unique(array_column($res['data'], 'sgd_dpgxb_code'));
			LibTpl::Set('dpGxbArr', $dpGxbArr);
			
			//底盘型号
			$hasDpModArr = [];
			if(!empty($dpGxbArr))
			{
				$res = $YpwBase->get('stand_model_ypgxb', ['distinct gxb_code'], sprintf(" and gxb_code in ('%s')", implode("','", $dpGxbArr)));
				$hasDpModArr = array_column($res['data'], 'gxb_code');
			}
			LibTpl::Set('hasDpModArr', $hasDpModArr);
		}
        LibTpl::Set('vinArr', $vinArr);
        LibTpl::Set('Params', $Params);
        LibTpl::Set('title','VIN报表');
        LibTpl::Put();
    }


	//重刷指定规则的报表统计
	public function standModelAnyTjReget()
    {
        LibRule::Check('CA02');
		if(!empty($_POST['codes']))
		{
			$YpwBase = new YpwBase();
			$gxbCodeArr = [];
			foreach($_POST['codes'] as $unicode)
			{
				$gxbCodeArr[] = $gxb;
				$tt = explode('@', $unicode);
				$vin18 = LibFc::FormatNum($tt[0]);
				$groupby = in_array(substr($vin18, 0 , 1), ['L', 'H'])? ' GROUP BY sma_gxb_code, sma_vin1_8': ' GROUP BY sma_gxb_code, sma_vin1_8, sma_brand';
				if(empty($tt[0])) LibFc::ReturnJson(false, $unicode.'参数异常');
				if(count($tt) > 1)
				{
					$gxb = LibFc::FormatNum($tt[1]);
					if(empty($gxb)) LibFc::ReturnJson(false, $unicode.'参数异常');
					$sqlArr = [
						//型号+v1_8
						sprintf("delete from stand_model_tj where smt_vin1_8='%s' and smt_gxb_code='%s'", $vin18, $gxb),
						//型号+v1_8
						sprintf("INSERT INTO stand_model_tj (smt_vin1_8, smt_gxb_code, smt_gxb_code_show, smt_vin10, smt_vin, smt_byear, smt_eyear, smt_vin_count, smt_brand, smt_engine, smt_cc, smt_kw, smt_passenger, smt_vtype, smt_tran, smt_gtype, smt_xuhang) 
						SELECT sma_vin1_8,  sma_gxb_code, sma_gxb_code_show, GROUP_CONCAT(DISTINCT sma_vin10), sma_vin, MIN(sma_vyear), MAX(sma_vyear), COUNT(*), sma_brand,
						GROUP_CONCAT(DISTINCT( CASE WHEN sma_engine != '' THEN sma_engine END)),
						GROUP_CONCAT(DISTINCT( CASE WHEN sma_cc != '' THEN sma_cc END)),
						GROUP_CONCAT(DISTINCT( CASE WHEN sma_kw != '' THEN sma_kw END)),
						GROUP_CONCAT(DISTINCT( CASE WHEN sma_passenger > 0 THEN sma_passenger END)),
						MAX(sma_vtype),
						GROUP_CONCAT(DISTINCT(CASE WHEN sma_tran != '' THEN sma_tran END)),
						MAX(sma_gtype),
						MAX(sma_xuhang)
						FROM stand_model_any
						WHERE sma_vin1_8 = '%s' and sma_gxb_code = '%s' %s", $vin18, $gxb, $groupby),
					];
				}
				else
				{
					$sqlArr = [
						//v1_8
						sprintf("delete from stand_model_tj where smt_vin1_8='%s'", $vin18),
						//v1_8
						sprintf("INSERT INTO stand_model_tj (smt_vin1_8, smt_gxb_code, smt_gxb_code_show, smt_vin10, smt_vin, smt_byear, smt_eyear, smt_vin_count, smt_brand, smt_engine, smt_cc, smt_kw, smt_passenger, smt_vtype, smt_tran, smt_gtype, smt_xuhang) 
						SELECT sma_vin1_8,  sma_gxb_code, sma_gxb_code_show, GROUP_CONCAT(DISTINCT sma_vin10), sma_vin, MIN(sma_vyear), MAX(sma_vyear), COUNT(*), sma_brand,
						GROUP_CONCAT(DISTINCT( CASE WHEN sma_engine != '' THEN sma_engine END)),
						GROUP_CONCAT(DISTINCT( CASE WHEN sma_cc != '' THEN sma_cc END)),
						GROUP_CONCAT(DISTINCT( CASE WHEN sma_kw != '' THEN sma_kw END)),
						GROUP_CONCAT(DISTINCT( CASE WHEN sma_passenger > 0 THEN sma_passenger END)),
						MAX(sma_vtype),
						GROUP_CONCAT(DISTINCT(CASE WHEN sma_tran != '' THEN sma_tran END)),
						MAX(sma_gtype),
						MAX(sma_xuhang)
						FROM stand_model_any
						WHERE sma_vin1_8 = '%s' %s", $vin18, $groupby),
					];

				}
				$YpwBase->exeAnySql($sqlArr);
			}
			/*$gxbCodeArr = array_unique($gxbCodeArr);
			foreach($gxbCodeArr as $tg)
			{
				$sqlArr = [
					sprintf("delete from stand_gxb_engine where sge_gxb_code='%s'", $tg),
					sprintf("INSERT INTO stand_gxb_engine SELECT sma_gxb_code, sma_engine, COUNT(*), sma_vin FROM stand_model_any WHERE sma_gxb_code ='%s' and sma_engine != '' GROUP BY sma_gxb_code, sma_engine", $tg)
				];
				$YpwBase->exeAnySql($sqlArr);
			}*/
		}
		LibFc::ReturnJson(true);
	}

    public function details()
    {
		LibRule::Check('CA02');
        $params = mvc::$URL_PARAMS;
        $list = (new YpwBase)->get('stand_model_any',['sma_vin1_8','sma_gxb_code', 'sma_vin10','sma_vyear','COUNT(*) as count'],sprintf(" AND sma_vin1_8 = '%s' AND sma_gxb_code = '%s' GROUP BY sma_vyear",$params['vin8'],$params['gxb_code']));
        LibTpl::Set('list',$list['data']);
        LibTpl::Set('title','vin年份统计');
        LibTpl::Put();
    }


	/**
	 * @method   外调明细
	 * @author soul
	 * @copyright 2020/9/3
	 */
	function wdList()
	{
		LibRule::Check('CA02');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$where = '';
		$YpwBase = new YpwBase();
		
		$ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
		$table = 'stand_gxb_soupei JOIN stand_model_any ON sma_vin = sgs_vin';
		foreach($Params as $K=>$V)
		{
			$V = trim($V);
			if($V == '') continue;
			switch($K)
			{
				case 'sgs_vin':
					$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($V))));
					if(count($anyNum) > 1)
					{
						foreach($anyNum as $kk=>$vv)
						{
							$anyNum[$kk] = LibFc::FormatVin($vv);
						}
						$where .= sprintf(" and sgs_vin IN ('%s')", implode("','", $anyNum));
					}
					else
					{
						$V = LibFc::FormatNum(strtr($V, $ReLike), '%_');
						$where .= sprintf(" AND sgs_vin like '%s'", $V);
					}
				break;
				case 'sgs_gxb_soupei':
					$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($V))));
					if(count($anyNum) > 1)
					{
						foreach($anyNum as $kk=>$vv)
						{
							$anyNum[$kk] = LibFc::FormatNum($vv);
						}
						$where .= sprintf(" and sgs_gxb_soupei_format IN ('%s')", implode("','", $anyNum));
					}
					else
					{
						$where .= sprintf(" AND sgs_gxb_soupei_format like '%s'", LibFc::FormatNum(strtr($V, $ReLike), '%_'));
					}
				break;
				case 'wj': 
					if($V == 'Y'){
						$where .= " and sgs_gxb_soupei_format != '' AND sgs_gxb_soupei_format = sgs_gxb_yp_format";
					}else if($V == 'N'){
						$where .= " and sgs_gxb_soupei_format != '' AND sgs_gxb_yp_format != '' AND sgs_gxb_soupei_format != sgs_gxb_yp_format";
					}
				break;
				case 'wr': 
					if($V == 'Y'){
						$where .= " and sgs_gxb_soupei_format != '' AND sgs_gxb_soupei_format = sma_gxb_code";
					}else if($V == 'N'){
						$where .= " and sgs_gxb_soupei_format != '' AND sma_gxb_code != '' AND sgs_gxb_soupei_format != sma_gxb_code";
					}
				break;
				case 'jr': 
					if($V == 'Y'){
						$where .= " and sgs_gxb_yp_format != '' AND sgs_gxb_yp_format = sma_gxb_code";
					}else if($V == 'N'){
						$where .= " and sgs_gxb_yp_format != '' AND sma_gxb_code != '' AND sgs_gxb_yp_format != sma_gxb_code";
					}
				break;
				case 'wjr': 
					if($V == 'Y'){
						$where .= " and sgs_gxb_soupei_format != '' and sgs_gxb_yp_format != '' AND sgs_gxb_soupei_format = sgs_gxb_yp_format AND sgs_gxb_yp_format = sma_gxb_code";
					}else if($V == 'N'){
						$where .= " and sgs_gxb_soupei_format != '' and sgs_gxb_yp_format != '' and sma_gxb_code != '' AND (sgs_gxb_soupei_format != sma_gxb_code OR sgs_gxb_yp_format != sma_gxb_code OR sgs_gxb_soupei_format != sgs_gxb_yp_format)";
					}
				break;
			}
		}
		$vinArr = [];
		$Res = $YpwBase->get($table, array('count(1) as count'), $where, true);
		$Count = $Res['data']['count'];
		$Page = LibPage::show($Count, $perPage);
		if($Count > 0)
		{
			$Res = $YpwBase->get($table, ['*'], sprintf("%s order by left(sgs_vin, 8), right(sgs_vin, 8) LIMIT %d,%d", $where, ($nowPage-1)*$perPage,$perPage));
			$vinArr = $Res['data'];
		}
		LibTpl::Set('Page', $Page);
		LibTpl::Set('vinArr', $vinArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','外调明细');
		LibTpl::Put();
	}

	/**
	 * @method   外调统计
	 * @author soul
	 * @copyright 2020/9/3
	 */
	function wdTj()
	{
		LibRule::Check('CA02');
		$Params = mvc::$URL_PARAMS;
		$vinArr = [];
		if(isset($Params['sgs_vin']))
		{
			$where = '';
			$YpwBase = new YpwBase();
			$allGroupArr = [
				'wmi'=>['left(sgs_vin, 3) as vin_wmi', 'left(sgs_vin, 3)'],	
				'year'=>['vin_year', 'vin_year'],	
			];
			$groupArr = [];
			$filed = [];

			if((!isset($Params['wmi']) && empty($Params['year'])) || !empty($Params['sgs_vin'])) $Params['wmi'] = 1;
			
			$ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
			$table = 'stand_gxb_soupei JOIN stand_model_any ON sma_vin = sgs_vin JOIN yp_vin_year ON right(left(sgs_vin, 10), 1) = vin_10';
			foreach($Params as $K=>$V)
			{
				$V = trim($V);
				if($V == '') continue;
				switch($K)
				{
					case 'sgs_vin':
						$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($V))));
						if(count($anyNum) > 1)
						{
							foreach($anyNum as $kk=>$vv)
							{
								$anyNum[$kk] = LibFc::FormatVin($vv);
							}
							$where .= sprintf(" and sgs_vin IN ('%s')", implode("','", $anyNum));
						}
						else
						{
							$V = LibFc::FormatNum(strtr($V, $ReLike), '%_');
							$where .= sprintf(" AND sgs_vin like '%s'", $V);
						}
					break;
					case 'sgs_gxb_soupei':
						$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($V))));
						if(count($anyNum) > 1)
						{
							foreach($anyNum as $kk=>$vv)
							{
								$anyNum[$kk] = LibFc::FormatNum($vv);
							}
							$where .= sprintf(" and sgs_gxb_soupei_format IN ('%s')", implode("','", $anyNum));
						}
						else
						{
							$where .= sprintf(" AND sgs_gxb_soupei_format like '%s'", LibFc::FormatNum(strtr($V, $ReLike), '%_'));
						}
					break;
					case 'wmi':
					case 'year':
						$groupArr[] = $allGroupArr[$K][1];
						$filed[] = $allGroupArr[$K][0];
					break;
					case 'addTime': $where .= sprintf(" and sgs_atime >= %d", strtotime($V)); break;
					case 'endTime': $where .= sprintf(" and sgs_atime <= %d", strtotime($V.' 23:59:59')); break;
				}
			}
			$filed = array_merge($filed, [
				'vin_10',
				"COUNT(*) AS total",
				"COUNT(CASE WHEN sgs_gxb_soupei_format != '' and sgs_gxb_soupei_format = sgs_gxb_yp_format THEN 1 END) AS 'wj_ok'",
				"COUNT(CASE WHEN sgs_gxb_soupei_format != '' and sgs_gxb_yp_format != '' THEN 1 END) AS 'wj_total'",

				"COUNT(CASE WHEN sgs_gxb_soupei_format != '' and sgs_gxb_soupei_format = sma_gxb_code THEN 1 END) AS 'wr_ok'",
				"COUNT(CASE WHEN sgs_gxb_soupei_format != '' and sma_gxb_code != '' THEN 1 END) AS 'wr_total'",

				"COUNT(CASE WHEN sgs_gxb_yp_format != '' and sgs_gxb_yp_format = sma_gxb_code THEN 1 END) AS 'jr_ok'",
				"COUNT(CASE WHEN sgs_gxb_yp_format != '' and sma_gxb_code != '' THEN 1 END) AS 'jr_total'",

				"COUNT(CASE WHEN sgs_gxb_soupei_format != '' and sgs_gxb_yp_format != '' and sgs_gxb_yp_format = sma_gxb_code THEN 1 END) AS 'wjr_ok'",
				"COUNT(CASE WHEN sgs_gxb_soupei_format != '' and sgs_gxb_yp_format != '' and sma_gxb_code != '' THEN 1 END) AS 'wjr_total'",
			]);
			$Res = $YpwBase->get($table, $filed, sprintf("%s group by %s order by left(sgs_vin, 3), vin_year desc", $where, implode(',', $groupArr)));
			$vinArr = $Res['data'];
			foreach($vinArr as $k=>$v)
			{
				if(!empty($Params['wmi']) && !empty($Params['year']))
				{
					$v['uri_vin'] = $v['vin_wmi'].'______'.$v['vin_10'].'%';
				}
				else if(!empty($Params['wmi']))
				{
					$v['uri_vin'] = $v['vin_wmi'].'%';
				}
				else if(!empty($Params['year']))
				{
					$v['uri_vin'] = '_________'.$v['vin_10'].'%';
				}
				$vinArr[$k] = $v;
			}
		}
		LibTpl::Set('vinArr', $vinArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','外调统计');
		LibTpl::Put();
	}


	/**
	 * @method  外调搜配
	 * @author soul
	 * @copyright 2019/1/22
	 */
	function wdspApiVinList()
	{
		LibRule::Check('CA01');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$where = " and sma_from = 'wdsp'";
		$YpwBase = new YpwBase();
		
		$ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
		$table = 'stand_model_any join stand_gxb_soupei on sgs_vin = sma_vin';
		foreach($Params as $K=>$V)
		{
			$V = trim($V);
			if($V == '') continue;
			switch($K)
			{
				case 'sma_vin':
					$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($V))));
					if(count($anyNum) > 1)
					{
						foreach($anyNum as $kk=>$vv)
						{
							$anyNum[$kk] = LibFc::FormatVin($vv);
						}
						$where .= sprintf(" and sma_vin IN ('%s')", implode("','", $anyNum));
					}
					else
					{
						$V = LibFc::FormatNum(strtr($V, $ReLike), '%_');
						if(strlen($V) <= 8)
							$where .= sprintf(" AND sma_vin1_8 like '%s'", $V);
						else
							$where .= sprintf(" AND sma_vin like '%s'", $V);
					}
				break;
				case 'sma_gxb_code':
					$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($V))));
					if(count($anyNum) > 1)
					{
						foreach($anyNum as $kk=>$vv)
						{
							$anyNum[$kk] = LibFc::FormatNum($vv);
						}
						$where .= sprintf(" and viz_gxb_code IN ('%s')", implode("','", $anyNum));
					}
					else
					{
						$where .= sprintf(" AND viz_gxb_code like '%s'", LibFc::FormatNum(strtr($V, $ReLike), '%_'));
					}
				break;
				case 'sma_length':
				case 'sma_width':
				case 'sma_height':
				case 'sma_wheel':
					$where .= sprintf(" AND %s = '%d'", $K, $V);
				break;
				case 'sma_engine':
				case 'sma_brand':
				case 'sma_kw':
					$where .= sprintf(" AND %s like '%s'", $K, strtr($V, $ReLike));
				break;
			}
		}
		$vinArr = [];
		$Res = $YpwBase->get($table, array('count(1) as count'), $where, true);
		$Count = $Res['data']['count'];
		$Page = LibPage::show($Count, $perPage);
		if($Count > 0)
		{
			$Res = $YpwBase->get($table, ['*'], sprintf("%s order by sma_id desc LIMIT %d,%d", $where, ($nowPage-1)*$perPage,$perPage));
			$vinArr = $Res['data'];
		}
		LibTpl::Set('Page', $Page);
		LibTpl::Set('vinArr', $vinArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','外调SP-VIN');
		LibTpl::Put();
	}

	

	//采集外调车架号
	function catchWdspApiVin()
	{
		LibRule::Check('CA01');
		$vinArr = [];
		foreach($_POST['vins'] as $vin)
		{
			$vin = LibFc::FormatVin($vin);
			if(strlen($vin) == 17) $vinArr[$vin] = [];
		}
		if(!empty($vinArr))
		{
			//剔除600w有的
			$YpwBase = new YpwBase();
			$hasArr = [];
			if(!empty($_POST['ignore']))
			{
				$res = $YpwBase->get('stand_model_any', ['sma_id', 'sma_vin'], sprintf(" and sma_vin in ('%s')", implode("','", array_keys($vinArr))));
				$hasArr = array_column($res['data'], null, 'sma_vin');
				$vinArr = array_merge($vinArr, $hasArr);
			}
			$needVin = array_diff(array_keys($vinArr), array_keys($hasArr));
			if(!empty($needVin))
			{
				if(!empty($_POST['cattype']) && $_POST['cattype'] == 'task')
				{
					$res = $YpwBase->get('stand_catch_list', ['sce_vin'], sprintf(" and sce_vin in ('%s') and sce_reg_code = 'wdsp'", implode("','", $needVin)));
					$hasTaskArr = array_column($res['data'], 'sce_vin');
					$needTaskVin = array_unique(array_diff($needVin, $hasTaskArr));
					if(!empty($needTaskVin))
					{
						$addTaskArr = [];
						foreach($needTaskVin as $tvin)
						{
							$addTaskArr[] = [
								'sce_vin'=>$tvin,	
								'sce_level'=>'9999',	
								'sce_reg_code'=>'wdsp'
							];
						}
						$YpwBase->addAny('stand_catch_list', array_keys($addTaskArr[0]), $addTaskArr);
						$YpwBase->set('stand_scqd_reg', ['reg_waitcount'=>'#@reg_waitcount+'.count($addTaskArr)], " and reg_code = 'wdsp'");
					}
					$YpwBase->set('stand_catch_list', ['sce_level'=>'9999'], sprintf(" and sce_vin in ('%s') and sce_reg_code = 'wdsp'", implode("','", $needVin)));
					LibFc::ReturnJson(true, ['task'=>'ok']);
				}
				else
				{
					$LibYpApi = new LibYpApi();
					$res = $LibYpApi->Get('vin/catchAnyVinfromWdspApi', [], ['vins'=>implode(',', $needVin), 'addToSma'=>1]);
					$vinArr = array_merge($vinArr, $res['data']);
				}
			}
		}
		LibFc::ReturnJson(true, $vinArr);
	}
	

	//批量添加VIN与型号
	function addAnySma()
	{
		LibRule::Check('CA10');
		$vinArr = [];
		foreach($_POST['vins'] as $str)
		{
			if(strlen($str) >= 17)
			{
				$vin = LibFc::FormatVin(substr($str, 0, 17));
				if(strlen($vin) != 17) LibFc::ReturnJson(false, $str.'无法提取车架号！');
				$gxb = substr($str, 17);
				$vinArr[$vin] = ['gxb'=>strtoupper(trim($gxb))];
			}
		}
		if(!empty($vinArr))
		{
			$YpwBase = new YpwBase();
			
			$res = $YpwBase->get('stand_model_any', ['sma_vin'], sprintf(" and sma_vin in ('%s')", implode("','", array_keys($vinArr))));
			$hasArr = array_column($res['data'], 'sma_vin');
			foreach($vinArr as $vin=>$vg)
			{
				if(in_array($vin, $hasArr))
				{
					$vinArr[$vin]['res'] = 'has';
					continue;
				}
				
				$addArr = [
					'sma_vin'=>$vin,
					'sma_gxb_code_show'=>$vg['gxb'],
					'sma_from'=>'rgany',
					'sma_etime'=>time()
				];
				$addArr['sma_gxb_code'] = LibFc::FormatNum($addArr['sma_gxb_code_show']);
				$addArr['sma_gtype'] = LibFc::getGxbCarType($addArr['sma_gxb_code']);
				$addArr['sma_vin1_3'] = substr($addArr['sma_vin'], 0, 3);
				$addArr['sma_vin1_8'] = substr($addArr['sma_vin'], 0, 8);
				$addArr['sma_vin10'] = substr($addArr['sma_vin'], 9, 1);
				$addArr['sma_vin10_12'] = substr($addArr['sma_vin'], 9, 3);
				$addArr['sma_vin13_17'] = substr($addArr['sma_vin'], 12, 5);
				$addArr['sma_vin10_11'] = substr($addArr['sma_vin'], 9, 2);
				$addArr['sma_vin12_17'] = substr($addArr['sma_vin'], 11, 6);
				$addArr['sma_vyear'] = LibFc::VinYear($addArr['sma_vin10']);
				$YpwBase->add('stand_model_any', $addArr);
				$vinArr[$vin]['res'] = 'add';
			}
			LibFc::ReturnJson(true, $vinArr);
		}
		LibFc::ReturnJson(false, '获取VIN数据失败');
	}


	public function getVinImgOcr()
	{
		$LibHttp = new LibHttp();
		$url = $_POST['url'];
		if(mvc::$cfg['HOST']['vinimg_2real']) $url = str_replace(mvc::$cfg['HOST']['vinimg_2'], mvc::$cfg['HOST']['vinimg_2real'], $url);
		$image = $LibHttp->fetch($url);
		$image = base64_encode($image);
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('ocr/paddle', [], ['image'=>$image, 'rotate'=>$_POST['rotate']]);
		$ocrtxt = LibFc::reBrandName(implode("\r\n", $res['data']));
		if($_POST['vii_id']){
			$YpwBase = new YpwBase();
			$res = $YpwBase->get('stand_vin_imgs', ['vii_status, vii_ocrstatus,vii_imgocr'], sprintf(" and vii_id=%d", $_POST['vii_id']), true);
			if($res['data'] && strlen($ocrtxt) > strlen($res['data']['vii_imgocr'])){
				$set = ['vii_imgocr'=>$ocrtxt]; 
				if($res['data']['vii_imgocr'] != 1) $set['vii_smastatus'] = 'sma';
				if($res['data']['vii_ocrstatus'] < 1) $set['vii_ocrstatus'] = 2;
				$YpwBase->set('stand_vin_imgs', $set, sprintf(" and vii_id=%d", $_POST['vii_id']));
			}
		}
		LibFc::ReturnJson(true, $ocrtxt);
	}
	
	//重新识别图片的VIN
	public function getImgVin()
	{
		$LibHttp = new LibHttp();
		$url = $_POST['url'];
		if(mvc::$cfg['HOST']['vinimg_2real']) $url = str_replace(mvc::$cfg['HOST']['vinimg_2'], mvc::$cfg['HOST']['vinimg_2real'], $url);
		$image = $LibHttp->fetch($url);
		$imageData = base64_encode($image);
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('ocr/vin', [], ['image'=>$imageData, 'issmall'=>1]);
		LibFc::ajaxJsonEncode($res);
	}


	//卡车尺寸统计 统计
	public function kcSizeTj()
    {
        LibRule::Check('CA13');
        $Params = mvc::$URL_PARAMS;
        $nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		if(!isset($Params['skt_statue'])) $Params['skt_statue'] = 1;
        $where = '';
        $YpwBase = new YpwBase();
        $ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
        $orderBy = 'skt_vin_count desc';
        foreach($Params as $K=>$V)
        {
            $V = trim($V);
            if($V == '') continue;
            switch($K)
            {
                case 'skt_gxb_code':
                    $anyNum = array_unique(explode("\r\n", strtr(trim($V), [';'=>"\r\n", ','=>"\r\n"])));
                    if(count($anyNum) > 1)
                    {
                        foreach($anyNum as $kk=>$vv)
                        {
                            $anyNum[$kk] = LibFc::FormatNum($vv);
                        }
                        $where .= sprintf(" and skt_gxb_code IN ('%s')", implode("','", $anyNum));
                    }
                    else
                    {
                        $where .= sprintf(" AND skt_gxb_code like '%s'", LibFc::FormatNum(strtr($V, $ReLike), '%_'));
                    }
                    break;
				case 'skt_wheel':
				case 'skt_b_name':
				case 'skt_m_name':
				case 'skt_m1_name':
				case 'skt_vtype':
				case 'skt_tran':
				case 'skt_drive':
				case 'skt_zwps':
				case 'skt_kw':
				case 'skt_cc':
				case 'skt_cc_name':
				case 'skt_fuel':
					if($V == '=')
						$where .= " and {$K}=''";
					else if($V == '!')
						$where .= " and {$K} !=''";
					else
						$where .= sprintf(" AND %s like '%s'", $K, strtr($V, $ReLike));
				break;
				case 'skt_engine':
					if($V == '=')
						$where .= " and {$K}=''";
					else if($V == '!')
						$where .= " and {$K} !=''";
					else
						$where .= sprintf(" AND skt_engine like '%s'", LibFc::FormatEng(strtr($V, $ReLike), '%_'));
				break;
                case 'sgb_rname':
                    $where .= sprintf(" and sgb_rname like '%%%s%%'", $V);
                    break;
				case 'skt_statue':
                    $where .= sprintf(" and skt_statue = %d", $V);
                break;
				case 'skt_length':
				case 'skt_width':
				case 'skt_height':
					if($V == '='){
						$where .= " and {$K}=0";
					}else if($V == '!'){
						$where .= " and {$K} > 0";
					}else if(preg_match('/\d+/', $V, $Match)){
						if(LibFc::Int($V) !== false) $V = '='.$V;
						$where .= ' AND '.$K.' '.$V;
					}
				break;
				case "sort":
                    if ($V == 3){
                        $orderBy = 'skt_vin_count asc';
                    }else{
                        $orderBy = 'skt_vin_count desc';
                    }
                break;
				case 'skt_vin10s':
					$tw = [];
					foreach(str_split($V) as $tv)
					{
						if(trim($tv) != '')
						{
							$tw[] = sprintf(" skt_vin10s like '%%%s%%'", $tv);
						}
					}
					if(!empty($tw))
						$where .= sprintf(" and (%s)", implode(" or ", $tw));
				break;
				case 'has':
					if($V == 'Y'){
						$where .= " and skt_m1_name != ''";
					}else if($V == 'Y1'){
						$where .= " and skt_m1_name != '' and skt_m1_name not like '%,%'";
					}else if($V == 'Y2'){
						$where .= " and skt_m1_name like '%,%'";
					}else if($V == 'N'){
						$where .= " and skt_m1_name = ''";
					}
				break;
				case 'ypcar':
					if($V == 'Y'){
						$where .= " and gxb_code is not null";
					}else if($V == 'N'){
						$where .= " and gxb_code is null";
					}
				break;
            }
        }
        $table = "stand_kczj_tj 
		left join stand_gxb_base on skt_gxb_code = sgb_gxb_code
		left join (select distinct gxb_code from stand_model_ypgxb) t on gxb_code = skt_gxb_code";
        $vinArr = [];
        $Count = $YpwBase->YpwDb->One(sprintf('select count(*) as count from (select count(*) from %s where 1=1 %s group by skt_id) as tt ',$table, $where));
        if((int) $Count <= 0){
        	$Count = 0;
        }else{
        	$Count = (int) $Count;
        }
        $Page = LibPage::show($Count, $perPage);
        if($Count > 0)
        {
            $Res = $YpwBase->get($table, ['*'], sprintf("%s group by skt_id order by %s LIMIT %d,%d", $where, $orderBy,($nowPage-1)*$perPage,$perPage));
            $vinArr = $Res['data'];
        }

        LibTpl::Set('Page', $Page);
        LibTpl::Set('vinArr', $vinArr);
        LibTpl::Set('Params', $Params);
        LibTpl::Set('title','卡车尺寸报表');
        LibTpl::Put();
    }


	//卡车车型
	public function kcModel()
    {
        LibRule::Check('CA13');
        $Params = mvc::$URL_PARAMS;
        $nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
        $where = '';
        $KczjBase = new BaseDb(mvc::$cfg['DB']['KCZJ']);
        $ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
        $orderBy = 'm3_b_name,m3_m_name,m3_m1_name,m3_name';
        foreach($Params as $K=>$V)
        {
            $V = trim($V);
            if($V == '') continue;
            switch($K)
            {
                case 'gxb_code':
                    $anyNum = array_unique(explode("\r\n", strtr(trim($V), [';'=>"\r\n", ','=>"\r\n"])));
                    if(count($anyNum) > 1)
                    {
                        foreach($anyNum as $kk=>$vv)
                        {
                            $anyNum[$kk] = LibFc::FormatNum($vv);
                        }
                        $where .= sprintf(" and mmg_gxb_code IN ('%s')", implode("','", $anyNum));
                    }
                    else
                    {
                        $where .= sprintf(" and mmg_gxb_code like '%s'", LibFc::FormatNum(strtr($V, $ReLike), '%_'));
                    }
                    break;
				case 'm3_wheel':
				case 'm3_b_name':
				case 'm3_m_name':
				case 'm3_m1_name':
				case 'm3_vtype':
				case 'm3_tran':
				case 'm3_drive':
				case 'm3_zwps':
				case 'm3_kw':
				case 'm3_cc':
				case 'm3_cc_name':
				case 'm3_fuel':
				case 'm3_engine':
				case 'm3_name':
					if($V == '=')
						$where .= " and {$K}=''";
					else if($V == '!')
						$where .= " and {$K} !=''";
					else
						$where .= sprintf(" AND %s like '%s'", $K, strtr($V, $ReLike));
				break;
				case 'mms_length':
				case 'mms_width':
				case 'mms_height':
					if($V == '='){
						$where .= " and {$K}=0";
					}else if($V == '!'){
						$where .= " and {$K} > 0";
					}else if(preg_match('/\d+/', $V, $Match)){
						if(LibFc::Int($V) !== false) $V = '='.$V;
						$where .= ' and '.$K.' '.$V;
					}
				break;
            }
        }
        $table = "mer_model3 m3
		left join mer_model3_gxb on mmg_m3_code = m3_code
		left join mer_model3_size on mms_m3_code = m3_code";
        $modArr = [];
        $res = $KczjBase->get($table, ['count(distinct m3_code) count'], $where, true);
		$Count =  $res['data']['count'];
        $Page = LibPage::show($Count, $perPage);
        if($Count > 0)
        {
            $Res = $KczjBase->get($table, ['m3.*', 'group_concat(distinct mmg_gxb_show) gxbs', 'group_concat(distinct concat(mms_length, "X", mms_width, "X", mms_height)) sizes'], sprintf("%s group by m3_code order by %s LIMIT %d,%d", $where, $orderBy,($nowPage-1)*$perPage,$perPage));
            $modArr = array_column($Res['data'], null, 'm3_code');
			if(!empty($modArr))
			{
				$Res = $KczjBase->get('mer_model3_gxb', ['mmg_m3_code', 'group_concat(distinct mmg_gxb_show) gxbs'], sprintf(" and mmg_m3_code in ('%s') group by mmg_m3_code", implode("','", array_keys($modArr))));
				foreach($Res['data'] as $v)
				{
					$modArr[$v['mmg_m3_code']]['gxbs'] = $v['gxbs'];
				}

				$Res = $KczjBase->get('mer_model3_size', ['mms_m3_code', 'group_concat(distinct concat(mms_length, "X", mms_width, "X", mms_height)) sizes'], sprintf(" and mms_m3_code in ('%s') group by mms_m3_code", implode("','", array_keys($modArr))));
				foreach($Res['data'] as $v)
				{
					$modArr[$v['mms_m3_code']]['sizes'] = $v['sizes'];
				}
			}
        }
        LibTpl::Set('Page', $Page);
        LibTpl::Set('modArr', $modArr);
        LibTpl::Set('Params', $Params);
        LibTpl::Set('title','卡车车型');
        LibTpl::Put();
    }

	/**
	 * @method  卡车尺寸统计详情
	 * @author soul
	 * @copyright 2023/5/6
	 */
	public function kcSizeTjInfo()
    {
        LibRule::Check('CA02');
		$Params = mvc::$URL_PARAMS;
		$YpwBase = new YpwBase();
		$res = $YpwBase->get('stand_kczj_tj', ['*'], sprintf(" and skt_id =%d", $Params['id']), true);
		LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method  管理卡车尺寸统计
	 * @author soul
	 * @copyright 2023/5/6
	 */
	function kcSizeTjSet()
	{
		LibRule::Check('CA02');
		$YpwUser = new YpwUser();
		$res = $YpwUser->kcSizeTjSet($_POST);
		LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method  管理卡车尺寸统计
	 * @author soul
	 * @copyright 2023/5/6
	 */
	function kcSizeTjStatus()
	{
		LibRule::Check('CA02');
		$status = $_POST['status'];
		$ids = [];
		foreach(explode(',', $_POST['ids']) as $id)
		{
			$ids[] = (int) $id;
		}
		$YpwBase = new YpwBase();
		if($status=='del'){
			$res = $YpwBase->del('stand_kczj_tj', sprintf(" and skt_id in (%s)", implode(',', $ids)));
		}else{
			$res = $YpwBase->set('stand_kczj_tj', ['skt_statue'=>(int) $status], sprintf(" and skt_id in (%s)", implode(',', $ids)));
		}
		LibFc::ajaxJsonEncode($res);
	}


	/**
	 * @method  管理卡车尺寸统计
	 * @author soul
	 * @copyright 2023/5/6
	 */
	function updateKcSizeTjVinCount()
	{
		LibRule::Check('CA02');
		$ids = [];
		foreach(explode(',', $_POST['ids']) as $id)
		{
			$ids[] = (int) $id;
		}
		$YpwBase = new YpwBase();
		$res = $YpwBase->get('stand_kczj_tj', ['distinct skt_gxb_code'], sprintf(" and skt_id in (%s)", implode(',', $ids)));
		if(!empty($res['data']))
		{
			$LibYpApi = new LibYpApi();
			$LibYpApi->Get('ypc/updateKczjSizeTj', [], ['gxbs'=>implode(',', array_column($res['data'], 'skt_gxb_code'))]);
		}
		LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method  将型号纳入到卡车尺寸统计表
	 * @author soul
	 * @copyright 2023/5/27
	 */
	function addGxbsToKczjSizeTj()
	{
		LibRule::Check('CA02');
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('ypc/addGxbsToKczjSizeTj', [], ['gxbs'=>$_POST['gxbs']]);
		LibFc::ajaxJsonEncode($res);
	}


	public function buildKczjModel()
	{
		$Params = mvc::$URL_PARAMS;
		$LibHttp = new LibHttp();
		$html = $LibHttp->fetch('http://hub.paojd.cn:75/kczj/buildCar?brand='.$Params['brand']);
		echo $html;
	}

	public function matchEng6(){
		if(!empty($_POST['vin']) && !empty($_POST['ocrtxt'])){
			$LibYpApi = new LibYpApi();
			$res = $LibYpApi->Get('vin/matchEng6', [], $_POST);
			LibFc::ajaxJsonEncode($res);
		}
		LibFc::ReturnJson(true, []);
	}
}
