<?php

namespace admin\action;

use model\pro\packing;
use \model\pro\pro;
use \model\pro\photo;
use \model\pro\master;

class proAction  extends \action
{
    public $pro = null;

	public function __construct()
    {
		$this->pro = new pro();
	}


	function getSetstate()
	{
		$data = [
			['key'=>'Y1', 'value'=>'Y1'],
			['key'=>'Y2', 'value'=>'Y2'],
			['key'=>'Y3', 'value'=>'Y3'],
			['key'=>'Y4', 'value'=>'Y4'],
			['key'=>'Y6', 'value'=>'Y6'],
		];
		$this->successJson($data);
	}


	function total()
	{
		$this->successJson($this->pro->total());
	}

	function totalCommon($states)
	{
		$this->successJson($this->pro->totalCommon($states));
	}

    public function listView()
    {
        $req = \mvc::$req;
        if(!isset($req['from']))  $req['from'] = 'pro';
		$carmodel = new \model\carmodel();
		$pack = new \model\pro\packing();
		\view::set('proExpModelfields', $carmodel->proExpModelfields);
		\view::set('packFileds',$pack->packFileds);
		\view::set('from',$req['from']);
        \view::put('pro/list');
    }
    
    public function list()
    {
        $req = \mvc::$req;
		//前置条件
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
		}
		if(isset($req['keys'])){
			$rules['keys'] = explode(',',$req['keys']);
		}
		if(isset($rules['findNulls']) && $rules['findNulls']){
			$rules['findNulls'] = json_decode(base64_decode($rules['findNulls']),true);
		}
		if(isset($req['coutype'])) $rules['coutype'] = $req['coutype'];
        $data = $this->pro->list($rules,$req['filters'], $req['page'], $req['rows'], $req['sidx'], $req['sord'],'p_outnum');
        $this->successJson($data);
    }
    
    //
    public function exportMQ(){
        error_reporting(E_ALL& ~E_NOTICE);
        set_time_limit(0);
        $mq = makeOne(\lib\mqRabbitMQ::class,'exportMQ',\mvc::$cfg['exportMQ']);
        echo "exportMQ runing.\r\n";
        $mq->receive(function($talk,$queue){
            sleep(1);
            $data = json_decode($talk->getBody(),true);
            $export = new \model\pro\export2();
            try {
                $queue->ack($talk->getDeliveryTag());
                if($export->export($data['msgId'],$data['count'],$data['filename'],$data['username'],$data['lgtag'],$data['type'],$data['options'],$data['rules'],$data['sql'],$data['pagesize'])){
                    //$queue->ack($talk->getDeliveryTag());
                }
            } catch (\Exception $e ) {
                makeOne(\model\message::class)->update($data['msgId'],['amsg_body'=>lg('失败').': '.$e->getMessage()]);
                //$queue->ack($talk->getDeliveryTag());
            }
            unset($export);
            return true;
        });
        echo "exportMQ exit.\r\n";
    }
    //监听队列
    public function export2($type,$options,$req)
    {
        ignore_user_abort(true);
		ini_set('memory_limit', \mvc::$cfg['export_memory_limit']);
		set_time_limit(\mvc::$cfg['export_time_limit']);
        //type:xlsx|xlsxzip|imgxlsx|imgzip
        $options = json_decode(base64_decode($options),true);
        parse_str(html_entity_decode($req), $req);
		//前置条件
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
			$options['numbers'] = $req['numbers'];
		}
		if(isset($req['keys'])){
			$rules['keys'] = explode(',',$req['keys']);
		}
        $pagesize = \p::fieldval('1100','export_limit');
        if(\p::isAdmin()) $pagesize = 2147483647;
        if($options['model']['hasmodel']){
            if($options['model']['modelCel']=='one'){
                $rules['modelsOne'] = 1;
            }else if($options['model']['modelCel']=='more'){
                $rules['modelsAll'] = 1;
            }else{
                $rules['modelsRows'] = 1;
            }
        }
        if(empty($pagesize)) $pagesize = \mvc::$cfg['export_record_limit'];
        if($options['oe']['qty']>200) $options['oe']['qty'] = 200;
        $options['fac'] = ($options['fac']!='') ? explode(',',$options['fac']) : [];
        
		$rules['getSQL'] = true;
        $sql = $this->pro->list($rules,$req['filters'], 1, $pagesize, '', '','p_cate,p_outnum');
        $sql = preg_replace('/ORDER(.*)/','',$sql);
        $sql = preg_replace('/SELECT(.*)FROM/','SELECT p.p_id,p_cate,p_pic,p_innum,p_outnum,p_state_main,p_sales_qty,p_vio FROM',$sql);
        $sql = str_replace('"','`',$sql);
        $sql = "SELECT * FROM (".$sql.") proAction GROUP BY p_id";
        
        $filename = date('ymdHis');
        $msg = [
        	'amsg_title'=> lg('自由导出').','.lg('序号').': '.$filename,
        	'amsg_body'=> lg('排队中'),
        	'amsg_send_mail'=>0,
			'amsg_send_sms'=> 0
        ];
        $msgId = makeOne(\model\message::class)->send([getOpuser()],$msg);
        $export = makeOne(\model\pro\export2::class);
        $count = $export->count($sql);
        $backJson = ['mq'=>false];
        $newRules['models'] = $rules['models'];
        $newRules['modelFields'] = $rules['modelFields'];
        $newRules['modelDisplayFields'] = $rules['modelDisplayFields'];
        $newRules['modelPos'] = $options['modelPos'];
        if($count>2000){
            //加入队列
            if($msgId){
                $mq = makeOne(\lib\mqRabbitMQ::class,'exportMQ',\mvc::$cfg['exportMQ']);
                $mq->send(json_encode([
                    'msgId'=>$msgId,
                    'count'=>$count,
                    'filename'=>$filename,
                    'username'=>getOpuser(),
                    'lgtag'=>cateName(),
                    'type'=>$type,
                    'options'=>$options,
                    'rules'=>$newRules,
                    'sql'=>$sql,
                    'pagesize'=>$pagesize
                ]));
            }
            $mq->close();
            $backJson = ['mq'=>true];
            (new \model\user)->toLog('导出','自由导出(队列)'.', 共 '. $count . '条, '.$sql,$count);
        }else{
            $export->export($msgId,$count,$filename,getOpuser(),cateName(),$type,$options,$newRules,$sql,$pagesize);
            (new \model\user)->toLog('导出','自由导出'.', 共 '. $count . '条, '.$sql,$count);
        }
        $this->successJson($backJson);
    }
    
    public function export($type,$options,$req)
    {
		ini_set('memory_limit', \mvc::$cfg['export_memory_limit']);
		set_time_limit(\mvc::$cfg['export_time_limit']);
        //type:xlsx|xlsxzip|imgxlsx|imgzip
        $options = json_decode(base64_decode($options),true);
        parse_str(html_entity_decode($req), $req);
		//前置条件
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
			$options['numbers'] = $req['numbers'];
		}
		if(isset($req['keys'])){
			$rules['keys'] = explode(',',$req['keys']);
		}
        $pagesize = \p::fieldval('1100','export_limit');
        if(\p::isAdmin()) $pagesize = 2147483647;
        if($options['model']['hasmodel']){
            if($options['model']['modelCel']=='one'){
                $rules['modelsOne'] = 1;
            }else if($options['model']['modelCel']=='more'){
                $rules['modelsAll'] = 1;
            }else{
                $rules['modelsRows'] = 1;
            }
        }
        //dd($rules);
        if(empty($pagesize)) $pagesize = \mvc::$cfg['export_record_limit'];
        $data = $this->pro->list($rules,$req['filters'], 1, $pagesize, '', '','p_cate,p_outnum');
        //dd($data);
        if(empty($data['rows'])) exit(lg('无数据'));
        
        if($options['oe']['qty']>200) $options['oe']['qty'] = 200;
        $options['fac'] = ($options['fac']!='') ? explode(',',$options['fac']) : [];
        (new \model\user)->toLog('导出','自由导出(1)'.', 共 '. count($data['rows']) . '条, ');
        $export = makeOne(\model\pro\export::class,$options,$data['rows']);
        if($type=='xlsx'){
            $export->imgxlsx($options,false);
        }else if($type=='xlsxzip'){
            $export->zip($options);
        }else if($type=='imgxlsx'){
            $export->imgxlsx($options,true);
        }else if($type=='imgzip'){
            $export->imgzip($options);
        }
    }


	/**
	  * @method 编码库
	  * @author soul
	  */
	public function exportState($url,$query,$fields,$keyField,$keys,$searchoptions,$pwcode='',$page=1,$pagesize=2147483647,$callback=null)
	{
		ini_set('memory_limit', \mvc::$cfg['export_memory_limit']);
		set_time_limit(\mvc::$cfg['export_time_limit']);
		$bigDataPageSize = 65535;
		$excelType = 'binary'; //binary | xml ,默认 binary
		
		$dir = str_replace('\\','/',__DIR__);
		preg_match('/(\w+)\/action/i',str_replace('\\','/',__DIR__),$m);
		$path_info = '/'. explode($m[1].'/',$url)[1];
		
        $fields = html_entity_decode($fields);
        $arr1 = explode(',',$fields);
        $fields = [];
        foreach($arr1 as $k=>$v){
            $arr2 = explode('=>',$v);
            $fields[$arr2[0]] = $arr2[1];
        }
        parse_str(html_entity_decode($query), $post);
        /*
        if(!\p::isAdmin() && !in_array($url,\mvc::$cfg['export_record_max_urls'])){
           $pagesize = \mvc::$cfg['export_record_limit'];
            if($pwcode!=''){
                $pagesize = \p::fieldval($pwcode,'export_limit');
            }
        }
        if(empty($pagesize)) $pagesize = \mvc::$cfg['export_record_limit'];*/
        $post['page'] = 1;
        $post['rows'] = $pagesize;
        list($class,$method,$uri_params,$req,$reqUriValues) = \mvc::parseurl($path_info);
		if($req){
		    foreach ($req as $k=>$v){
		        $post[$k] = $v;
		    }
		}
		\mvc::$req = [];
		if(strpos($url,'?')){
		    parse_str(html_entity_decode(explode('?',$url)[1]), \mvc::$req);
		}
		$_hasJsonFields = [];
        if(!empty($post['_hasJsonFields'])){
    		$_hasJsonFields = explode(',',$post['_hasJsonFields']);
        }
	    foreach ($post as $k=>$v){
	        if(in_array($k,$_hasJsonFields)) $v = json_decode(urldecode(base64_decode($v)), true);
	        \mvc::$req[$k] = $v;
	    }	
	    
        $req = \mvc::$req;
		//前置条件
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
		}
		if(isset($req['keys'])){
			$rules['keys'] = explode(',',$req['keys']);
		}
		if(isset($rules['findNulls']) && $rules['findNulls']){
			$rules['findNulls'] = json_decode(base64_decode($rules['findNulls']),true);
		}
		$rules['getDoneSQL'] = true;
        $sql = $this->pro->list($rules,$req['filters'], $req['page'], $req['rows'], $req['sidx'], $req['sord'],'p_outnum');
        $fields = "p.*";
        /*
        $fields .= ",   (
                        select 
                          mpro.`p_outnum` 
                        from 
                          p_code 
                          JOIN pro mpro ON pc_merge_p_id = mpro.`p_id` 
                        where 
                          pc_p_id = p.p_id 
                        limit 
                          1
                      ) AS `merge_outnum`";
        $fields .= ",   (
                        select 
                          mpro.`p_innum` 
                        from 
                          p_code 
                          JOIN pro mpro ON pc_merge_p_id = mpro.`p_id` 
                        where 
                          pc_p_id = p.p_id 
                        limit 
                          1
                      ) AS `merge_innum`";
        */
	    $join = "\r\n ";
	    $sql = preg_replace('/SELECT\s.*\s+FROM/is',"SELECT ".$fields." FROM",$sql);
	    //$sql = preg_replace('/\sAS\s`p`(.*)\sWHERE/is','AS `p` "\\1"'.$join." WHERE",$sql);
	    $pro = new \model\pro\pro();
	    $db = $pro->getDb();
        //$rows  = $db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
        $data = [];
        
        $cateRows = $db->select('pro_cate',['id'=>['parent_id',cateName()]]);
        $tRows = $db->query("SELECT from_id,pc_p_id to_id,pc_outnum,pc_innum FROM p_code
JOIN (SELECT pc_p_id from_id,pc_merge_p_id FROM p_code WHERE pc_merge_p_id>0) t1 ON t1.pc_merge_p_id = pc_p_id
WHERE pc_p_id>0")->fetchAll(\PDO::FETCH_ASSOC);
        $mergeRows = [];                        
        foreach($tRows as $tRow){
            $mergeRows[$tRow['from_id']] = $tRow;
        }       
        unset($tRows);
        $header = [
            lg('主状态'),
            lg('产品线'),
            lg('品名')
        ];

        if(\p::fieldhas('1D00','outnum')) $header[] = lg('GSP型号');
        if(\p::fieldhas('1D00','innum')) $header[] = lg('内部编码');
        if(\p::fieldhas('1D00','merge_outnum')) $header[] = lg('合并后型号');
        if(\p::fieldhas('1D00','merge_innum')) $header[] = lg('合并后内部编码');
        
        $cacheDir = \mvc::$cfg['dir']['cache'].'/'.date('Ym');
	    mkdirs($cacheDir);
        $tempfile = $cacheDir.'/'.getOpuser().guid().'.xlsx';
        include(\mvc::$cfg['mvcDir'].'/lib/excel/excelInterface.php');
        include(\mvc::$cfg['mvcDir'].'/lib/excel/excel.php');
        include(\mvc::$cfg['mvcDir'].'/lib/excel/excelBase.php');
        include(\mvc::$cfg['mvcDir'].'/lib/excel/excelXlsx.php');
        
        $excel = new \lib\excel\excel('xlsx');
        $excel->setDirFile($tempfile);
        //$excel = new \lib\exportXlsxDll($cacheDir,$tempfile);
        $excel->header();
        $excel->bookBegin();
        $excel->sheetBegin(lg('基本资料'),$header);
        
        //foreach($rows as $k=>$row){
        
        $db->useBuff(false);
        $res = $db->query($sql);
        while($row = $res->fetch(\PDO::FETCH_ASSOC)){
            //$row = $pro->formatRow($row);
            $pid = $row['p_id'];
            if(isset($cateRows[$row['p_cate']])){
                $cateName = $cateRows[$row['p_cate']][cateName()];
                $bigCateName = $cateRows[$cateRows[$row['p_cate']]['parent_id']][cateName()];
            }else{
                $cateName = '';
                $bigCateName = '';
            }
            if($mergeRows[$pid]){
                $row['merge_outnum'] = $mergeRows[$pid]['pc_outnum'];
                $row['merge_innum'] = $mergeRows[$pid]['pc_innum'];
            }
            $item = [
                'p_state_main'=>$row['p_state_main'],
                //'p_bigcate'=>$row['langs']['p_bigcate'][LG],
                //'p_cate'=>$row['langs']['p_cate'][LG],
                'p_bigcate'=>$bigCateName,
                'p_cate'=>$cateName
            ];
            if(\p::fieldhas('1D00','outnum')) $item['p_outnum'] =$row['p_outnum'];
            if(\p::fieldhas('1D00','innum')) $item['p_innum'] =$row['p_innum'];
            if(\p::fieldhas('1D00','merge_outnum')) $item['merge_outnum'] =$row['merge_outnum'];
            if(\p::fieldhas('1D00','merge_innum')) $item['merge_innum'] =$row['merge_innum'];
            
            $excel->append($item);
    	    unset($rows[$k]);
        }
        $excel->sheetEnd();
        $excel->bookEnd();
	    //readfile($tempfile);
        //ob_end_flush();
        //unlink($tempfile);
        //exit();
	}

	/**
	  * @method 编码库
	  * @author soul
	  */
	public function getCodeList()
	{
		$req = \mvc::$req;
		$rules = $this->urlRulesToWhere($req);
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = arryNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
		}
        $data = $this->pro->getCodeList($req, $rules);
        $this->successJson($data);
	}

	/**
	  * @method 编辑编码库
	  * @param  id  int  [必填] pn_id
	  * @param  field  string  [必填] 字段
	  * @author soul
	  */
	public function setCodeCell()
	{
		$req = \mvc::$req;
		$result = '';
		if(!empty($req['id']) && preg_match('/^\d+$/', $req['id']))
		{
			$setArr = [
				$req['field']=>$req[$req['field']]
			];
			$result = $this->pro->setCodeCell($req['id'], $setArr);
		}
		echo $result;
	}

	public function setCnNosale()
	{
		$req = \mvc::$req;
		$data = $this->pro->setCnNosale($req['ids'], $req['val']);
		$this->successJson($data);
	}

	public function setCodeCate()
	{
		$req = \mvc::$req;
		$data = $this->pro->setCodeCate($req['ids'], $req['pc_cate']);
		$this->successJson($data);
	}

	/**
	  * @method 删除编码库
	  * @param  ids  string  [必填] pc_id  多个逗号分隔
	  * @author soul
	  */
	public function delCode()
	{
		$req = \mvc::$req;
		$data = $this->pro->delCode(explode(',', $req['ids']));
		$this->successJson($data);
	}

	/**
	  * @method 变更主状态
	  * @param  ids  string  [必填] pc_id  多个逗号分隔
	  * @author soul
	  */
	public function changeStateMain()
	{
		$req = \mvc::$req;
		$data = $this->pro->changeStateMain(explode(',', $req['ids']), $req);
		$this->successJson($data);
	}


	/**
	  * @method 生成编码
	  * @param  ids  string  [必填] pc_id  多个逗号分隔
	  * @author soul
	  */
	public function buildCode()
	{
		$req = \mvc::$req;
		$data = $this->pro->buildCode(explode(',', $req['ids']), $req['auto'], $req['pcr_id']);
		$this->successJson($data);
	}


	/**
	  * @method 审核编码
	  * @param  ids  string  [必填] pc_id  多个逗号分隔
	  * @author soul
	  */
	public function checkCode()
	{
		$req = \mvc::$req;
		$data = $this->pro->checkCode(explode(',', $req['ids']));
		$this->successJson($data);
	}



	//取附件
    public function attaqtyList()
    {
        $req = \mvc::$req;
		//前置条件
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
		}
        $data = $this->pro->list($rules,$req['filters'], $req['page'], $req['rows'], $req['sidx'], $req['sord'],'p_outnum');
		if(!empty($data)){
			foreach($data['rows'] as &$row){
				$attaRow = $this->pro->getAttaqtyByPid($row['p_id']);
				if(!empty($attaRow)){
					foreach($attaRow as $field=>$value){
						$regi = substr($field,strrpos($field, '_')+1);
						if($regi!='' && is_numeric($regi)){
							$row['pa_'.$regi] = $value;
						}
					}
				}//$data['rows']
			}
		}
        $this->successJson($data);
    }

    public function detail($p_id,$outnum='')
    {
        if($p_id){
            $item = $this->pro->getRowByKey($p_id);
        }else if($outnum){
            $item = $this->pro->getRowByFieldValue('p_outnum_format',formatNum($outnum));
            $p_id = $item['p_id'];
        }
		
        \view::set('item',$item);
		\view::put('pro/detail');
    }

    public function getNumberByPid($num)
    {
        $num = $this->pro->getPidByNumber($num);
        $this->successJson($num);
    }

    public function getPidByNumber($num)
    {
        $pid = $this->pro->getPidByNumber($num);
        $this->successJson(['pid'=>$pid]);
    }

    public function getRowByNumber($num)
    {
        $pid = $this->pro->getPidByNumber($num);
		if($pid){
			$data = $this->pro->getRowByKey($pid);
			if(!empty($data))
				$this->successJson($this->pro->formatRow($data));
		}
		$this->successJson(0);
    }

	public function chkProIdByAny()
	{
		$this->successJson($this->pro->chkProIdByAny(\mvc::$req));
	}

    public function base($p_id)
    {
        $item = $this->pro->formatRow($p_id);
		$item['tousu_num'] = $this->pro->getTousuNum($p_id);
		$item['ppic_type'] = $this->pro->getPicType($item['p_pic']);
		
		$tItem = [$item];
		$country = new \model\country();
		$tItem = $country->getDataCountryId($tItem, 'pro');
		$tItem = $country->formatDataCountry($tItem, 1);
		$item = $tItem[0];
		$item['stock'] = $this->pro->getStock($item['p_outnum']);
		

        \view::set('item',$item);
		//合并记录
		$pchids = $this->pro->getMergeHistory($p_id);
		$mergeArr = [];
		if(!empty($pchids))
		{
			$list = $this->pro->getMergeList(['pch_id'=>$pchids]);
			$mergeArr = $list['rows'];
		}
		\view::set('mergeArr', $mergeArr);
		\view::put('pro/base/form');
    }

    public function pic($p_id)
    {
        $item = $this->pro->formatRow($p_id);
        \view::set('item',$item);
		\view::put('pro/pic');
    }

    public function pack()
    {
		$req = \mvc::$req;
		$p_id = $req['p_id'];
		$area = $req['area'];
        $pack = new packing();
		$packArea = $pack->getProPackArea($p_id);
		if(empty($area)) $area = $packArea[0]['id'];
        $item = $pack->getProPack($p_id, $area);

        \view::set('item',$item);
        \view::set('p_id',$p_id);
        \view::set('area',$area);
        \view::set('hasArea',$hasArea);
        \view::set('packArea', $packArea);
        \view::set('packFileds',$pack->packFileds);
		\view::put('pro/pack');
    }

    public function getPackFiledAndArea()
    {
		$req = \mvc::$req;
        $pack = new packing();
		$data = ['packFileds'=>$pack->packFileds, 'packArea'=>$pack->packArea];
		$this->successJson($data);
    }
    
    public function bom($p_id)
    {
        $proRow = $this->pro->getRowByKey($p_id);
        \view::set('proRow',$proRow);
		\view::put('pro/bom');
    }
    
    public function order()
    {
		\view::put();
    }
    
    public function base_order($p_id)
    {
        $proRow = $this->pro->getRowByKey($p_id);
        \view::set('proRow',$proRow);
		\view::put();
    }
    
    public function base_sample($p_id)
    {
        if(empty($p_id)){
		    exitJson(lg('参数错误'));
		}else{
            $proRow = $this->pro->getRowByKey($p_id);
            \view::set('proRow',$proRow);
    		\view::put();
		}
    }
    
    public function getOrder()
    {
        $req = \mvc::$req;
		$rules = $this->urlRulesToWhere($req);
        $data = (makeOne(\model\bi\bi::class))->getOrder($rules,$req['filters'], $req['page'], $req['rows'], $req['sidx'], $req['sord']);
        $this->successJson($data);
    }

    public function baseEdit()
    {
        $req = \mvc::$req;
        $key = $req['p_id'];
        $link_tags = $req['link_tags'];
        unset($req['link_tags']);
        if($key==0){
            $result = $this->pro->baseAdd($req,$link_tags);
        }else{
            $result = $this->pro->baseEdit($key,$req,$link_tags);
        }
        $this->successJson($result);
    }

	//取父零件
    public function getFather($p_id)
    {
        $data = $this->pro->getFather($p_id);
        $this->successJson($data);
    }

	//取子零件
    public function getSon($p_id)
    {
        $data = $this->pro->getSon($p_id);
        $this->successJson($data);
    }

	//添加父零件
    public function addFather($p_id,$father_p_id)
    {
		if($p_id == $father_p_id){
			$this->msgJson(lg('自己不能添加自己'));
		}
		if($this->pro->hasSon($p_id,$father_p_id)){
			$this->msgJson(lg('执行失败, 此型号已存在于子零件中'));
		}
		$data = [
			'pf_father_pid' => $father_p_id,
			'pf_son_pid' => $p_id,
		];
        $this->pro->addFatherSon($data);
        $this->successJson(lg('执行成功'));
    }

	//添加子零件
    public function addSon($p_id,$son_p_id)
    {
		if($p_id == $son_p_id){
			$this->msgJson(lg('自己不能添加自己'));
		}
		if($this->pro->hasFather($p_id,$son_p_id)){
			$this->msgJson(lg('执行失败, 此型号已存在于父零件中'));
		}
		$data = [
			'pf_father_pid' => $p_id,
			'pf_son_pid' => $son_p_id,
		];
        $this->pro->addFatherSon($data);
        $this->successJson(lg('执行成功'));
    }

	//删父或子零件
    public function deleteSon($p_id)
    {
        $data = $this->pro->deleteSon($p_id,\mvc::$req['ids']);
        $this->successJson($data);
    }

    //编码测试
    public function testProCodeCreate($plmseq,$innum)
    {
        $codeRule = new \model\pro\codeRule();
        $data = $codeRule->createCode($plmseq,$innum);
        $this->successJson($data);
    }



	/**
	 * 通过属性集合住创建产品CODE
	 * @param  s_cate  int  [必填] 品名
	 * @param  s_procode_ext  string  [必填] 扩展类型
	 * @param  s_usa_make  string  [选填] 大品牌
	 * @param  s_procode_a  string  [选填]
	 * @param  s_procode_b  string  [选填]
	 * @param  s_procode_c  string  [选填]
	 * @param  innum string [必填] 内部编码
	 * @author soul
	 */
	public function createCodeByValues()
    {
		$req = \mvc::$req;
        $codeRule = new \model\pro\codeRule();
        $data = $codeRule->createCodeByValues($req,$req['innum']);
		$this->successJson($data);
    }



    public function editCell()
    {
		$req = \mvc::$req;
        $id = $req['id'];
        $oper = $req['oper'];
        $field = $req['field'];
		if(isset($req['value']))
			$value = $req['value'];
 		else
			$value = $req[$field];
        if($oper=='edit'){
            $result = $this->pro->setValue($id,$field,$value);
        }
    }

    public function editCellAttaqty()
    {
		$req = \mvc::$req;
        $id = $req['id'];
        $oper = $req['oper'];
        $field = $req['field'];
		if(isset($req['value']))
			$value = $req['value'];
 		else
			$value = $req[$field];
        if($oper=='edit'){
            $result = $this->pro->setAttaqty($id,$field,$value);
        }
    }



	/**
	  * @method 新增产品
	  * @param  p_cate  int  [必填] 品名
	  * @param  p_innum  string  [必填] 内部编码
	  * @param  nums  array  [必填] 自动生成的编码
	  * @author soul
	  */
	public function addNewProduct()
	{
		$req = \mvc::$req;
		$autonums = [];
		foreach($req['nums'] as $fac=>$nv)
		{
			if($fac == 'OUTNUM'){
				$row = json_decode($nv['old'], true);
				$row['num'] = $nv['num'];
				$autonums[$fac] = $row;
			}else{
				foreach($nv as $nkk=>$nvv)
				{
					$row = json_decode($nvv['old'], true);
					$row['num'] = $nvv['num'];
					$autonums[$fac][] = $row;
				}
			}
		}
		$baseArr = [
			'p_cate'=>$req['p_cate'],
			'p_innum'=>$req['p_innum']
		];
		$othArr = [
			'autonums'=>$autonums
		];
		$data = $this->pro->addProductBySelf($baseArr, $othArr);
		$this->successJson($data);
	}

	/**
	  * @method 号码自动完成
	  * @param  type string  [选填] outnum[默认] innum  oth:非gsp品牌号  all:不限制
	  * @param  num string  [必填] 号码
	  * @author soul
	  */
	public function autocomNum()
	{
		$req = \mvc::$req;
		$data = $this->pro->autocomNum($req);
		$this->successJson($data);
	}

	
	/**
	  * @method 导入中心
	  */
	  public function import()
	  {
		  \view::put();
	  }

	
	/**
	  * @method 产品比较
	  * @param  pids string  [选填] 产品ID，逗号分隔
	  * @param  nums string  [选填] GSP型号，逗号分隔
	  * @author soul
	  */
	  public function compare()
	  {
		  $req = \mvc::$req;
		  $maxItem = 20;
		  $req['maxItem'] = $maxItem;
		  if(!empty($req['pids']))
		  {
			    $pids = [];
				foreach(explode(',', $req['pids']) as $k=>$v)
				{
					$t = explode('-', $v);
					$pids[] = (int) $t[0];
				}
				$req['pids'] = implode(',', $pids);
		  }
		  $dataArr = $this->pro->getCompare($req);
		  $bom_kv = json_encode($this->pro->getBomKv());
		  
		  \view::set('bom_kv', $bom_kv);
		  \view::set('ip_test_edi_runtime', gethostbyname("test.edi-runtime.jdl.cn")); //test.edi-runtime.jdl.cn
		  \view::set('ip_edi_runtime', gethostbyname("edi-runtime.jdl.cn")); //test.edi-runtime.jdl.cn
		  \view::set('maxItem', $maxItem);
		  \view::set('maxInput', 6);
		  \view::set('nums', $req['nums']);
		  \view::set('itemArr', $dataArr['items']);
		  \view::set('paraArr', $dataArr['para']);
		  \view::set('dataArr', $dataArr);
		  \view::set('req', $req);
		  \view::put();
	  }

	public function addMerge()
	{
	   $req = \mvc::$req;
	   $data = $this->pro->addMerge($req['pch_p_id_from'], $req['pch_p_id_to']);
	   $this->successJson($data);
	}

	public function getMergeList()
	{
		$req = \mvc::$req;
		$rules = $this->urlRulesToWhere($req);
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
		}
        $data = $this->pro->getMergeList($req, $rules);
        $this->successJson($data);
	}

	public function getMergeEndList()
	{
		$req = \mvc::$req;
		$rules = $this->urlRulesToWhere($req);
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
		}
        $data = $this->pro->getMergeEndList($req, $rules);
        $this->successJson($data);
	}

	public function getExchageAllList()
	{
		$req = \mvc::$req;
		$rules = $this->urlRulesToWhere($req);
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
		}
        $data = $this->pro->getExchageAllList($req, $rules);
        $this->successJson($data);
	}

	public function delMerge()
	{
		$req = \mvc::$req;
		$data = $this->pro->delMerge(explode(',', $req['ids']));
		$this->successJson($data);
	}

	public function checkMerge()
	{
		$req = \mvc::$req;
		$data = $this->pro->checkMerge(explode(',', $req['ids']), $req);
		$this->successJson($data);
	}

	public function rollbackMerge()
	{
		$req = \mvc::$req;
		$data = $this->pro->rollbackMerge($req['id'], $req);
		$this->successJson($data);
	}
	

	/**
	  * @method 选择器
	  * @param  sql    string  [sql+db] base64:xxxxxx select brand_name name, brand_id id, brand_initial letter from m_cn_model group by brand_id order by brand_initial
	  * @param  db    string  [sql+db] 选择sql时必填
	  * @param  table  string  [选填] factory | make
	  * @param  style  string  [选填] 选择模式 anychk:多选  空(默认):单选
	  * @param  letter  int  [选填] 是否启用字母选择  1(默认)|-1
	  * @param  liwidth  int  [选填] 每个名称宽度 默认 150
	  * @param  data  string  [选填] base64:W3sibmFtZSI6Ilx1NTAzYyIsImlkIjoiMTIzIn0seyJuYW1lIjoiXHU1MDNjMiIsImlkIjoiNDU2In1d  base64_encode(json_encode([["name"=>"值", "id"=>"123"], ["name"=>"值2", "id"=>"456"]]))
	  * @author soul
		传sql   pro/select?db=main&sql=select+brand_name+name%2C+brand_id+id%2C+brand_initial+letter+from+m_cn_model+group+by+brand_id+order+by+brand_initial&style=anychk&callback=onSelectUser&letter=1
        传sql base64 /pro/select?sql=base64:xxxxxx
		model/pro/pro/getSelect配置  pro/select?table=cnmakesql&callback=onSelectUser&letter=1
	  */
    public function select()
	{
		$req = \mvc::$req;
		$rules = $this->urlRulesToWhere($req);
		$style = !empty($req['style']) && $req['style'] == 'anychk'? 'anychk': '';
        if(substr($req['sql'],0,7)=='base64:'){
            $req['sql'] = base64_decode(substr($req['sql'],7));
        }
		if(!empty($req['sql']) && stripos($req['sql'], 'select') === 0 && !empty(\mvc::$cfg['db'][$req['db']]))
		{
			$req['sql'] = strtr($req['sql'], ['insert'=>'###','update'=>'###','delete'=>'###', 'drop'=>'###', 'truncate'=>'###', 'alert'=>'###']);
			$this->sdb = new \lib\db(\mvc::$cfg['db'][$req['db']]);
			$dataArr = $this->sdb->query($req['sql'])->fetchAll(\PDO::FETCH_ASSOC);
		}
		else if(!empty($req['data']))
		{
			$dataArr = json_decode(base64_decode(substr($req['data'],7)), true);
		}
		else
		{
			$dataArr = $this->pro->getSelect($req['table'], $rules);
		}
		$letterArr = [];
		if($req['letter'] != -1)
		{
			$sort = ['seq'=>[], 'letter'=>[], 'name'=>[]];
			$cnInitialLetter = include(\mvc::$cfg['mvcDir'].'/lib/cnInitialLetter.php');
			foreach($dataArr as &$v)
			{
				if(isset($v['letter']))
				{
					$v['letter'] = substr($v['letter'], 0, 1);
				}
				else if(preg_match('/^[0-9a-zA-Z]/', $v['name'], $match))
				{
					$v['letter'] = $match[0];
				}
				else
				{
					$first = mb_substr($v['name'], 0, 1);
					if(!empty($cnInitialLetter[$first])){
						$py = $cnInitialLetter[$first];
					}else{
						$py = pinyinFirst($first);
					}
					$v['letter'] = substr($py, 0, 1);
				}
				$v['letter'] = strtoupper($v['letter']);
				$sort['seq'][] = isset($v['seq'])? $v['seq']: 0;
				$sort['letter'][] = $v['letter'];
				$sort['name'][] = $v['name'];
				$letterArr[] = $v['letter'];
			}
			array_multisort($sort['seq'], SORT_DESC,$sort['letter'], SORT_ASC, $sort['name'], SORT_ASC, $dataArr);
			$letterArr = array_unique($letterArr);
			sort($letterArr);
		}
		\view::set('letterArr', $letterArr);
		\view::set('dataArr', $dataArr);
		\view::set('style', $style);
		\view::set('req', $req);
		\view::put();
    }
	
    /**
    * @method 区域&本地码 审核
    * @param string $ids 
    */
    public function codeAreaNumberCheck2($ids)
    {
        if($ids!=''){
            $res = (new \model\pro\codeRule())->codeAreaNumberCheck2($ids,true);
            $this->successJson($res);
        }
        $this->msgJson(lg('未知错误'));
    }
	
    /**
    * @method 区域&本地码 删除
    * @param string $ids 
    */
    public function codeAreaNumberDeleteRows($ids)
    {
        if($ids!=''){
            $res = (new \model\pro\codeRule())->codeAreaNumberDeleteRows($ids);
            $this->successJson();
        }
        $this->msgJson(lg('未知错误'));
    }
    
    
	
    /**
    * @method 生成条码
    * @param string $ids 
    */
    public function buildBarCode($ids)
    {
        if($ids!=''){
            $res = (new \model\pro\codeRule())->buildBarCode($ids);
            if($res){
                $this->successJson([$res]);
            }
        }
        $this->msgJson(lg('生成条码出现错误,请检测企业编码可使用次数'));
    }


	public function getPlmParamByInnum($innum)
	{
	    $io = new \model\io();
        $data = $io->plmParam($innum);
		$this->successJson($data);
	}

	public function getBomByInnum()
	{
		$req = \mvc::$req;
		$rules = $this->urlRulesToWhere($req);
		if(empty($rules['innum']) || empty($rules['cid']))
		    return $this->successJson([]);;
		$cate = makeOne(\model\pro\cate::class)->getRowByKey($rules['cid']);
		$io = new \model\io();
		$ioPost = [
		    "IV_VALUE"=>$cate['iv_value'],
			"IV_MAKTX"=>$rules['innum'],
			"IV_WERKS"=>$cate['iv_werks']
		];
		$data = $io->bom('sap/bom', $ioPost);
		$data = $data['ET_BOM_ITEM'];
		if(!empty($data))
		{
			$sort = [];
			foreach($data as $k=>&$v)
			{
			    $v['IMAKT_zh_cn'] =$v['IMAKT'];
			    $v['IMAKT_en'] = $v['IMAKT_zh_cn'];
			    preg_match_all("/[\x{4e00}-\x{9fa5}]+/u",$v['IMAKT_zh_cn'],$m);
			    if($m){
			        foreach($m[0] as $mv){
			            $en = $this->pro->getBomEnTxt($mv);
			            if(empty($en)){
    			            preg_match("/[a-z0-9]+".$mv."/i",$v['IMAKT_en'],$m2);
    			            if($m2){
    			                $en = $this->pro->getBomEnTxt($m2);
    			                $mv = $m2;
    			            }
			            }
			            if($en){
			                $v['IMAKT_en'] = str_replace($mv,' '.ucfirst($en).' ',$v['IMAKT_en']);
			            }
			        }
			    }
				$sort[$k] = $v['deliverydate'];
			}
			array_multisort($sort, SORT_DESC, $data);
		}
		$this->successJson($data);
	}


	//报表
	public function master()
	{
		$req = \mvc::$req;
		$master = new master();
		$mainkey = $req['mainkey'];
		$scof = [];
		$selftscof = [];
		if($mainkey == 'self'){
			$selftscof = $master->getSelfReport();
			\view::set('selftscof', $selftscof);
		}else{
			$scof = \mvc::$cfg['master'][$mainkey];	
			\view::set('scof', $scof);
		}
		\view::set('mainkey', $mainkey);
		\view::put();
	}

	public function exeMaster()
	{
		$req = \mvc::$req;
		$master = new master();
		$master->export($req['mainkey'], explode(',', $req['skey']), $req);
		$this->successJson([]);
	}

	function delMasterTpl()
	{
		$req = \mvc::$req;
		$master = new master();
		$master->delMasterTpl(explode(',', $req['ids']));
		$this->successJson([]);
	}

	//监听队列
    public function exeMasterSelf($options,$req)
    {
        ignore_user_abort(true);
		ini_set('memory_limit', \mvc::$cfg['export_memory_limit']);
		set_time_limit(\mvc::$cfg['export_time_limit']);
        //type:xlsx|xlsxzip|imgxlsx|imgzip
        $options = json_decode(base64_decode($options),true);
        parse_str(html_entity_decode($req), $req);
		//前置条件
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
			$options['numbers'] = $req['numbers'];
		}
		if(isset($req['keys'])){
			$rules['keys'] = explode(',',$req['keys']);
		}
        $pagesize = 2147483647;
        if($options['model']['hasmodel']){
            if($options['model']['modelCel']=='one'){
                $rules['modelsOne'] = 1;
            }else if($options['model']['modelCel']=='more'){
                $rules['modelsAll'] = 1;
            }else{
                $rules['modelsRows'] = 1;
            }
        }
        if($options['oe']['qty']>200) $options['oe']['qty'] = 200;
        $options['fac'] = ($options['fac']!='') ? explode(',',$options['fac']) : [];
		$rules['getSQL'] = true;
        $sql = $this->pro->list($rules,$req['filters'], 1, $pagesize, '', '','');
        $fields = "p.p_id";
	    $join = "\r\n ";
	    $sql = preg_replace('/SELECT\s.*\s+FROM/is',"SELECT ".$fields." FROM",$sql);
		$master = new master();
		if($options['act'] == 'reporttpl'){
			$data = ['mr_name'=>$options['mr_name'], 'mr_mt_id'=>(int)$options['mtids'], 'mr_sql'=>$sql];
			$master->setReportTpl($data);
			$this->successJson([]);
		}else if($options['act'] == 'export'){
			$master = new master();
			$master->export('self', '', ['sql'=>$sql, 'mtids'=>$options['mtids']]);
			$this->successJson([]);
		}
	}

	public function masAttaqtyList()
	{
		$req = \mvc::$req;
		//前置条件
		$rules = $this->urlRulesToWhere($req);
		if(isset($req['numbers'])){
			$rules['numbers'] = formatNums($req['numbers']);
			$rules['numlike'] = empty($req['numlike']) ? 0 : $req['numlike'];
		}
        $data = $this->pro->list($rules,$req['filters'], $req['page'], $req['rows'], $req['sidx'], $req['sord'],'p_outnum');
		if(!empty($data)){
			foreach($data['rows'] as &$row){
				$attaRow = $this->pro->getMasAttaqtyByPid($row['p_id']);
				if(!empty($attaRow)){
					foreach($attaRow as $field=>$value){
						$regi = substr($field,strrpos($field, '_')+1);
						if($regi!='' && is_numeric($regi)){
							$row['pa_'.$regi] = $value;
						}
					}
				}//$data['rows']
			}
		}
        $this->successJson($data);
	}

	public function editCellMasAttaqty()
    {
		$req = \mvc::$req;
        $id = $req['id'];
        $oper = $req['oper'];
        $field = $req['field'];
		if(isset($req['value']))
			$value = $req['value'];
 		else
			$value = $req[$field];
        if($oper=='edit'){
            $result = $this->pro->setMasAttaqty($id,$field,$value);
        }
    }
}