<?php
class Warehouse_InventoryBatchController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "warehouse/views/inventory/";
        $this->serviceClass = new Service_InventoryBatch();
    }

    public function listAction()
    {
        $holdStatus = Common_Status::holdStatus('auto');
        $status = Common_Status::inventoryBatchStatus('auto');
        $wh = Common_DataCache::getWarehouseSimple();
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $params = $this->_request->getParams();
            Common_Common::trim_blank($params);
            $operationType = isset($params['operationType']) ? $params['operationType'] : '';
            $operationCode = isset($params['operationCode']) ? $params['operationCode'] : '';
            if (!empty($operationCode)) {
                $params[$operationType] = $operationCode;
            }
            $condition = $this->serviceClass->getMatchFields($params);

            if ($params['customer_code'] != "") {
                $condition['customer_code'] = trim($params['customer_code']);
            }

            if ($params['wa_code'] != '') {
                $condition['wa_code'] = trim($params['wa_code']);
            }
            $productCondition=array();
            if ($operationType == 'goods_id'&&!empty($operationCode)){
                $productCondition['goods_id']=$operationCode;
            }
            if($params['product_sku']){
                $productCondition['product_sku_keyword']=$params['product_sku'];
            }
            if (!empty($productCondition)) {
                $product_array = Service_Product::getByCondition($productCondition, array('product_id', 'product_sku'));
                if ($product_array) {
                    $product_id_array = array();
                    foreach ($product_array as $row) {
                        $product_id_array[] = (int) $row['product_id'];
                    }
                    $condition['product_id_array'] = $product_id_array;
                }else{
                    $condition['product_id_array'] = array('-1');
                }
            }
            $count = $this->serviceClass->getLeftJoinByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields = array(
                    'lc_code',
                    'product_barcode',
                    'reference_no',
                    'warehouse_id',
                    'receiving_code',
                    'ib_status',
                    'ib_hold_status',
                    'ib_quantity',
                    'ib_fifo_time',
                    'ib_update_time',
                    'ib_id',
                    'product_id',
                    'hs_serial_no',
                    'batch_goods_id'
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getLeftJoinByCondition($condition, $showFields, $pageSize, $page, array('ib_id desc'));
                foreach ($rows as &$r) {
                    $product = Service_Product::getByField($r['E2'], 'product_id', 'goods_id');
                    $r['goods_id'] = $product['goods_id'];
                }
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['holdStatus'] = $holdStatus;
                $return['status'] = $status;
                $return['warehouse'] = $wh;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->status = $status;
        $this->view->warehouseArea = Common_DataCache::getWarehouseArea();
        $this->view->locationType = Common_DataCache::getLocationType();
        echo Ec::renderTpl($this->tplDirectory . "inventory_batch_index.tpl", 'layout');
    }

    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage' => array('Fail.')
        );

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(

                'ib_id' => '',
                'lc_code' => '',
                'product_barcode' => '',
                'reference_no' => '',
                'warehouse_id' => '',
                'receiving_code' => '',
                'ib_status' => '',
                'ib_hold_status' => '',
                'ib_quantity' => '',
                'ib_fifo_time' => '',
                'ib_update_time' => '',
            );
            $row = $this->serviceClass->getMatchEditFields($params, $row);
            $paramId = $row['ib_id'];
            if (!empty($row['ib_id'])) {
                unset($row['ib_id']);
            }
            $errorArr = $this->serviceClass->validator($row);

            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message' => '',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }

            if (!empty($paramId)) {
                $result = $this->serviceClass->update($row, $paramId);
            } else {
                $result = $this->serviceClass->add($row);
            }
            if ($result) {
                $return['state'] = 1;
                $return['message'] = array('Success.');
            }

        }
        die(Zend_Json::encode($return));
    }

    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'ib_id')) {
            $rows = $this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }
    
    /**
     * 调库存
     * @author solar
     */
    public function adjustAction() {
    	$response = array('state'=>1);
    	$ib_id = intval($this->_request->getParam('ib_id'));
    	if(empty($ib_id)) exit(Zend_Json::encode(array('state'=>0, 'message'=>'请输入批次库存ID')));
    	$new_quantity = trim($this->_request->getParam('new_quantity'));
    	if($new_quantity === '') exit(Zend_Json::encode(array('state'=>0, 'message'=>'请输入新库存')));
    	if(!preg_match("/^\d+$/", $new_quantity)) exit(Zend_Json::encode(array('state'=>0, 'message'=>'库存只能是整数')));
    	$reason = trim($this->_request->getParam('reason'));
    	if(empty($reason)) exit(Zend_Json::encode(array('state'=>0, 'message'=>'请输入调整库存的原因')));
    	$inventoryProcess = new Service_InventoryProcess();
    	$result = $inventoryProcess->adjustInventory($ib_id, $new_quantity, $reason);
    	if($result !== true) exit(Zend_Json::encode(array('state'=>0, 'message'=>$result)));
    	$response['ib_id'] = $ib_id;
    	$response['quantity'] = $new_quantity;
    	exit(Zend_Json::encode($response));
    }
    
    /**
     * 移货架
     * @author solar
     */
    public function moveAction() {
    	$ib_id = intval($this->_request->getParam('ib_id'));
    	if(empty($ib_id)) exit(Zend_Json::encode(array('state'=>0, 'message'=>'请输入批次库存ID')));
    	$new_location = $this->_request->getParam('new_location');
    	if(empty($new_location)) exit(Zend_Json::encode(array('state'=>0, 'message'=>'请输入目标货架')));
    	$move_quantity = trim($this->_request->getParam('move_quantity'));
    	if($move_quantity === '') exit(Zend_Json::encode(array('state'=>0, 'message'=>'请输入要移动的数量')));
    	if(!preg_match("/^\d+$/", $move_quantity)) exit(Zend_Json::encode(array('state'=>0, 'message'=>'移动数量只能是整数')));
    	$move_quantity = intval($move_quantity);
    	if($move_quantity <= 0) exit(Zend_Json::encode(array('state'=>0, 'message'=>'移动数量必须大于0')));
    	$reason = trim($this->_request->getParam('m_reason'));
    	if(empty($reason)) exit(Zend_Json::encode(array('state'=>0, 'message'=>'请输入移动货架的原因')));
    	//操作
    	$inventoryProcess = new Service_InventoryProcess();
    	$result = $inventoryProcess->moveLocation($ib_id, $new_location, $move_quantity, $reason);
    	if($result !== true) exit(Zend_Json::encode(array('state'=>0, 'message'=>$result)));
    	exit(Zend_Json::encode(array('state'=>1)));
    }
	
   /*colin 导出批次库存*/
   public function exportAction(){
		$userAuth = new Zend_Session_Namespace('userAuthorization');
        $ibIdArr = $this->_request->getParam('ibId','');
        $exportType = $this->_request->getParam("exportType","");

        if($exportType=="1"){

            header('Pragma:public');
			header("Content-Type: application/vnd.ms-excel; charset=UTF-8");  
            header("Content-Disposition:inline;filename=inventoryBatch".date('YmdHis').".xls");
			header("Content-Transfer-Encoding: binary ");
			echo "<meta http-equiv='content-type' content='application/ms-excel; charset=UTF-8'/>";
            echo "<table border='1'>";
            echo "<tr>";
			echo "<td>客户代码</td>";
            echo "<td>产品SKU</td>";
			echo "<td>产品条码</td>";
			echo "<td>产品名称</td>";           
			echo "<td>货架号</td>";
            echo "<td>数量</td>";
            echo "<td>海关备案序号</td>";
            echo "<td>批次料件号</td>";
            echo "<td>客户参考号</td>";
            echo "<td>收货单号</td>";
            echo "<td>上架时间</td>";
            echo "<td>更新时间</td>";
            echo "</tr>";

            foreach($ibIdArr as $val){
                if($val=="") continue;
                $ib = Service_InventoryBatch::getByField($val,"ib_id","*");
                if(substr($ib['receiving_code'],0,3)=="SWO"){
                    $inventoryBatchSerial = Service_InventoryBatchSerial::getByCondition(array('ib_id'=>$val),"*");
                    if(!empty($inventoryBatchSerial)){
                        foreach($inventoryBatchSerial as $ibs){
                            echo "<tr>";
                            $p = Service_Product::getByField($ib['product_id'],"product_id","*");
                            echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['customer_code']."</td>";
                            echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['product_sku']."</td>";
                            echo "<td style='vnd.ms-excel.numberformat:@;'>".$ib['product_barcode']."</td>";
                            echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['product_title']."</td>";
                            echo "<td style='text-align:left;'>".$ib['lc_code']."</td>";
                            echo "<td>".$ibs['ibs_quantity']."</td>";
                            echo "<td>".$ibs['hs_serial_no']."</td>";
                            echo "<td>".$ibs['batch_goods_id']."</td>";
                            $r = Service_Receiving::getByField($ib['receiving_code'],"receiving_code","*");
                            echo "<td style='vnd.ms-excel.numberformat:@'>".$r['reference_no']."</td>";
                            echo "<td style='text-align:left;'>".$ib['receiving_code']."</td>";
                            echo "<td>".$ib['ib_fifo_time']."</td>";
                            echo "<td>".$ib['ib_update_time']."</td>";
                            echo "</tr>";
                        }
                    }else{
                        echo "<tr>";
                        $p = Service_Product::getByField($ib['product_id'],"product_id","*");
                        echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['customer_code']."</td>";
                        echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['product_sku']."</td>";
                        echo "<td style='vnd.ms-excel.numberformat:@;'>".$ib['product_barcode']."</td>";
                        echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['product_title']."</td>";
                        echo "<td style='text-align:left;'>".$ib['lc_code']."</td>";
                        echo "<td>".$ib['ib_quantity']."</td>";
                        echo "<td>".$ib['hs_serial_no']."</td>";
                        echo "<td>".$ib['batch_goods_id']."</td>";
                        $r = Service_Receiving::getByField($ib['receiving_code'],"receiving_code","*");
                        echo "<td style='vnd.ms-excel.numberformat:@'>".$r['reference_no']."</td>";
                        echo "<td style='text-align:left;'>".$ib['receiving_code']."</td>";
                        echo "<td>".$ib['ib_fifo_time']."</td>";
                        echo "<td>".$ib['ib_update_time']."</td>";
                        echo "</tr>";
                    }
                }else{
                    echo "<tr>";
                    $p = Service_Product::getByField($ib['product_id'],"product_id","*");
                    echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['customer_code']."</td>";
                    echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['product_sku']."</td>";
                    echo "<td style='vnd.ms-excel.numberformat:@;'>".$ib['product_barcode']."</td>";
                    echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['product_title']."</td>";
                    echo "<td style='text-align:left;'>".$ib['lc_code']."</td>";
                    echo "<td>".$ib['ib_quantity']."</td>";
                    echo "<td>".$ib['hs_serial_no']."</td>";
                    echo "<td>".$ib['batch_goods_id']."</td>";
                    $r = Service_Receiving::getByField($ib['receiving_code'],"receiving_code","*");
                    echo "<td style='vnd.ms-excel.numberformat:@'>".$r['reference_no']."</td>";
                    echo "<td style='text-align:left;'>".$ib['receiving_code']."</td>";
                    echo "<td>".$ib['ib_fifo_time']."</td>";
                    echo "<td>".$ib['ib_update_time']."</td>";
                    echo "</tr>";
                }
            }
            echo "</table>";

        }else{

			
			$params = $this->_request->getParams();
			Common_Common::trim_blank($params);
			
            $operationType = isset($params['operationType']) ? $params['operationType'] : '';
            $operationCode = isset($params['operationCode']) ? $params['operationCode'] : '';
            if (!empty($operationCode)) {
                $params[$operationType] = $operationCode;
            }
              $productCondition=array();
            if ($operationType == 'goods_id'&&!empty($operationCode)){
                $productCondition['goods_id']=$operationCode;
            }
            if($params['product_sku']){
                $productCondition['product_sku_keyword']=$params['product_sku'];
            }
            $condition = $this->serviceClass->getMatchFields($params);
            if($params['customer_code']!=""){
                $condition['customer_code'] = trim($params['customer_code']);
            }
            if($params['wa_code']!=""){
                $condition['wa_code'] = trim($params['wa_code']);
            }

			if(!empty($productCondition)){
				   $product_array = Service_Product::getByCondition($productCondition,array('product_id','product_sku'));
					if($product_array){
						$product_id_array = array();
						foreach($product_array as $row){
							$product_id_array[] = (int)$row['product_id'];
						}
						$condition['product_id_array'] = $product_id_array;
						
                                        }else{
                                            $condition['product_id_array'] = array('-1');
                                        }
                                        
			}
			$condition['warehouse_id']	= $userAuth->warehouseId;
            $count = $this->serviceClass->getLeftJoinByCondition($condition, 'count(*)');
            if($count){

                header('Pragma:public');
				header("Content-Type: application/vnd.ms-excel; charset=UTF-8");  
				header("Content-Disposition:inline;filename=inventoryBatch".date('YmdHis').".xls");
				header("Content-Transfer-Encoding: binary ");
				echo "<meta http-equiv='content-type' content='application/ms-excel; charset=UTF-8'/>";
                echo "<table border='1'>";
                echo "<tr>";
				echo "<td>客户代码</td>";
                echo "<td>产品SKU</td>";
				echo "<td>产品条码</td>";
                echo "<td>产品名称</td>";
				echo "<td>货架号</td>";
                echo "<td>数量</td>";
                echo "<td>海关备案序号</td>";
                echo "<td>批次料件号</td>";
                echo "<td>客户参考号</td>";
                echo "<td>收货单号</td>";
                echo "<td>上架时间</td>";

                echo "<td>更新时间</td>";
                echo "</tr>";

                $rows = $this->serviceClass->getLeftJoinByCondition($condition, "*",0,0,array('ib_id desc'));
                foreach($rows as $key=>$val){
                    if(substr($val['receiving_code'],0,3)=="SWO"){
                        $inventoryBatchSerial = Service_InventoryBatchSerial::getByCondition(array('ib_id'=>$val['ib_id']),"*");
                        if(!empty($inventoryBatchSerial)){
                            foreach($inventoryBatchSerial as $ibs){
                                echo "<tr>";
                                $p = Service_Product::getByField($val['product_id'],"product_id","*");
                                echo "<td>".$p['customer_code']."</td>";
                                echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['product_sku']."</td>";
                                echo "<td style='vnd.ms-excel.numberformat:@;'>".$val['product_barcode']."</td>";
                                echo "<td>".$p['product_title']."</td>";
                                echo "<td>".$val['lc_code']."</td>";
                                echo "<td>".$ibs['ibs_quantity']."</td>";
                                echo "<td>".$ibs['hs_serial_no']."</td>";
                                echo "<td>".$ibs['batch_goods_id']."</td>";
                                $r = Service_Receiving::getByField($val['receiving_code'],"receiving_code","*");
                                echo "<td style='vnd.ms-excel.numberformat:@;'>".$r['reference_no']."</td>";
                                echo "<td style='text-align:left;'>".$val['receiving_code']."</td>";
                                echo "<td>".$val['ib_fifo_time']."</td>";
                                echo "<td>".$val['ib_update_time']."</td>";
                                echo "</tr>";
                            }
                        }else{
                            echo "<tr>";
                            $p = Service_Product::getByField($val['product_id'],"product_id","*");
                            echo "<td>".$p['customer_code']."</td>";
                            echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['product_sku']."</td>";
                            echo "<td style='vnd.ms-excel.numberformat:@;'>".$val['product_barcode']."</td>";
                            echo "<td>".$p['product_title']."</td>";
                            echo "<td>".$val['lc_code']."</td>";
                            echo "<td>".$val['ib_quantity']."</td>";
                            echo "<td>".$val['hs_serial_no']."</td>";
                            echo "<td>".$val['batch_goods_id']."</td>";
                            $r = Service_Receiving::getByField($val['receiving_code'],"receiving_code","*");
                            echo "<td style='vnd.ms-excel.numberformat:@;'>".$r['reference_no']."</td>";
                            echo "<td style='text-align:left;'>".$val['receiving_code']."</td>";
                            echo "<td>".$val['ib_fifo_time']."</td>";
                            echo "<td>".$val['ib_update_time']."</td>";
                            echo "</tr>";
                        }
                    }else{
                        echo "<tr>";
                        $p = Service_Product::getByField($val['product_id'],"product_id","*");
                        echo "<td>".$p['customer_code']."</td>";
                        echo "<td style='vnd.ms-excel.numberformat:@;'>".$p['product_sku']."</td>";
                        echo "<td style='vnd.ms-excel.numberformat:@;'>".$val['product_barcode']."</td>";
                        echo "<td>".$p['product_title']."</td>";
                        echo "<td>".$val['lc_code']."</td>";
                        echo "<td>".$val['ib_quantity']."</td>";
                        echo "<td>".$val['hs_serial_no']."</td>";
                        echo "<td>".$val['batch_goods_id']."</td>";
                        $r = Service_Receiving::getByField($val['receiving_code'],"receiving_code","*");
                        echo "<td style='vnd.ms-excel.numberformat:@;'>".$r['reference_no']."</td>";
                        echo "<td style='text-align:left;'>".$val['receiving_code']."</td>";
                        echo "<td>".$val['ib_fifo_time']."</td>";
                        echo "<td>".$val['ib_update_time']."</td>";
                        echo "</tr>";
                    }
                }
            }
            echo "</table>";
        }

    }	
	

    //通过customer_code导出批次库存
    public function exportForCustomerAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');

        $fileName = $_FILES['uploadXLS']['name'];
        $filePath = $_FILES['uploadXLS']['tmp_name'];
        $pathinfo = pathinfo($fileName);
        if (!isset($pathinfo["extension"]) && $pathinfo["extension"] != "xls") {
            echo '<script>window.parent.alertTip("请选择xls文件");</script>';
            exit;
        }

        $fileData = Common_Upload::readEXCELAndType($filePath);
        $fileData = $fileData['value'];

        $isTemplate = array_shift($fileData);
        if($isTemplate[0] != '客户代码'){
            echo '<script>window.parent.alertTip("请选择合适的模板");</script>';
            exit;
        }

        $condition['customer_codes'] = array_map('array_shift', $fileData);
        $showFields = array(
            'customer_code',
            'product.product_sku',
            'product_barcode',
            'product.product_title',
            'lc_code',
            'ib_quantity',
            'receiving.reference_no',
            'receiving_code',
            'ib_fifo_time',
            'ib_update_time',
        );
        $rows = $this->serviceClass->getLeftJoinByCondition($condition, $showFields, false, false, array('customer_code'));

        $filename    = 'inventoryBatchForCustomer' . date('YmdHis').'.xls';
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';
        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体');
        $table->setActiveSheetIndex(0);
        $table->setActiveSheetIndex(0)->setTitle("产品批次库存列表");
        $objActSheet=$table->setActiveSheetIndex(0);

        $objActSheet->setCellValue('A1','客户代码');
        $objActSheet->setCellValue('B1','产品SKU');
        $objActSheet->setCellValue('C1','产品条码');
        $objActSheet->setCellValue('D1','产品名称');
        $objActSheet->setCellValue('E1','货架号');
        $objActSheet->setCellValue('F1','数量');
        $objActSheet->setCellValue("G1","客户参考号");
        $objActSheet->setCellValue("H1","收货单号");
        $objActSheet->setCellValue("I1","上架时间");
        $objActSheet->setCellValue("J1","更新时间");

        foreach ($rows as $key => $val) {
            $rowNum = $key+2;
            $objActSheet->setCellValue('A'.$rowNum, $val['customer_code']);
            $objActSheet->setCellValueExplicit('B'.$rowNum, $val['product_sku'], PHPExcel_Cell_DataType::TYPE_STRING);
            $objActSheet->setCellValueExplicit('C'.$rowNum, $val['product_barcode'], PHPExcel_Cell_DataType::TYPE_STRING);
            $objActSheet->setCellValue('D'.$rowNum, $val['product_title']);
            $objActSheet->setCellValueExplicit('E'.$rowNum, $val['lc_code'], PHPExcel_Cell_DataType::TYPE_STRING);
            $objActSheet->setCellValue('F'.$rowNum, $val['ib_quantity']);
            $objActSheet->setCellValueExplicit('G'.$rowNum, $val['reference_no'], PHPExcel_Cell_DataType::TYPE_STRING);
            $objActSheet->setCellValueExplicit('H'.$rowNum, $val['receiving_code'], PHPExcel_Cell_DataType::TYPE_STRING);
            $objActSheet->setCellValue('I'.$rowNum, $val['ib_fifo_time']);
            $objActSheet->setCellValue('J'.$rowNum, $val['ib_update_time']);
        }
        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel5');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename=productInventory".date('YmdHis').'.xls');
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');
        exit;
    }

    //下载导入模板
    public function exportForCustomerTempleteAction()
    {
        $fullPath = APPLICATION_PATH."/../data/file/inventoryBatchForCustomer.xls";
        $filename = basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header="Content-Disposition: attachment; filename=".$filename.";";
        header($header);
        //  header("Content-Transfer-Encoding: binary");
        //  header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }

    public function batchMoveAction(){
        $ib_id = $this->_request->getParam('idArr','');
        $batch_new_location	 = $this->_request->getParam("batch_new_location","");
        if(empty($batch_new_location)) exit(Zend_Json::encode(array('state'=>0, 'message'=>'请输入目标货架')));
        $b_m_reason = $this->_request->getParam("b_m_reason","");
        if(empty($b_m_reason)) exit(Zend_Json::encode(array('state'=>0, 'message'=>'请输入移动货架的原因')));
        $IbArr = explode("|",$ib_id);
        $inventoryProcess = new Service_InventoryProcess();
        $ret = array('state'=>1,'data'=>array());
        $total = 0;
        $success = 0;
        $failure = 0;
        foreach($IbArr as $id){
            if($id=="") continue;
            $inventoryRow = Service_InventoryBatch::getByField($id,'ib_id',"*");
            $result = $inventoryProcess->moveLocation($id, $batch_new_location, $inventoryRow['ib_quantity'], $b_m_reason);
            $tips = "货架号:".$inventoryRow['lc_code']."产品代码:".$inventoryRow['product_barcode'];
            if($result !== true){
                $message = $tips." 移货架失败-->".$result;
                $ret['data'][] = array('state'=>0, 'message'=>$message);
                $failure+=1;
            }else{
                $message = $tips." 移货架成功!";
                //exit(Zend_Json::encode(array('state'=>0, 'message'=>$message)));
                $ret['data'][] = array('state'=>1, 'message'=>$message);
                $success+=1;
            }
            $total+=1;
            //exit(Zend_Json::encode(array('state'=>1)));
        }
        $ret['total'] = $total;
        $ret['success'] = $success;
        $ret['failure'] = $failure;
        exit(Zend_Json::encode($ret));
    }

    public function importHsSerialAction(){
        $result = array("ask"=>1,"message"=>"",'error'=>array(),'data'=>array());
        $xlsData = Service_Product::getXLSData($_FILES,'filename');
        //var_dump($xlsData);
        //exit;
        if(count($xlsData[0])!=5||($xlsData[0][0]!="入库单号"||strtoupper($xlsData[0][1])!="SKU"||$xlsData[0][2]!="批次料件号"||$xlsData[0][3]!="海关备案序号"||$xlsData[0][4]!="数量")){
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照 入库单号,sku,批次料件号,海关备案序号,数量 排列!";
            die(json_encode($result));
        }
        foreach($xlsData as $key=>$value){
            if($key==0) continue;
            $existError = 0;
            $productSku = $value[1];
            $hsSerialNo = $value[3];
            $receivingCode = $value[0];
            $batchGoodsId = $value[2];
            $quantity = $value[4];
            $resultData = array(
                'receiving_code'=>$receivingCode,
                'product_sku'=>$productSku,
                'batch_goods_id'=>$batchGoodsId,
                'hs_serial_no'=>$hsSerialNo,
                'quantity'=>$quantity,
                'ok'=>0
            );
            if($receivingCode==""){
                $existError = 1;
                $resultData['message'] .= "入库单号为空;";
            }
            if($productSku==""){
                $existError = 1;
                $resultData['message'] .= "SKU为空;";
            }
            if($batchGoodsId==""){
                $existError = 1;
                $resultData['message'] .= "批次料件号为空;";
            }
            if($quantity==""){
                $existError = 1;
                $resultData['message'] .= "数量为空;";
            }
            /*if($hsSerialNo==""){
                $existError = 1;
                $resultData['message'] .= "海关备案序号为空;";
            }*/
            $receivingRow = Service_Receiving::getByField($receivingCode,'receiving_code',"*");
            if(empty($receivingRow)){
                $existError = 1;
                $resultData['message'] .= "入库单号[".$receivingCode."]为不存在";
            }
            if($existError) {
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $inventoryBatchList = Service_InventoryBatch::getLeftJoinByCondition(array('receiving_code'=>$receivingCode,'product_sku'=>$productSku,'ib_quantity'=>$quantity,'empty_serial_or_batch'=>1),"*");
            if(!empty($inventoryBatchList)){
                foreach($inventoryBatchList as $ib){
                    $updateIb = array(
                        'hs_serial_no'=>$hsSerialNo,
                        'batch_goods_id'=>$batchGoodsId,
                    );
                    Service_InventoryBatch::update($updateIb,$ib['ib_id'],"ib_id");
                }
                $resultData['ok'] = 1;
                $resultData['message'] = "数据更新成功!";
            }else{
                $resultData['message'] .= "入库单号[".$receivingCode."]不存在SKU[".$productSku."]的产品或数量不相等或是已导入！请核实!";
            }

            $result['data'][] = $resultData;
        }
        die(json_encode($result));
    }

}
