<?php
/*
 [
    'key'=>'rule1',                             //键名
    'caption'=>lg('编码规则',                      //字段名
    'must'=> true,                              //是否必须,默认false
    'mustCols'=> ['ruleA','ruleB']              //当此列存在时，必须有的其他列 ，默认空
    'minlen'=>0,                                //最小长度 默认0不判断
    'maxlen'=>50,                               //最大长度 默认0不判断
    'type'=>'number',                           //类型 number,string,date,datetime 默认 string
    //自定义检测
    'checkfunction'=>function($arr, $k, $v, $obj){
        $obj->lastError = '[line:'.$obj->lineNum.'] ['.$obj->rules[$k]['caption'].'] 自定义检测, 当前值为[ '.$v.' ]';
        return false;
    }
     //格式化单元格的值 [
        类, 
        类的创建参数, 默认[]
        方法, 
        参数,  ['@innum','@outnum',123,true] @表示使用导入数据中的列中的值 ,'@'表示自己 
        如果结果是数组指定返回哪个键 默认null
     ]
    'formatCell'=> [\model\collocation::class,'getRowByKey',['@'],null],   或者 config/import.php 中的配置
],
 */
 
namespace model\import;
use \model;
use \model\tags;
use \model\check;
use \model\history;

/**
 * 
 */
class sample  extends model
{
	 /**
     * 标题 (用于消息提醒)
     */
	public $title = '样品初始化'; //固定
	public $import = null;    //固定
	public $rules = null;    //规则
	public $demoData = null;  //样例数据
	public $demoremark = null;  //样例说明
	public $type = '';
	public $classId = '';
	
