<?php
class PjlProduct extends PjlBase
{
	/**
	  * @method 配件搜索  条件：keyword关键字、mod3_id末级车型ID
	  * @param  $shopId 店铺ID
	  * @param  $Params URL参数
	  * @param  $perPage 每页显示多少条
	  * @author soul
	  * @copyright 2017/9/22
	  * @return 
			成功 ["status"=>true, "data"=> ] 
			失败 ["status"=>false, "data"=> 错误信息] 
	  */
	public function searchShopItem($shopId, $Params, $perPage = 20)
	{
		$shopId = (int) $shopId;
		$type = $Params['type'];
		$returnArr = [
			'total'=>0,
			'items'=>[],	
		];
		$whereArr = [];
		$table = 'pl_product';
		switch($type)
		{
			case 'number':
				$re = ["、",",","，",";","；","\n","\t","\r"];
				$keyword = str_replace($re, ',', $Params['number']);
				$numwhere = [];
				foreach(explode(',', $keyword) as $tword){
					$tword = LibFc::FormatNum($tword);
					if(strlen($tword) > 2){
						$numwhere[] = $Params['numtype'] == 2? $tword: sprintf("pro_format like '%%%s%%'", $tword);
					}
				}
				if(!empty($numwhere)){
					$whereArr['num'] = $Params['numtype'] == 2? sprintf(" and pro_format in ('%s')", implode("','", $numwhere)) : sprintf(" and (%s)", implode(" or ", $numwhere));
				}else{
					$whereArr['num'] = ' and 1=0';
				}
			break;
			case 'all':
			case 'item':
			case 'model':
				$Ypc2Model = new Ypc2Model();
				$comWhere = '';
				if(!empty($Params['mod3_id']))
				{
					$tids = [];
					foreach(explode(',', $Params['mod3_id']) as $tid)
					{
						$tids[] = (int) $tid;
					}
					$tids = array_unique($tids);
					$table .= ' join pl_product_model3_link on pro_id = pml3_pro_id';
					$whereArr['mod3'] .= sprintf(" and pml3_mod3_id in (%s)", implode(',', $tids));
				}
				//配件关键字
				if($Params['keyword'] != '')
				{	
					$whereArr['word'] = sprintf(" and pro_name like '%%%s%%'", LibFc::Escape($Params['keyword']));
					/*
					$blparams = ['word'=>$Params['keyword'], 'shop_id'=>$shopId, 'count'=>10000];
					if(!empty($whereArr)){//能否限制少量产品
						$res = $this->get($table, ['distinct pro_id'], implode(' ', $whereArr));
						$blparams['pro_id'] = array_column($res['data'], 'pro_id');
					}
					$B2cElastic = new B2cElastic();
					$res = $B2cElastic->searchProId($blparams);
					if(!empty($res['data'])){
						$Params['orderPids'] = $res['data'];
						$tempWhere = sprintf(" and pro_id in (%s)", implode(',', $res['data']));
					}else{
						$tempWhere = sprintf(" and pro_name like '%%%s%%'", LibFc::Escape($Params['keyword']));
					}
					$whereArr['word'] = $tempWhere;*/
				}
			break;
		}
		if(!empty($whereArr)){
			$Params['page'] = empty($Params['page'])? 1: (int)$Params['page'];
			$perPage = empty($perPage)? 20: (int) $perPage;
			$where = sprintf(" and pro_shop_id = %d ", $shopId).implode(' ', $whereArr);
			$res = $this->get($table, ['count(distinct(pro_id)) count'], $where, true);
			$returnArr['total'] = $res['data']['count'];
			if($returnArr['total'] > 0)
			{
				$orderBy = ' order by pro_name, pro_format';
				$where = sprintf(" %s group by pro_id %s limit %d, %d", $where, $orderBy, ($Params['page']-1)*$perPage, $perPage);
				$res = $this->get($table, ['pro_id','pro_display', 'pro_name','pro_price', 'pro_quality','pro_quality_des', 'pro_model'], $where);
				$returnArr['items'] = $res['data'];
			}
		}
		return LibFc::ReturnData(true, $returnArr); 
	}

	/**
	  * @method 跑街令产品车型自动匹配任务
	  * @param  $cfg array  [
				'shopid'=>369676,	// 店铺ID
				'proids'=>[], //指定产品	
			]
	  * @author soul
	  * @copyright 
	  * @return 
	  */
	public function autoPjlItemModel($cfg)
	{
		$version = date('Ymd');
		$lastversion = date('Ymd', strtotime("-7 day"));
		$shopId = (int) $cfg['shopid'];

		$where = sprintf(" and pro_shop_id = %d and LENGTH(pro_format) BETWEEN  5 and 20 and pro_automodel_num < %d", $shopId, $lastversion);
		if(isset($cfg['proids']) && is_array($cfg['proids']) && !empty($cfg['proids'])) $where .= sprintf(" and pro_id in (%s)", implode(',', $cfg['proids']));
		$pres = $this->get('pl_product', ['pro_id, pro_format'], $where);
		if(empty($pres['data'])) return LibFc::ReturnData(true);
		
		$YpcModel = new YpcModel();
		foreach(array_chunk($pres['data'], 100) as $rows)
		{
			$proArr = array_column($rows, null, 'pro_id');
			$pidArr = array_keys($proArr);
			
			//已有
			$res = $this->get('pl_product_model3_link', ['pml3_pro_id pro_id, pml3_mod3_id mod3_id'], sprintf(" and pml3_pro_id in (%s)", implode(',', $pidArr)));
			$allHasArr = [];
			foreach($res['data'] as $tv){
				$allHasArr[$tv['pro_id']][] = $tv['mod3_id'];
			}

			//忽略
			$res = $this->get('pl_product_model3_ignore', ['pmi_pro_id pro_id, pmi_mod3_id mod3_id'], sprintf(" and pmi_pro_id in (%s)", implode(',', $pidArr)));
			$allIgnoreArr = [];
			foreach($res['data'] as $tv){
				$allIgnoreArr[$tv['pro_id']][] = $tv['mod3_id'];
			}
			
			$this->PjlDb->Begin();
			foreach($proArr as $proId=>$tv){
				$hasArr = $allHasArr[$proId]? $allHasArr[$proId]: [];
				$ignoreArr = $allIgnoreArr[$proId]? $allIgnoreArr[$proId]: [];
				
				//新匹配
				$res = $YpcModel->getM3idByNum([['factory'=>'OE', 'display'=>$tv['pro_format']]]);
				$newIdArr = array_diff($res['data'], $ignoreArr);
			
				$addIdArr = array_diff($newIdArr, $hasArr);
				$delArr = array_diff($hasArr, $newIdArr);

				
				if(!empty($delArr)){
					$this->del('pl_product_model3_link', sprintf(" and pml3_pro_id=%d and pml3_mod3_id in (%s)", $proId, implode(',', $delArr)));
				}
				
				if(!empty($addIdArr)){
					$addArr = [];
					foreach($addIdArr as $id){
						$addArr[] = [
							'pml3_pro_id'=>$proId,
							'pml3_mod3_id'=>$id,
							'pml3_atime'=>time()
						];
					}
					$this->addAny('pl_product_model3_link', array_keys($addArr[0]), $addArr);
				}
			}
			$this->set('pl_product', ['pro_automodel_num'=>$version], sprintf(" and pro_id in (%s)", implode(',', $pidArr)));
			$this->PjlDb->End();
		}
		return LibFc::ReturnData(true);
	}
}