<?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()
    {
		$carmodel = new \model\carmodel();
		\view::set('proExpModelfields', $carmodel->proExpModelfields);
        \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);
		}
        $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 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 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']);
        \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($p_id)
    {
        $pack = new packing();
        if((int) $p_id > 0){
            $row = $pack->getRowByKey($p_id);
        }
        if(empty($row)){
           $row = [];
        }
        \view::set('item',$row);
		\view::put('pro/pack');
    }
    
    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 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);
		  \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 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  array  [选填] 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 = \mvc::$cfg['master'][$mainkey];
		\view::set('mainkey', $mainkey);
		\view::set('scof', $scof);
		\view::put();
	}

	public function exeMaster()
	{
		$req = \mvc::$req;
		$master = new master();
		$master->export($req['mainkey'], explode(',', $req['skey']), $req);
		$this->successJson([]);
	}
}