<?php 
namespace model\import;
use \model;
use model\freyIbp;

/**
 * 事业部商品批量更新导入
 */
class compPro  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->rulesUpdate = [
            ['key'=>'p_innum',  'caption'=>lg('物料编码'),  'must'=>true],
            ['key'=>'com_name', 'caption'=>lg('事业部'),'must'=>true],
        ];
        
		// 可更新字段
        $this->rulesUpdate[] = ['key'=>'plc_classification',       'caption'=>lg('产品分类'),       'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_p_state_main',         'caption'=>lg('产品状态'),       'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_p_model_year',         'caption'=>lg('年限'),           'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_p_chassis',            'caption'=>lg('底盘'),           'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_p_cc',                 'caption'=>lg('排量'),           'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_p_engine',             'caption'=>lg('发动机'),         'update'=>true];
        foreach(\mvc::$cfg['LANGS'] as $lk=>$lv){
            $this->rulesUpdate[] = ['key'=>'plc_p_'.$lv['field'],        'caption'=>lg($lv['name'].'名称'), 'update'=>true];
        }
        foreach(\mvc::$cfg['LANGS'] as $lk=>$lv){
            $this->rulesUpdate[] = ['key'=>'plc_p_model_'.$lv['field'],  'caption'=>lg($lv['name'].'车型'), 'update'=>true];
        }
        $this->rulesUpdate[] = ['key'=>'plc_safe_stock',            'caption'=>lg('安全库存'),       'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_top_stock',             'caption'=>lg('库存上限'),       'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_down_stock',            'caption'=>lg('库存下限'),       'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_waiting_days',          'caption'=>lg('入仓日期'),       'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_mnemonic_code',         'caption'=>lg('助记码（首选）'), 'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_mnemonic_code_bak',     'caption'=>lg('助记码（备选）'), 'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_precautions',           'caption'=>lg('安装注意事项'),   'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_shelf_name',            'caption'=>lg('销售质保期'),     'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_planned_delivery_date', 'caption'=>lg('计划交期(天)'),   'update'=>true];
        $this->rulesUpdate[] = ['key'=>'plc_shelf_date',            'caption'=>lg('工厂质保期'),     'update'=>true];

		$this->demoData = [];
		$this->demoremark = '';
	}
	
	
	/**批量更新
     * @param array|string $src 数组或者文件名
     * @return 可返回任意值(string|array|bool)，都会到前端
     */
    public function importUpdate($src) //固定
    {
		$state = $this->import->execute($src, $this->rulesUpdate);
        $proPro = new \model\pro\pro();
		//数据验证与定位
		if($state && !empty($this->import->data))
		{
			foreach($this->import->data as &$dv)
			{
                // 定位 p_id（通过物料编码）
                $p_id = $proPro->getPidByNumber($dv['p_innum']);
                // 定位 com_id（通过事业部中文名称）
                $com = $this->db->get('company', 'com_id', ['com_cn_name'=>$dv['com_name']]);
                $com_id = $com ?: 0;
                if(!$p_id || !$com_id){
                    $dv['excelInfo']['error'] = '无法定位事业部商品（物料编码='.$dv['p_innum'].', 事业部='.$dv['com_name'].'）';
                    $this->import->lineNum = $dv['excelInfo']['line'];
                    $this->import->lastError = $dv['excelInfo']['error'];
                    continue;
                }
                // 查 plc_id
                $plc = $this->db->get('pro_link_company', 'plc_id', ['plc_p_id'=>$p_id, 'plc_com_id'=>$com_id]);
                if(!$plc){
                    $dv['excelInfo']['error'] = '商品与事业部无关联记录';
                    $this->import->lineNum = $dv['excelInfo']['line'];
                    $this->import->lastError = $dv['excelInfo']['error'];
                    continue;
                }
                $dv['_plc_id'] = $plc;
                $dv['_p_id'] = $p_id;
                // 清理定位辅助字段，只保留可更新的
                unset($dv['p_innum'], $dv['com_name']);
			}
		}

		//入库
		if($state && !empty($this->import->data))
		{
            // 产品状态枚举：文字 → 键 的反向映射
            $statusReverse = [];
            foreach(explode(',', \mvc::$cfg['PROSTATUSITEMS']) as $val){
                $temp = explode(':', trim($val));
                if(count($temp) >= 2) $statusReverse[$temp[1]] = $temp[0];
            }
            $freyIbp = new freyIbp();
            foreach($this->import->data as &$dv)
            {
                // 跳过定位阶段已报错的行
                if(!empty($dv['excelInfo']['error'])) continue;
                
                $plc_id = $dv['_plc_id'];
                $p_id = $dv['_p_id'];
                unset($dv['_plc_id'], $dv['_p_id'], $dv['excelInfo']);
                // 产品状态：如果填的是文字（如"上市"），转为枚举键（如"03"）
                if(!empty($dv['plc_p_state_main']) && isset($statusReverse[$dv['plc_p_state_main']])){
                    $dv['plc_p_state_main'] = $statusReverse[$dv['plc_p_state_main']];
                }
                // 去掉空值（不填=不更新）
                $fields = array_filter($dv, function($v){ return $v !== '' && $v !== null; });
                if(empty($fields)) continue;
                // 更新
                $logArr = [['p_id'=>$p_id, 'plc_id'=>$plc_id]];
                $this->db->Begin();
                $this->db->update('pro_link_company', $fields, ['plc_id'=>$plc_id]);
                $proPro->addProComLinkSynLog($logArr, 'set', 'text');
                $freyIbp->receivePdmProLink($plc_id, 'com_link');
                $this->db->End();
            }
		}
		
		return $state ? $this->import->data : false;
	}
}