<?php
/*
 [
    'key'=>'rule1',                             //键名
    'caption'=>'编码规则',                      //字段名
    '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;

/**
 * 
 */
class codeInit  extends model
{
	 /**
     * 标题 (用于消息提醒)
     */
	public $title = '编码库'; //固定
	public $import = null;    //固定
	public $rules = null;    //规则
	public $demoData = null;  //样例数据
	public $demoremark = null;  //样例说明
	
	public function __construct()
	{
		parent::__construct(); //执行父类
		$this->import = new \lib\import();
		$this->rules = [
			 ['key'=>'pcate',            'caption'=>lg('产品线')],
			 ['key'=>'pc_cate',            'caption'=>lg('品名'),'must'=>true,'formatCell'=>'cate'],
		     ['key'=>'pc_outnum',           'caption'=>lg('GSP型号')],
		     ['key'=>'pc_innum',            'caption'=>lg('内部编码'),  'must'=>true,'minlen'=>3,'maxlen'=>50],
		     ['key'=>'pc_innum_abs',         'caption'=>lg('内部编码带ABS')],
		     ['key'=>'pc_state_main',         'caption'=>lg('主状态'),  'must'=>true],
		     ['key'=>'pc_state_sub',          'caption'=>lg('子状态')],
		     ['key'=>'pc_state_remark',          'caption'=>lg('状态备注')],
			 ['key'=>'pc_rule_1',              'caption'=>lg('编码规则'),  'formatCell'=> 'pro_code_ext'],
		     ['key'=>'pc_rule_a',              'caption'=>lg('补充规则A'),  'formatCell'=> 'pro_code_a'],
		     ['key'=>'pc_rule_b',              'caption'=>lg('补充规则B'),  'formatCell'=>'pro_code_b'],
		     ['key'=>'pc_rule_c',              'caption'=>lg('补充规则C'),  'formatCell'=>'pro_code_c'],
		     ['key'=>'pc_usa_make',              'caption'=>lg('北美品牌'),  'formatCell'=>'mk_id'],
			 ['key'=>'pc_fno_date',             'caption'=>lg('编码时间'),'type'=>'date'],
			 ['key'=>'pc_pf_id',         'caption'=>lg('编码品牌'),'formatCell'=>'pf_id'],
		     ['key'=>'pc_fno',        'caption'=>lg('编码品牌号'),'minlen'=>3,'maxlen'=>255],
			 ['key'=>'tags',             'caption'=>lg('数据版本'),'formatCell'=>'tags'],
			 ['key'=>'pc_release_time',             'caption'=>lg('发布时间'),'type'=>'date'],
			 ['key'=>'pc_release_vers',             'caption'=>lg('目录版本号')],
			 ['key'=>'pc_remark',             'caption'=>lg('产品备注')],
		];

		$this->demoData = [
			
		];

		$this->demoremark = '';
	}
	
	 /**处理导入
     * @param array|string $src 数组或者文件名
     * @param isInit 是否是初始化
     * @return 可返回任意值(string|array|bool)，都会到前端
     */
    public function import($src,$isInit=false) //固定
    {
		$state = $this->import->execute($src, $this->rules);
		
		//数据重复验证
		if($state && !empty($this->import->data))
		{
			$check = new check();
			foreach($this->import->data as &$dv)
			{
				$exist = $check->checkExist('p_code', $dv);
				if(!empty($exist))
				{
					$state = false;
					$dv['excelInfo']['error'] = '记录已存在';
					$this->import->lineNum = $dv['excelInfo']['line'];
					$this->import->lastError = $dv['excelInfo']['error'];
					continue;
				}
			}
		}
		//入库
		if($state && !empty($this->import->data))
		{
			$opuser = getOpuser();
			$datetime = getNowTime();
			$tags = new tags();
			$pro = new \model\pro\pro();
			$allPcArr = [];
			$this->db->Begin();
			foreach($this->import->data as $k=>$mv)
			{
				if($k > 0 && $k%1000 === 0) errorLog(__CLASS__.$this->title.':'.$k, 'import');
				$set = [
					'create_time'=>$datetime,
					'update_time'=>$datetime,
					'opuser'=>$opuser
				];
				$fashfileds = array_column($this->rules, 'key');
				foreach($fashfileds as $filed)
				{
					if(isset($mv[$filed]) && !in_array($filed, ['tags']) && stripos($filed, 'pc_') === 0) $set[$filed] = $mv[$filed];
				}

				$this->db->insert('p_code', $set);
				$pc_id = $this->db->id();
				$pro->addProductByCode($pc_id, 'init');
				if(isset($mv['tags']))
				{
					$tags->changeTagsLink('pro', 'replace', ['t_id'=>$mv['tags'], 'value_id'=>$pc_id]);
				}
			}
			$this->db->End();
		}
        return $this->import->output(); //生成处理结果
	}
	
	
}