	public function __construct()
	{
		parent::__construct(); //执行父类
		$this->import = new \lib\import();
		$this->rules = [
		     ['key'=>'s_code',            'caption'=>lg('样品预编码')],
		     ['key'=>'s_plmseq',          'caption'=>lg('流水号')],
		     //['key'=>'s_outnum',          'caption'=>lg('外部编码')],
		     ['key'=>'s_innum',           'caption'=>lg('内部编码')],
			 ['key'=>'s_cate',            'caption'=>lg('品名'),'must'=>true,'formatCell'=>'cate'],
			 ['key'=>'s_apply_user',      'caption'=>lg('申请人'),'must'=>true,'formatCell'=>'auser'],
			 ['key'=>'s_apply_depa',      'caption'=>lg('申请部门'),'formatCell'=>'adepa'],
			 ['key'=>'s_apply_area',      'caption'=>lg('申请区域'),'formatCell'=>'aarea'],
			 ['key'=>'s_customer_name',   'caption'=>lg('客户名称'),'must'=>true,'formatCell'=>'customer'],
			 ['key'=>'s_customer_code',   'caption'=>lg('客户代码')],
			 ['key'=>'s_requqty',         'caption'=>lg('年需求量')],
			 ['key'=>'s_requqty_first',   'caption'=>lg('首单量')],
			 ['key'=>'s_expected_order_time',   'caption'=>lg('预计下单时间'), 'type'=>'date'],
			 ['key'=>'s_apply_remark',    'caption'=>lg('申请人备注')],
			 ['key'=>'s_remark',          'caption'=>lg('核对备注')],
			 ['key'=>'s_state_main',      'caption'=>lg('主状态'),'must'=>true],
			 ['key'=>'s_state_sub',       'caption'=>lg('子状态'),'formatCell'=>'s_state_sub'],
			 ['key'=>'s_modcost',         'caption'=>lg('模具费用')],
			 ['key'=>'s_apply_date',      'caption'=>lg('申请日期'),'must'=>false, 'type'=>'date'],
			 ['key'=>'s_apply_type',      'caption'=>lg('申请类型'),'must'=>true,'formatCell'=>'coll32'],
			 ['key'=>'s_apply_brand',     'caption'=>lg('申请品牌'),'formatCell'=>'pf_id'],
			 ['key'=>'s_apply_number',    'caption'=>lg('申请编码')],
			 ['key'=>'s_apply_cause',     'caption'=>lg('申请原因')],
			 ['key'=>'s_demand_data',     'caption'=>lg('需求时间'), 'type'=>'date'],
			 ['key'=>'s_model_src',       'caption'=>lg('车型来源'),'formatCell'=>'coll30'],
			 ['key'=>'s_sales_area',      'caption'=>lg('可销售区域'),'formatCell'=>'sarea'],
			 ['key'=>'s_model_vio_src',   'caption'=>lg('保有量来源'),'formatCell'=>'coll28'],
			 ['key'=>'s_model_vio',       'caption'=>lg('保有量'),'type'=>'number'],
			 ['key'=>'s_refgsp_no',       'caption'=>lg('配对型号')],
			 ['key'=>'s_downorder_time',  'caption'=>lg('下单日期'), 'type'=>'date'],
			 ['key'=>'s_arrival_time',    'caption'=>lg('到样日期'), 'type'=>'date'],
			 ['key'=>'s_supp_price',      'caption'=>lg('采购价')],
			 ['key'=>'s_supp_currency',   'caption'=>lg('币种'),'formatCell'=>'coll33'],
			 ['key'=>'s_supp_rate',       'caption'=>lg('汇率')],
			 ['key'=>'s_channel',         'caption'=>lg('采购渠道'),'formatCell'=>'coll34'],
			 ['key'=>'s_supp_supplier',   'caption'=>lg('供应商')],
			 ['key'=>'s_purc_state',      'caption'=>lg('采购状态'),'formatCell'=>'coll35'],
			 ['key'=>'s_stop_cause',      'caption'=>lg('停购原因')],
			 ['key'=>'s_purc_user',       'caption'=>lg('指定采购人'),'formatCell'=>'auser'],
			 ['key'=>'s_sign_time',       'caption'=>lg('登记日期'), 'type'=>'date'],
			 ['key'=>'s_sign_opuser',       'caption'=>lg('登记人')],
			 ['key'=>'s_check_type',      'caption'=>lg('核对类型'),'formatCell'=>'coll36'],
			 ['key'=>'s_arri_brand',      'caption'=>lg('到样品牌'),'must'=>true,'formatCell'=>'pf_id'],
			 ['key'=>'s_arri_number',     'caption'=>lg('到样号码'),'must'=>true],
			 ['key'=>'s_sign_type',       'caption'=>lg('来样方式'),'formatCell'=>'coll37'],
			 ['key'=>'s_sign_address',    'caption'=>lg('到样地点'),'formatCell'=>'coll38'],
			 ['key'=>'s_proof_catagroup', 'caption'=>lg('目录组校对意见')],
			 ['key'=>'s_custrequ',        'caption'=>lg('客户要求')],
			 ['key'=>'s_procode_ext',     'caption'=>lg('编码规则'),'formatCell'=>'pro_code_ext'],
			 ['key'=>'s_usa_make',        'caption'=>lg('编码品牌'),'formatCell'=>'mk_id'],
			 ['key'=>'sm_make',           'caption'=>lg('大车型'),'formatCell'=>'mk_id'],
			 ['key'=>'sm_series',         'caption'=>lg('小车型/车款/年份/备注')],
			 ['key'=>'sn_pro_factory',    'caption'=>lg('交叉号品牌'),'formatCell'=>'pf_id'],
			 ['key'=>'sn_number',         'caption'=>lg('交叉号码')],
			 ['key'=>'sn_src',            'caption'=>lg('交叉号来源'),'formatCell'=>'coll29'],
			 
			 ['key'=>'tech_SUSER01',        'caption'=>lg('核对结论')],
			 ['key'=>'tech_HTIME',          'caption'=>lg('核对时间'), 'type'=>'date'],
			 ['key'=>'tech_SUSER03',        'caption'=>lg('技术GSP型号')],
			 ['key'=>'tech_ASUSER08',       'caption'=>lg('ABS')],
			 ['key'=>'tech_WXTX',           'caption'=>lg('评审特性')],
			 ['key'=>'tech_SUSER06',        'caption'=>lg('开发完成时间'), 'type'=>'date'],
			 ['key'=>'tech_ASUSER12',       'caption'=>lg('类似报价')],
			 ['key'=>'tech_ASUSER09',       'caption'=>lg('客户确认栏')],
			 ['key'=>'tech_PROTYPE',        'caption'=>lg('样品描述')],
			 ['key'=>'tech_ASUSER13',       'caption'=>lg('初步校对意见')],
			 ['key'=>'tech_SMEMO',          'caption'=>lg('备注')],
			 ['key'=>'tech_JDR',            'caption'=>lg('核对人')],
			 ['key'=>'tech_WQLDM',          'caption'=>lg('外球笼是否单卖')],
			 ['key'=>'tech_NQLDM',          'caption'=>lg('内球笼是否单卖')],
			 ['key'=>'tech_WQLXLDM',        'caption'=>lg('外球笼维修包是否单卖')],
			 ['key'=>'tech_NQLXLDM',        'caption'=>lg('内球笼维修包是否单卖')],
			 ['key'=>'tech_DESCRIBE',       'caption'=>lg('描述')],
			 ['key'=>'tech_update_time',    'caption'=>lg('回复时间'), 'type'=>'date'],
			 
		];
		$this->demoData = [
			
		];

		$this->demoremark = '';
		$this->history = new history();
	}
	
	 /**处理导入
     * @param array|string $src 数组或者文件名
     * @param isInit 是否是初始化
     * @return 可返回任意值(string|array|bool)，都会到前端
     */
    public function import($src,$isInit=false) //固定
    {
		$sample = makeOne(\model\sample\sample::class);
		$state = $this->import->execute($src, $this->rules);
		
		//数据重复验证 - 自己
		if($state && !empty($this->import->data))
		{
		    $repeatRules = [
			    ['s_code'],
			    ['s_plmseq']
			];
		    if($this->type == 'new'){
		        $repeatRules[] = ['s_customer_name','s_apply_number'];
		    }elseif($this->type == 'comein'){
		        $repeatRules[] = ['s_customer_name','s_arri_number'];
		    }
			$state = !$this->import->checkRepeat($repeatRules);
		}
		
		//数据重复验证 - 数据库
		if($state && !empty($this->import->data))
		{
			foreach($this->import->data as &$item)
			{
				if($sample->checkRepeat($item))
				{
					$state = false;
					$item['excelInfo']['error'] = '记录已存在';
					$this->import->lineNum = $item['excelInfo']['line'];
					$this->import->lastError = $item['excelInfo']['error'];
				}
				
				//非初始化，品名权限
				if($isInit==false && $this->pwcode!='' && !\p::catesImport($this->pwcode,$item['s_cate'])){
					$state = false;
					$item['excelInfo']['error'] = '无此品类的导入权限';
					$this->import->lineNum = $item['excelInfo']['line'];
					$this->import->lastError = $item['excelInfo']['error'];
				}
				
				//非初始化，非强制导入
				if($isInit==false){
					/*
				    $find = [];
					//if ($this->type == 'comein' && $item['s_arri_number'] != '') {
				    if($item['s_arri_number']!=''){
						//$find = $sample->checkBaseNumber(0, $item['s_arri_brand'], $item['s_arri_number']);
						$find = $sample->checkBaseNumber(0, 0, $item['s_arri_number']);
					} else if ($item['s_apply_number'] != '') {
						$find = $sample->checkBaseNumber(0, $item['s_apply_brand'], $item['s_apply_number']);
				    }
				    if($find){
				        if($this->force){
        					$item['s_issame'] = 1;
				        }else{
        					$state = false;
        					$item['excelInfo']['error'] = '存在重复号码: '.implode(', ',$find);
        					$this->import->lineNum = $item['excelInfo']['line'];
        					$this->import->lastError = $item['excelInfo']['error'];
				        }
				    }*/
					$findCount = 0;
					if ($item['s_arri_number']) {
						$findRows = $sample->checkBaseNumberCount($item['s_arri_number']);
						$findCount = count($findRows);
					} else if ($item['s_apply_number']) {
						$findRows = $sample->checkBaseNumberCount($item['s_apply_number']);
						$findCount = count($findRows);
					}
					if ($findCount > 0) {
						if ($this->force) {
							$item['s_issame'] = 1;
						} else {
							$state = false;
							$item['excelInfo']['error'] = '存在重复号码: ' . implode(', ', $findRows);
							$this->import->lineNum = $item['excelInfo']['line'];
							$this->import->lastError = $item['excelInfo']['error'];
						}
					}
				}

				//s_p_id
				if($state && !empty($item['s_innum']))
				{
					$row = $this->db->get('p_code', ['pc_p_id', 'pc_outnum', 'opuser', 'create_time'], ['pc_innum'=>$item['s_innum']]);
					$item['s_p_id'] = $row['pc_p_id'];
					$item['s_outnum'] = $row['pc_outnum'] ?? '';
					$item['s_topro_opuser'] = $row['opuser'];
					$item['s_topro_time'] = $row['create_time'];
				}
			}
		}
		
		if($state && $this->type == 'comein'){
		    //登记批量新增
			foreach($this->import->data as &$item){
			    $item['s_form'] = 1;
			    $item['s_apply_comp'] = 1;
			    $item['s_check1'] = 1;
			    $item['s_check2'] = 1;
			    $item['s_check3'] = 1;
			    $item['s_has_purc'] = 1;
			    $item['s_purc_state'] = 10039;
			    $item['s_has_comein'] = 0;
			    $item['s_state_main'] = 'YJ';
			    $item['s_sign_time'] = $item['s_sign_time'] ?: getNowDate();
			}
		}
		if($state && $this->type == 'new'){
		    //申请批量新增
			foreach($this->import->data as &$item){
			    $item['s_form'] = 0;
			    $item['s_apply_date'] = $item['s_apply_date'] ?: getNowDate();
			}
		}
		//dd($this->import->data);
		//入库
		if($state && !empty($this->import->data))
		{
	        $sampleTag = 's_';
	        $techTag   = 'tech_';
	        $sampleNumidxTag   = 'sn_';
	        $sampleModelTxtTag   = 'sm_';
	        $this->db->Begin();
	        $oddno = $sample->getOddnoNext();
	        $user = makeOne(\model\user::class);
	        $opuser = getOpuser();
	        $userRow = $user->getRowInfo($opuser);
	        $applyDepa = $userRow['captions']['au_depa'] ?? '';
	        $applyArea = $userRow['captions']['au_area'] ?? '';
	        if($applyDepa === ''){
	            $applyDepa = $_SESSION['user']['au_depa_name'] ?? ($_SESSION['user']['au_depa'] ?? '');
	        }
	        if($applyArea === ''){
	            $applyArea = $_SESSION['user']['au_area_name'] ?? ($_SESSION['user']['au_area'] ?? '');
	        }
	        
			foreach($this->import->data as $k=>&$item){
				if($k > 0 && $k%1000 === 0) errorLog(__CLASS__.$this->title.':'.$k, 'import');
		       $sampleData = [];
		       $sampleNumidxData = [];
		       $sampleModelTxtData = [];
		       $techData = [];
		       $hasTech = false; //是否有技术部回复的数据
			   foreach($item as $field=>$value){
			       if(substr($field,0,strlen($sampleTag)) === $sampleTag){
			           $sampleData[$field] = $value;
			       }
			       if(substr($field,0,strlen($techTag)) === $techTag){
			           $techData[substr($field,strlen($techTag))] = $value;
			           if($value!='')
			             $hasTech=true;
			       }
			       if(substr($field,0,strlen($sampleModelTxtTag)) === $sampleModelTxtTag){
			           if($value!=''){
    			           $sampleModelTxtData[$field] = $value;
			           }
			       }
			       if(substr($field,0,strlen($sampleNumidxTag)) === $sampleNumidxTag){
			           if($value!=''){
    			           $sampleNumidxData[$field] = $value;
			           }
			       }
			   }
			   //如果未提供预编码并且不是初始化
			   if($isInit==false && $sampleData['s_form'] == '0' && (!isset($sampleData['s_code']) || empty($sampleData['s_code']))){
			       //自动计算预编码
			       $sampleData['s_code'] = $sample->getCodeNext();//获取下一预编码
			   }
			   //如果未提供流水号
			   if((!isset($sampleData['s_plmseq']) || empty($sampleData['s_plmseq']))){
			       //自动计算流水号
			       $sampleData['s_plmseq'] = $sample->getPlmSeqNext();//获取下一流水号
			   }
			   //如果非初始化，创建单号
			   if($isInit==false){
			       $sampleData['s_oddno'] = $oddno;
			   }
			   //如果非初始化，申请人自动取当前操作人
			   if($isInit==false){
			       $sampleData['s_apply_user'] = $opuser;
			       $sampleData['s_apply_depa'] = $applyDepa;
			       $sampleData['s_apply_area'] = $applyArea;
			       $sampleData['s_apply_date'] = getNowDate();
			       if($this->type == 'comein'){
    			       $sampleData['s_sign_opuser'] = $opuser;
    			       $sampleData['s_sign_time'] = getNowDate();
			       }
			   }
			   //申请人备注”字段内容自动代入到“客户要求”
			   if(trim($sampleData['s_custrequ'])==''){
			       $sampleData['s_custrequ'] = $sampleData['s_apply_remark'];
			   }
			   //“核对备注”字段内容自动代入到“目录组校对意见”
			   if(trim($sampleData['s_proof_catagroup'])==''){
			       $sampleData['s_proof_catagroup'] = $sampleData['s_remark'];
			   }
			   
			   //如果没有子状态，默认-1
			   if($sampleData['s_state_sub']=='')
			      $sampleData['s_state_sub'] = '-1';
			   //如果有流水号
			   if(!empty($sampleData['s_plmseq'])){
    			   $sampleData['s_formatnum'] = formatNum($sampleData['s_arri_number']);
    			   $sampleData['s_apply_number_format'] = formatNum($sampleData['s_apply_number']);
    			   if(!isset($sampleData['s_apply_date']) || $sampleData['s_apply_date']==''){
    			       $sampleData['s_apply_date'] = getNowDate();
    			   }
    			   if(isset($sampleData['s_purc_state']) && empty($sampleData['s_purc_state'])){
    			       $sampleData['s_purc_state'] = 10037;
    			   }
    			   $sampleData['create_time'] = getNowTime();
    			   $sampleData['update_time'] = $sampleData['create_time'];
				   //$sampleData['s_apply_user'] = 'test'; //QG
    			   $this->db->Insert('sample',$sampleData);
    			   $id = $this->db->id();
    			   if($hasTech && $id){
    			        $techData['st_s_id'] = $id;
                        if(!exists($techData['update_time']))
                            $techData['update_time'] = getNowTime();
                        else {
                            $techData['update_time'] = date(\mvc::$cfg['datetimeformat'],strtotime($techData['update_time']));
                        }
    			        $this->db->Insert('sample_tech',$techData);
    			   }
    			   if(!empty($sampleNumidxData) && $id){
    			       $sampleNumidxData['sn_s_id'] = $id;
    			       $sampleNumidxData['sn_numfomart'] = formatNum($sampleNumidxData['sn_number']);
                       $sampleNumidxData['opuser'] = getOpuser();
                       $sampleNumidxData['create_time'] = getNowTime();
                       $sampleNumidxData['update_time'] = getNowTime();
                       $this->db->Insert('sample_numidx',$sampleNumidxData);
    			   }
    			   if(!empty($sampleModelTxtData) && $id){
    			       $sampleModelTxtData['smt_s_id'] = $id;
                       $sampleModelTxtData['opuser'] = getOpuser();
                       $sampleModelTxtData['create_time'] = getNowTime();
                       $sampleModelTxtData['update_time'] = getNowTime();
                       $this->db->Insert('sample_model_txt',$sampleModelTxtData);
    			   }
			   }else{
			       dd('生成样品流水号失败');
			   }
			}
			$this->db->End();
		}
        return $this->import->output(); //生成处理结果
	}
	
	
	 /**批量更新
     * @param array|string $src 数组或者文件名
     * @return 可返回任意值(string|array|bool)，都会到前端
     */
    public function importUpdate($src) //固定
    {
		$state = $this->import->execute($src, $this->rulesUpdate);
		$sample = makeOne(\model\sample\sample::class);
		//验证
		if($state && !empty($this->import->data))
		{
			foreach($this->import->data as $k=>&$item)
			{
			    if($row = $sample->db->get('sample','*',['s_plmseq'=>$item['s_plmseq']])){
			        
			    }else{
    				$state = false;
    				$item['excelInfo']['error'] = '流水号不存在';
    				$this->import->lineNum = $item['excelInfo']['line'];
    				$this->import->lastError = $item['excelInfo']['error'];
			    }
			}
		}
		//更新
		if($state && !empty($this->import->data))
		{
			$this->db->begin();
			foreach($this->import->data as $k=>&$item)
			{

				if ($item['s_arri_number']) {
					$findRows = $sample->checkBaseNumberCount($item['s_arri_number'], $item['s_plmseq']);
					$findCount = count($findRows);
					if ($findCount > 0) {
						$state = false;
						$item['excelInfo']['error'] = '存在重复号码: ' . implode(', ', $findRows);
						$this->import->lineNum = $item['excelInfo']['line'];
						$this->import->lastError = $item['excelInfo']['error'];
					}
				}
				if ($state) {
					if (isset($item['s_purc_state']) && $item['s_purc_state'] == '10040') {
						$item['s_stop_fag'] = 1;
					}
					unset($item['excelInfo']);
					
					$sRow = $sample->db->get('sample', '*', ['s_plmseq' => $item['s_plmseq']]);
					if ($sRow && $sRow['s_stop'] == '0') {
						if ($item['s_purc_state'] == SAPMLE_DEFINE['到样']) {
							$item['s_state_main'] = 'YJ';
							if ($sRow['s_apply_type'] == '11824') {
								//产品对比分析
								$item['s_stop'] = 1;
							}
						}
						$where = ['s_plmseq' => $item['s_plmseq']];
						if (in_array($this->classId,['2','2_PurcState'])) {
							$where['s_check3'] = 1;
							$sample->db->update('sample', $item, $where);
							if ($this->classId == '2_PurcState' || ($this->classId == '2' && $item['s_purc_state'] && !$item['s_arrival_time'])) {
								$stateName = $sample->db->get('object', 'cn_name', ['o_id' => $item['s_purc_state']]);
								$this->history->addRow('sample', $sRow['s_id'], '采购状态', '[' . $stateName . '] ', true);
							} else if ($this->classId == '2' && $item['s_arrival_time']) {
								$stateName = $sample->db->get('object', 'cn_name', ['o_id' => $item['s_purc_state']]);
								$this->history->addRow('sample', $sRow['s_id'], '采购录入', '[' . $stateName . '] ', true);
							}
						} elseif (in_array($this->type, ['comein'])) {
							$where['s_has_purc'] = 1;
							$sample->db->update('sample', $item, ['s_plmseq' => $item['s_plmseq']]);
						}
					}
				}
			}
			$this->db->End();
		}
        return $this->import->output(); //生成处理结果
    }
		
}
