<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 15-6-8
 * Time: 上午10:24
 * To change this template use File | Settings | File Templates.
 */
class Service_SwapOrderProcess
{
    //private $_order = array();
    //private $_ordersCode = '';
    //private $_order_weight = 0;
    private $_warehouseId = 0;
    private $_picking = array();
    private $_pickingId = 0;
    private $_pickingCode = '';
    private $_pickerId = '0'; //配货员
    //private $_printType = '0'; //下架类型
    //private $_lc_code_arr = array();
    protected $_QcCode = null;
    protected $_QcOrder = null;
    protected $_asnItem = null;
    protected $_errorArr = array();
    protected $_params = array();
    protected $_userId = 0;
    //protected $_warehouseId = 0;
    protected $_date = '';

    public function offShelfTransaction($swo_id,$picker_id){
        $result = array("ask" => 0, "message" => "");
        $errors = array();
        $db = Service_QualityControl::getModelInstance()->getAdapter();
        $swapOrderRow = Service_SwapOrder::getByField($swo_id,'swo_id',"*");
        $this->_warehouseId = $swapOrderRow['warehouse_id'];
        $this->_pickerId = $picker_id;
        $db->beginTransaction();
        try{
            $pickCode = Common_GetNumbers::getCode('picking', $this->_warehouseId, 'PL'); // 配货号

            $this->_userAuth = new Zend_Session_Namespace('userAuthorization');
            $this->_picking = array(
                'warehouse_id' => $this->_warehouseId,
                'picking_code' => $pickCode,
                'picker_id' => $this->_pickerId,
                'creater_id' => isset($this->_userAuth->userId) ? $this->_userAuth->userId : '0',
                'picking_order_cnt' => '0',
                'picking_lc_cnt' => '0',
                'picking_item_cnt' => '0',
                'picking_status' => '0',
                'is_assign' => $this->_pickerId != '0' ? 1 : 0,
                'picking_type' => '1',
                'picking_add_time' => date("Y-m-d H:i:s"),
                'picking_update_time' => date("Y-m-d H:i:s"),
                'picking_model'=>'1',
            );
            if (!$this->_pickingId = Service_Picking::add($this->_picking)) { //配货单主键
                throw new Exception('Inner Error11', 50000);
            }
            $this->_pickingCode = $pickCode;

            $status = 5;
            $date = date('Y-m-d H:i:s');

            if ($swapOrderRow['swo_status'] != '2') {
                throw new Exception("易货单[".$swapOrderRow['swo_code']."]不是确认状态", 50003);
            }

            $row = array(
                'swo_status' => 3, //下架状态更新
                'last_update_time' => $date
            );
            Service_SwapOrder::update($row,$swo_id,"swo_id");
            $swapOrderDetail = Service_SwapOrderDetail::getByCondition(array('swo_code'=>$swapOrderRow['swo_code']),"*");
            $orderProductCount = 0; //产品数量
            foreach($swapOrderDetail as $p){
                $updateSwd = array(
                    'swod_status'=>3,
                    'last_update_time'=>date("Y-m-d H:i:s"),
                );
                Service_SwapOrderDetail::update($updateSwd,$p['swod_id'],"swod_id");
                $product = Service_Product::getByField($p['product_id'],"product_id","*");
                $toProduct = Service_Product::getByField($p['to_product_id'],"product_id","*");
                $orderProductCount += $p['quantity'];
                $con = array(
                    'product_id' => $p['product_id'],
                    'warehouse_id' => $swapOrderRow['warehouse_id'],
                    'ib_status' => '1',
                    'ib_hold_status' => '0',
                );
                $batchs = Service_InventoryBatch::getByCondition($con, '*', 0, 0, 'ib_id asc'); //先进先出
                if (empty($batchs)) {
                    throw new Exception('[' . $product['product_barcode'] . ']insufficient stock 001',50019);
                }
                foreach ($batchs as $batch) {
                    //$this->_lc_code_arr[$batch['lc_code']] = $batch['lc_code'];
                    $con1 = array(
                        'ib_id' => $batch['ib_id'], //一个货架多个产品无法用货架号去判断，用id吧
                    );
                    $sumQty = Service_InventoryBatchOutbound::getByCondition($con1, 'sum(ibo_quantity) as sum_qty'); //??
                    if (empty($sumQty)) {
                        $sumQty = 0;
                    } else {
                        $sumQty = $sumQty[0]['sum_qty'];
                    }
                    if (!$batch['ib_status'] || $batch['ib_hold_status'] != '0') {
                        continue;
                    }
                    $batch['ib_quantity'] -= $sumQty; //批次可用数
                    if($batch['hs_serial_no']==""&&substr($batch['receiving_code'],0,3)=="BHR"){
                        throw new Exception('批次库存还没导入海关备案序号!', 54000);
                    }

                    if ($p['quantity'] <= $batch['ib_quantity']) { // 订单产品数量小于等于批次可用数
                        $qty = $p['quantity'];
                        // 插入一条产品出库核销记录
                        $boundRow = array(
                            'lc_code' => $batch['lc_code'],
                            'warehouse_id' => $swapOrderRow['warehouse_id'],
                            'reference_no' => $swapOrderRow['swo_code'],
                            'application_code' => 'pickup',
                            'ibo_quantity' => $qty,
                            'ib_id' => $batch['ib_id'],
                            'ibo_add_time' => date('Y-m-d H:i:s')
                        );
                        if (!$ibo_id = Service_InventoryBatchOutbound::add($boundRow)) {
                            throw new Exception('Inner Error', 50011);
                        }
                        $boundLogRow = array(
                            'lc_code' => $batch['lc_code'],
                            'ibo_id' => $ibo_id,
                            'ib_id' => $batch['ib_id'],
                            'reference_no' => $swapOrderRow['swo_code'],
                            'application_code' => 'pickup',
                            'ibol_quantity' => $qty,
                            'user_id' => '0',
                            'ibol_ip' => Common_Common::getIP(),
                            'ibol_add_time' => date('Y-m-d H:i:s'),
                            'ibol_note' => $batch['product_barcode']
                        );
                        if (!Service_InventoryBatchOutboundLog::add($boundLogRow)) {
                            throw new Exception('Inner Error', 50012);
                        }
                        $batchLog = array(
                            'lc_code' => $batch['lc_code'],
                            'product_id' => $p['product_id'],
                            'product_barcode' => $product['product_barcode'],
                            'supplier_id' => '',
                            'warehouse_id' => $swapOrderRow['warehouse_id'],
                            'ib_id' => $batch['ib_id'],
                            'receiving_code' => '',
                            'reference_no' => $swapOrderRow['swo_code'],
                            'application_code' => '',
                            'ibl_note' => $batch['product_barcode'],
                            'ibl_quantity_before' => $batch['ib_quantity'],
                            'ibl_quantity_after' => $batch['ib_quantity'],
                            'user_id' => '0',
                            'ibl_ip' => Common_Common::getIP(),
                            'ibl_add_time' => date('Y-m-d H:i:s')
                        );

                        if (!Service_InventoryBatchLog::add($batchLog)) { //批次日志 ? 好像此时没动到批次哦
                            throw new Exception('Inner Error', 50013);
                        }

                        $pickingDetailRow = array(
                            'picking_id' => $this->_pickingId,
                            'picking_code' => $this->_pickingCode,
                            'order_id' => $swapOrderRow['swo_id'],
                            'order_code' => $swapOrderRow['swo_code'],
                            'pd_status' => '0',
                            'op_id' => $p['swod_id'],
                            'pd_quantity' => $qty,
                            'ibo_id' => $ibo_id,
                            'product_id' => $p['product_id'],
                            'product_barcode' => $product['product_barcode'],
                            'ib_id' => $batch['ib_id'],
                            'lc_code' => $batch['lc_code'],
                            'pd_add_time' => date('Y-m-d H:i:s')
                        );
                        if (!$pd_id = Service_PickingDetail::add($pickingDetailRow)) { //配货明细
                            throw new Exception('Inner Error', 50014);
                        }
                        if(substr($batch['receiving_code'],0,3)=="SWO"){
                            $this->dealSerial($con1,$toProduct,$qty,$batch,$swapOrderRow['swo_code']);
                        }else{
                            $inventoryBatchSerialRow = array(
                                'product_id' => $toProduct['product_id'],
                                'product_barcode' => $toProduct['product_barcode'],
                                'goods_id' => $toProduct['goods_id'],
                                'customer_code' => $toProduct['customer_code'],
                                'hs_serial_no'=>$batch['hs_serial_no'],
                                'swo_code'=>$swapOrderRow['swo_code'],
                                'ibs_quantity'=>$qty,
                                'ibs_add_time'=>date("Y-m-d H:i:s"),
                                'from_ib_id' => $batch['ib_id'],
                                'batch_goods_id'=>$batch['batch_goods_id'],
                            );
                            Service_InventoryBatchSerial::add($inventoryBatchSerialRow);
                        }
                        $p['quantity'] = 0;
                        break;
                    } else {
                        $qty = $batch['ib_quantity'];
                        if ($qty <= 0) {
                            continue;
                        }
                        // 插入一条产品出库核销记录
                        $boundRow = array(
                            'lc_code' => $batch['lc_code'],
                            'warehouse_id' => $swapOrderRow['warehouse_id'],
                            'reference_no' => $swapOrderRow['swo_code'],
                            'application_code' => 'pickup',
                            'ibo_quantity' => $qty,
                            'ib_id' => $batch['ib_id'],
                            'ibo_add_time' => date('Y-m-d H:i:s')
                        );
                        if (!$ibo_id = Service_InventoryBatchOutbound::add($boundRow)) {
                            throw new Exception('Inner Error', 50015);
                        }

                        $boundLogRow = array(
                            'lc_code' => $batch['lc_code'],
                            'ibo_id' => $ibo_id,
                            'ib_id' => $batch['ib_id'],
                            'reference_no' => $swapOrderRow['swo_code'],
                            'application_code' => 'pickup',
                            'ibol_quantity' => $qty,
                            'user_id' => '0',
                            'ibol_ip' => Common_Common::getIP(),
                            'ibol_add_time' => date('Y-m-d H:i:s'),
                            'ibol_note' => $batch['product_barcode']
                        );
                        if (!Service_InventoryBatchOutboundLog::add($boundLogRow)) {
                            throw new Exception('Inner Error', 50016);
                        }
                        $batchLog = array(
                            'lc_code' => $batch['lc_code'],
                            'product_id' => $p['product_id'],
                            'product_barcode' => $product['product_barcode'],
                            'supplier_id' => '',
                            'warehouse_id' => $swapOrderRow['warehouse_id'],
                            'ib_id' => $batch['ib_id'],
                            'receiving_code' => '',
                            'reference_no' => $swapOrderRow['swo_code'],
                            'application_code' => 'pickup',
                            'ibl_note' => $batch['product_barcode'],
                            'ibl_quantity_before' => $batch['ib_quantity'],
                            'ibl_quantity_after' => $batch['ib_quantity'],
                            'user_id' => '0',
                            'ibl_ip' => Common_Common::getIP(),
                            'ibl_add_time' => date('Y-m-d H:i:s')
                        );
                        if (!Service_InventoryBatchLog::add($batchLog)) {
                            throw new Exception('Inner Error', 50017);
                        }

                        $pickingDetailRow = array(
                            'picking_id' => $this->_pickingId,
                            'picking_code' => $this->_pickingCode,
                            'order_id' => $swapOrderRow['swo_id'],
                            'order_code' => $swapOrderRow['swo_code'],
                            'pd_status' => '0',
                            'op_id' => $p['swod_id'],
                            'pd_quantity' => $qty,
                            'ibo_id' => $ibo_id,
                            'product_id' => $p['product_id'],
                            'product_barcode' => $product['product_barcode'],
                            'ib_id' => $batch['ib_id'],
                            'lc_code' => $batch['lc_code'],
                            'pd_add_time' => date('Y-m-d H:i:s')
                        );
                        if (!$pd_id = Service_PickingDetail::add($pickingDetailRow)) { //配货明细
                            throw new Exception('Inner Error', 50018);
                        }
                        if(substr($batch['receiving_code'],0,3)=="SWO"){
                            $this->dealSerial($con1,$toProduct,$qty,$batch,$swapOrderRow['swo_code']);
                        }else{
                            $inventoryBatchSerialRow = array(
                                'product_id' => $toProduct['product_id'],
                                'product_barcode' => $toProduct['product_barcode'],
                                'goods_id' => $toProduct['goods_id'],
                                'customer_code' => $toProduct['customer_code'],
                                'hs_serial_no'=>$batch['hs_serial_no'],
                                'swo_code'=>$swapOrderRow['swo_code'],
                                'ibs_quantity'=>$qty,
                                'ibs_add_time'=>date("Y-m-d H:i:s"),
                                'from_ib_id' => $batch['ib_id'],
                                'batch_goods_id'=>$batch['batch_goods_id'],
                            );
                            Service_InventoryBatchSerial::add($inventoryBatchSerialRow);
                        }

                        $p['quantity'] -= $batch['ib_quantity']; //扣除已经处理的
                    }
                }

                if ($p['quantity'] > 0) {
                    throw new Exception('[' . $product['product_barcode'] . ' ]insufficient stock 002',50020);
                }
            }
            $db->commit();
            $result['ask'] = 1;
            $result['message'] = "易货单[".$swapOrderRow['swo_code']."]已下架,下架单号:".$this->_pickingCode;
            $result['picking_code'] = $this->_pickingCode;
        }catch (Exception $e){
            $db->rollBack();
            $result['ask'] = 0;
            $result['message'] =  $e->getMessage();
        }
        return $result;
    }

    public function qcSubmit($params = array()){
        $result = array(
            'state' => 0,
            'error' => array(),
            'message' => ''
        );
        $db = Service_QualityControl::getModelInstance()->getAdapter();
        $this->setQcData($params);
        $this->validQcData();
        if (!empty($this->_errorArr)) {
            $result['error'] = $this->_errorArr;
            return $result;
        }
        $db->beginTransaction();
        try{
            $this->updateSwapOrderDetail();
            //throw new Exception("updateSwapOrderDetail");
            $this->updateProduct();
            //throw new Exception("updateProduct");
            $this->updateQC();
            //throw new Exception("updateQC");
            $this->putaway();
            //throw new Exception("putaway");
            $this->inventory();
            //throw new Exception("inventory");
            //收取打包费
            $this->packFee();
            $db->commit();
            $result = array('state' => 1, 'message' => Ec::Lang('operationSuccess'));
        }catch (Exception $e){
            $db->rollBack();
            $result['error'][] = array(
                'errorCode' => '50000',
                'errorMsg' => $e->getMessage()
            );
        }
        return $result;
    }

    private function setQcData($params = array())
    {
        $keys = array(
            'receivedQty' => 0,
            'problemQty' => 0,
            'noLabelQty' => 0,
            'qcId' => 0,
            'userId' => 0,
            'remark' => '',
            'firstReceived' => 1,
            'shelf' => 0,
            'productWeight' => 0,
            'qcQty' => array(),
            'qcNote' => array(),
            'product' => array(),
            'boxArray' =>array(),
            'is_qc'=>'',
            'qc_subject'=>'',
            'qc_category'=>'',
            'qc_quantity'=>'',
            'real_qc_category'=>'',
            'real_qc_quantity'=>'',
            'qualified_rate'=>'',
            'qc_remark'=>'',
        );
        foreach ($keys as $key => $val) {
            $this->_params[$key] = isset($params[$key]) ? $params[$key] : $val;
        }
        $this->_userId = Service_User::getUserId();
        $this->_warehouseId = Service_User::getUserWarehouseId();
        $this->_params['userId'] = $this->_params['userId'] == '0' ? $this->_userId : $this->_params['userId'];
        $this->_params['shelf'] = !empty($this->_params['shelf']) ? strtoupper(trim($this->_params['shelf'])) : '';
        $this->_QcOrder = Service_QualityControl::getByField($this->_params['qcId'], 'qc_id');
    }

    private function validQcData()
    {
        //易货单 不合格总数
        if($this->_QcOrder['qc_model']=="1"){
            if($this->_params['problemQty']>0){
                $this->_errorArr[] = array('errorCode' => '10086', 'errorMsg' => "易货单的质检不合格总数不能大于0");
            }
            if($this->_params['receivedQty']!=$this->_QcOrder['qc_quantity']){
                $this->_errorArr[] = array('errorCode' => '10087', 'errorMsg' => "收货数[".$this->_params['receivedQty']."]不等于送检数[".$this->_QcOrder['qc_quantity']."]");
            }
         }
        //当收货数量为0时,应当处理未到货
        if ($this->_params['problemQty'] > $this->_params['receivedQty'] || $this->_params['noLabelQty'] > $this->_params['receivedQty'] || !is_numeric($this->_params['receivedQty']) || $this->_params['receivedQty']<1 ) {
            $this->_errorArr[] = array('errorCode' => '10003', 'errorMsg' => Ec::Lang('quantityError'));
        }
        if (!empty($this->_params['qcQty'])) {
            foreach ($this->_params['qcQty'] as $key => $val) {
                if ($val > 0 && ($this->_params['qcNote'][$key] == '' || !isset($this->_params['qcNote'][$key]))) {
                    $this->_errorArr[] = array('errorCode' => '10004', 'errorMsg' => Ec::Lang('abnormalNote'));
                }
            }
        }
        if (empty($this->_QcOrder)) {
            $this->_errorArr[] = array('errorCode' => '10002', 'errorMsg' => Ec::Lang('empty QcOrder'));
        }
        if ($this->_QcOrder['qc_status'] != '0' && isset($this->_QcOrder['qc_status'])) {
            $this->_errorArr[] = array('errorCode' => '10005', 'errorMsg' => Ec::Lang('errorState'));
        }
        if ($this->_params['firstReceived'] == '0' && empty($this->_params['product'])) {
            $this->_errorArr[] = array('errorCode' => '10002', 'errorMsg' => Ec::Lang('empty product'));
        }

        if (empty($this->_params['shelf']) && $this->_params['problemQty'] > 0) {
            $this->_errorArr[] = array('errorCode' => '10006', 'errorMsg' => '货架号不能为空.');
        } elseif (!empty($this->_params['shelf']) && $this->_params['problemQty'] > 0) {
            $shelfRow = Service_Location::getByCondition(array('lc_code' => $this->_params['shelf'], 'warehouse_id' => $this->_warehouseId), '*');
            if (empty($shelfRow)) {
                $this->_errorArr[] = array('errorCode' => '10007', 'errorMsg' => '货架号不存在.');
            } else {
                if ($shelfRow[0]['lc_status'] != '1') {
                    $this->_errorArr[] = array('errorCode' => '10008', 'errorMsg' => '货架号不可用.');
                } else {
                    $areaRow = Service_WarehouseArea::getByField($shelfRow[0]['wa_code'], 'wa_code');
                    //不良品区
                    if (isset($areaRow['wa_type']) && $areaRow['wa_type'] != '2') {
                        $this->_errorArr[] = array('errorCode' => '10008', 'errorMsg' => '此货架号不属于不良品区域.');
                    }
                }
            }

        }
        $boxArr = $this->_params['boxArray'];
        $boxCodeArr=array();
        if(!empty($boxArr)){
            //校验
            $boxQty=0;
            foreach($boxArr as $key=>$val){
                $boxCode=$val['box_code'];
                if(empty($boxCode)){
                    $this->_errorArr[] = array('errorCode' => '10014', 'errorMsg'=>"分箱".($key+1)."必填");
                }else{
                    if(preg_match('/^BOX\d+/i', $val['box_code'])==false){
                        $this->_errorArr[] = array('errorCode' => '10014', 'errorMsg'=>"分箱号:".$val['box_code']."必须以box开头");
                    }
                    if(!in_array($val['box_code'],$boxCodeArr)){
                        $boxCodeArr[]=$val['box_code'];
                    }else{
                        $this->_errorArr[] = array('errorCode' => '10014', 'errorMsg'=>"分箱号:".$val['box_code']."存在重复");
                    }
                    /* if(!empty($boxCode)){
                    	$checkbox = Service_PutawayBox::getByField($boxCode,'box_code');
                    	if(!empty($checkbox)){
                    		$this->_errorArr[] = array('errorCode' => '10014', 'errorMsg'=>"分箱号:".$val['box_code']."系统已存在");
                    	}
                    } */
                    if(!is_numeric($val['quantity']) || $val['quantity']<1 || $val['quantity']=='' ){
                        $this->_errorArr[] = array('errorCode' => '10015', 'errorMsg'=>"分箱号:".$val['box_code'].'数量必填');
                    }else{
                        $boxQty+=$val['quantity'];
                    }
                }
            }
            if($boxQty!=$this->_params['receivedQty']-$this->_params['problemQty']){
                $this->_errorArr[] = array('errorCode' => '10015', 'errorMsg'=>'分箱产品总数量必须等于实收总数减不合格总数');
            }
        }

        if (!preg_match('/^[0-9]+(?:\.\d+)?$/', $this->_params['productWeight']) || $this->_params['productWeight'] <= 0) {
            $this->_errorArr[] = array('errorCode' => '10016', 'errorMsg' => '产品重量必须是正数');
        }
    }

    private function updateSwapOrderDetail(){
        $swoStatus =4;
        $updateSwd = array(
            'swod_status'=>4,
            'last_update_time'=>date("Y-m-d H:i:s"),
        );
        if($this->_params['is_qc']=="1"&&$this->_params['qc_subject']=="BH"){
            $updateSwd['real_qc_category'] = $this->_params['real_qc_category'];
            $updateSwd['real_qc_quantity'] = $this->_params['real_qc_quantity'];
            $updateSwd['qualified_rate'] = $this->_params['qualified_rate'];
            $qcCategory = Service_QcCategory::getByField($this->_params['real_qc_category'],"qcc_code","*");
            $otherFee = Service_OtherFee::getByField('QCFEE','fee_code',"*");
            $customerRow = Service_Customer::getByField($this->_QcOrder['customer_id'],"customer_id","*");
            $customerOtherFee = Service_CustomerOtherFee::getByCondition(array('fee_id'=>$otherFee['fee_id'],'customer_code'=>$customerRow['customer_code']),"*");
            $price = $this->_params['real_qc_quantity']*$qcCategory['qcc_fee'];
            if(!empty($customerOtherFee)){
                $price = $price * $customerOtherFee[0]['discount'];
            }
            $feeArr = array(
                'currency_code'=>$qcCategory['currency_code'],
                'price'=>$price
            );
            Service_CustomerBalanceProcess::deductFee($this->_QcOrder['customer_id'], $feeArr, '易货单质检,扣质检费', $this->_QcOrder['qc_code'],'',$otherFee['fee_id'],array('add_time'=>date("Y-m-d H:i:s")));
        }
        $updateSwd['qc_remark'] = $this->_params['qc_remark'];
        Service_SwapOrderDetail::update($updateSwd,$this->_QcOrder['rd_id'],"swod_id");
        $swapDetail = Service_SwapOrderDetail::getByCondition(array('swo_code' => $this->_QcOrder['receiving_code']), '*');
        foreach($swapDetail as $val){
            if($val['swod_status']<4){
                $swoStatus = 3 ;
                break;
            }
        }
        if($swoStatus==4){
            $updateSwapOrder =array(
                'swo_status'=>4,
                'last_update_time'=>date("Y-m-d H:i:s")
            );
            Service_SwapOrder::update($updateSwapOrder,$this->_QcOrder['receiving_code'],'swo_code');
        }
    }

    private function updateProduct()
    {
        $productRow = Service_Product::getByField($this->_QcOrder['product_id'], 'product_id');
        //不是首次收货，只更新重量
        if ($this->_params['firstReceived'] == '1') {
            //if ($productRow['product_weight'] < $this->_params['productWeight']) {
            $productQcCount = Service_QualityControl::getByCondition(array(
                'product_id' => $this->_QcOrder['product_id'],
                'no_draft' => TRUE, // 统计非草稿状态的所有质检单数量
            ), 'count(*)');

            if (!$productQcCount) {
                Service_Product::update(array('product_weight' => $this->_params['productWeight'], 'product_update_time' => $this->_date), $this->_QcOrder['product_id']);
                $note = ' Weight:' . $productRow['product_weight'] . ' to  ' . $this->_params['productWeight'];
                $log = array(
                    'product_id' => $this->_QcOrder['product_id'],
                    'pl_type' => '0',
                    'user_id' => $this->_userId,
                    'customer_id' => $this->_QcOrder['customer_id'],
                    'pl_note' => $note,
                );
                Service_ProductLog::add($log);
            }
            //}
            return true;
        }
        //首次收货,确认详细资料
        $row = array(
            //'product_declared_value' => $this->_params['product']['declaredValue'],
            'product_length' => $this->_params['product']['length'],
            'product_width' => $this->_params['product']['width'],
            'product_receive_status' => 1,
            'product_height' => $this->_params['product']['height'],
            'pc_id' => $this->_params['product']['category'],
            'product_weight' => $this->_params['productWeight'],
            'product_update_time' => $this->_date,
        );
        Service_Product::update($row, $this->_QcOrder['product_id']);
        //$note = 'first goods,declaredValue:' . $productRow['product_declared_value'] . ' to  ' . $this->_params['product']['declaredValue'];
        $note = 'first goods,declaredValue: Weight:' . $productRow['product_weight'] . ' to  ' . $this->_params['productWeight'];
        $note .= ' Width:' . $productRow['product_width'] . ' to  ' . $this->_params['product']['width'];
        $note .= ' Length:' . $productRow['product_length'] . ' to  ' . $this->_params['product']['length'];
        $note .= ' Height:' . $productRow['product_height'] . ' to  ' . $this->_params['product']['height'];

        $log = array(
            'product_id' => $this->_QcOrder['product_id'],
            'pl_type' => '0',
            'user_id' => $this->_userId,
            'customer_id' => $this->_QcOrder['customer_id'],
            'pl_note' => $note,
        );
        Service_ProductLog::add($log);
        $package = Service_ProductPackageMap::getByCondition(array('product_id' => $this->_QcOrder['product_id'], 'warehouse_id' => $this->_QcOrder['warehouse_id']), '*');
        if (!empty($package)) {
            Service_ProductPackageMap::update(array('pp_id' => $this->_params['product']['package'], 'ppm_update_time' => $this->_date), $package[0]['ppm_id']);
        } else {
            $row = array(
                'product_id' => $this->_QcOrder['product_id'],
                'pp_id' => $this->_params['product']['package'],
                'warehouse_id' => $this->_QcOrder['warehouse_id'],
                'ppm_update_time' => $this->_date,
            );
            Service_ProductPackageMap::add($row);
        }
    }

    private function updateQC()
    {
        $qcRow = array(
            'qc_received_quantity' => $this->_params['receivedQty'],
            'qc_status' => 1,
            'lc_code' => $this->_params['shelf'],
            'qc_note' => $this->_params['remark'],
            'qc_operator_id' => $this->_params['userId'],
            'qc_quantity_sellable' => $this->_params['receivedQty'] - $this->_params['problemQty'],
            'qc_quantity_unsellable' => $this->_params['problemQty'],
            'qc_update_time' => $this->_date,
            'qc_finish_time' => $this->_date,
        );
        Service_QualityControl::update($qcRow, $this->_QcOrder['qc_id']);

        //Qc Result
        if ($this->_QcOrder['qc_type'] == '1' && !empty($this->_params['qcQty'])) {
            $qcResultObj = new Service_QualityControlResult();
            foreach ($this->_params['qcQty'] as $key => $qty) {
                $add = array(
                    'qc_id' => $this->_QcOrder['qc_id'],
                    'qc_code' => $this->_QcOrder['qc_code'],
                    'pqo_id' => $key,
                    'qcr_quantity_pass' => $this->_params['receivedQty'] - $qty,
                    'qcr_quantity_problem' => $qty,
                    'qcr_description' => isset($this->_params['qcNote'][$key]) ? $this->_params['qcNote'][$key] : '',
                    'qcr_add_time' => $this->_date,
                );
                $qcResultObj->add($add);
            }
        }
    }

    private function  putaway()
    {

        $putawayRow = Service_Putaway::getByField($this->_QcOrder['receiving_code'], 'receiving_code');

        $boxArr = $this->_params['boxArray'];
        if(!empty($boxArr)){
            foreach($boxArr as $key=>$val){
                $putaway = array(
                    'putaway_id' => $putawayRow['putaway_id'],
                    'putaway_code' => $putawayRow['putaway_code'],
                    'qc_code' => $this->_QcOrder['qc_code'],
                    'box_code'=>strtoupper($val['box_code']),
                    'receiving_code' => $putawayRow['receiving_code'],
                    'pd_type' => 2,
                    'product_barcode' => $this->_QcOrder['product_barcode'],
                    'product_id' => $this->_QcOrder['product_id'],
                    'pd_quantity' =>$val['quantity'],
                    'pd_lot_number' => 1,
                    'warehouse_id' => $this->_QcOrder['warehouse_id'],
                    'pd_add_time' => $this->_date,
                );
                Service_PutawayDetail::add($putaway);
            }
        }else{
            //之前的程序 只有一条 如果 有 分箱会插入多条
            $putaway = array(
                'putaway_id' => $putawayRow['putaway_id'],
                'putaway_code' => $putawayRow['putaway_code'],
                'qc_code' => $this->_QcOrder['qc_code'],
                'receiving_code' => $putawayRow['receiving_code'],
                'pd_type' => 1,
                'product_barcode' => $this->_QcOrder['product_barcode'],
                'product_id' => $this->_QcOrder['product_id'],
                'pd_quantity' => $this->_params['receivedQty'] - $this->_params['problemQty'],
                'pd_lot_number' => 1,
                'warehouse_id' => $this->_QcOrder['warehouse_id'],
                'pd_add_time' => $this->_date,
            );
            Service_PutawayDetail::add($putaway);
        }


    }

    private function inventory()
    {
        $row = array(
            'product_id' => $this->_QcOrder['product_id'],
            'quantity' => 0,
            'customQty' => 0, //用于其它
            'operationType' => 2,
            'unsellable' => 0,
            'warehouse_id' => $this->_QcOrder['warehouse_id'],
            'reference_code' => $this->_QcOrder['qc_code'], //操作单号
            'application_code' => 'QC', //操作类型
            'note' => '质检入库',
        );
        $obj = new Service_ProductInventoryProcess();
        //receivedQty 实收总数
        //problemQty 不合格总数
        //noLabelQty 未贴标数量
        //rd_receiving_qty 送货数
        //rd_received_qty 收货数量
        //$this->_QcOrder = Service_QualityControl::getByField($this->_params['qcId'], 'qc_id');
        /*$onWay = ($this->_asnItem[$this->_QcOrder['rd_id']]['rd_received_qty'] + $this->_params['receivedQty']) - $this->_asnItem[$this->_QcOrder['rd_id']]['rd_receiving_qty'];
        if ($onWay > 0) {
            $qty = $this->_asnItem[$this->_QcOrder['rd_id']]['rd_receiving_qty'] - $this->_asnItem[$this->_QcOrder['rd_id']]['rd_received_qty'];
            $row['customQty'] = $qty;
        } else {
            $row['customQty'] = $this->_params['receivedQty'];
        }*/
        $swd = Service_SwapOrderDetail::getByField($this->_QcOrder['rd_id'],"swod_id","*");
        $row['customQty'] = $swd['quantity'];
        $row['quantity'] = $this->_params['receivedQty'];
        $row['unsellable'] = $this->_params['problemQty'];

        $result = $obj->update($row);
        if (!isset($result['state']) || $result['state'] != '1') {
            // $this->_errorArr[]=array('errorCode'=>'50000','errorMsg'=>'Internal error');
            throw new Exception('Inventory Internal error');
        }
    }

    /**
     * [packFee 收取打包费]
     * @return [type] [description]
     */
    private function packFee(){
        $sodRow = Service_SwapOrderDetail::getByField($this->_QcOrder['rd_id'], "swod_id", "*");
        if(!empty($sodRow)){
            $swRow = Service_SwapOrder::getByField($sodRow['swo_id'], 'swo_id', array('customer_id'));
            $productWeight = Service_Product::getByField($sodRow['product_id'], 'product_id', array('product_weight'));
            //易货单中产品对应的是否打包为是
            if(isset($sodRow['is_package']) && $sodRow['is_package'] == 1){
                $objOtherCalculte = new Common_CalculateOtherFee(array());
                $objOtherCalculte->setQualityParams($sodRow);
                $otherFeeCode = 'DBF';
                $otherfeeArr = $objOtherCalculte->getOtherFee($otherFeeCode);
                $otherfeeDabao = $otherfeeArr['data']['otherFee'][strtolower($otherFeeCode)];
                if($otherfeeDabao['price'] > 0 ) {
                    $dabaoOtherFee = Service_OtherFee::getByField($otherFeeCode,'fee_code');
                    //扣打包费
                    $deductResult = Service_CustomerBalanceProcess::deductFee($swRow['customer_id'], $otherfeeDabao, '易货单'.$swRow['swo_code'].'扣打包费', $this->_QcOrder['qc_code'], $otherFeeCode, $otherfeeDabao['fee_id']);
                    if($deductResult['ask'] !=1 ){
                        throw new Exception($deductResult['error']);
                    }
                     //处理收费业务数据
                    $paymentArr = $incomeArr = $fee_cost_detail = array();
                    $dabaoBusinessIncom = self::getBusinessAndIncom($this->_QcOrder, $otherfeeDabao, $dabaoOtherFee);
                    // 打包费
                    if(!empty($dabaoBusinessIncom)){
                        if(array_key_exists('income', $dabaoBusinessIncom) && $dabaoBusinessIncom['income']){
                            $incomeArr[] = $dabaoBusinessIncom['income'];
                        }
                        if(array_key_exists('payment', $dabaoBusinessIncom) && $dabaoBusinessIncom['payment']){
                            $paymentArr[] = $dabaoBusinessIncom['payment'];
                        }
                        if(array_key_exists('cost_detail', $dabaoBusinessIncom) && $dabaoBusinessIncom['cost_detail']){
                            $fee_cost_detail[] = $dabaoBusinessIncom['cost_detail'];
                        }
                    }
                    //处理财务业务数据
                    if(!empty($incomeArr) || !empty($paymentArr)){
                        $weight = $productWeight['product_weight'] * $sodRow['quantity'];
                        self::doBusinessPaymentIncome($this->_QcOrder, $sodRow, $incomeArr, $paymentArr, $fee_cost_detail, $weight);
                    }
                }

            }
        }else {
            throw new Exception('质检单号'.$this->_QcOrder['qc_code'].'对应的易货单不存在');
        }
    }

    /**
     * [getBusinessAndIncom 获取费用 应收 | 应付 | 成本数组]
     * @author [simple] <[<^^^^^^^>]>
     * @param  [type] $qcRow        [质检单]
     * @param  [type] $otherfeeRow  [收费数组]
     * @param  [type] $otherFeeInfo [费用基本数组]
     * @return [type]               [description]
     */
    private static function getBusinessAndIncom($qcRow, $otherfeeRow, $otherFeeInfo){
        //应收 / 应付 / 成本
        $incomeArr = $paymentArr = $fee_cost_detail = array();
        $date = date("Y-m-d H:i:s");
        $tmpFee =  strtolower($otherFeeInfo['fee_code']);
        $_otherfee_mix_arr = Process_BillConfig::getOtherFeeArr();
        $billConfig = $_otherfee_mix_arr[$tmpFee];
        if(empty($billConfig)){
            throw new Exception('费用['.$otherFeeInfo['fee_code'].']配置错误');
        }
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        $remote_ip = Common_Common::getIP();
        $customerArr = Service_Customer::getByField($qcRow['customer_code'], 'customer_code', array('customer_saler_user_id','customer_currency'));
        //转为客户币种
        $convert_fee = Service_Currency::converByCode($otherfeeRow['currency_code'], $customerArr['customer_currency'], $otherfeeRow['price']);
        //应收
        $incomeArr = array(
            'customer_code' => $qcRow['customer_code'],
            'ft_code' => $billConfig['ftcode'],
            'ut_code' => $billConfig['utcode'],
            'sm_code' => '',
            'bi_amount' => $convert_fee,
            'bi_org_amount' => $otherfeeRow['price'],
            'currency_code' => $otherfeeRow['currency_code'],
            'currency_rate' => '',
            'bi_chargeable_time' => $date,
            'bi_note' => $otherFeeInfo['fee_name'],
        );
        $fee_detail = array(
            'fee_amount_customer' => $convert_fee,                                  //费用金额（客户）
            'fee_currency_code_customer' => $customerArr['customer_currency'],      //费用币种（客户）
            'discount_customer' => $otherFeeInfo['discount'],                       //折扣率（客户）（1=100%）
        );
        //应付费用  服务商不能为空
        $cost_detail = array();
        if (isset($otherfeeRow['cost']) && $otherfeeRow['cost'] > 0 && $otherFeeInfo['sp_code'] != '') {
            $spRow = Service_ServiceProvider::getByField($otherFeeInfo['sp_code'], 'sp_code');
            //转为服务商币种
            $convert_fee = Service_Currency::converByCode($otherFeeInfo['fee_currency_code'], $spRow['currency_code'], $otherFeeInfo['cost']);
            $paymentArr = array(
                'sp_code' => $otherFeeInfo['sp_code'],                              //服务商代码
                'ft_code' => $billConfig['ftcode'],
                'ut_code' => $billConfig['utcode'],
                'sm_code' => '',
                'bp_amount' => $convert_fee,
                'bp_org_amount' => $otherfeeRow['cost'],
                'currency_code' => $otherFeeInfo['fee_currency_code'],
                'currency_rate' => '',
                'bp_chargeable_time' => $date,
            );
            $cost_detail = array(
                'cost_amount_org'           => $otherfeeRow['cost'],                    //成本金额（原始）
                'cost_currency_code_org'    => $otherFeeInfo['fee_currency_code'],      //成本币种（原始）
                'cost_amount_sp'            => $convert_fee,                            //成本金额（服务商）
                'cost_currency_code_sp'     => $spRow['currency_code'],                 //成本币种（服务商）
                'sp_code'                   => $otherFeeInfo['sp_code'],                //服务商代码
            );
        }
        if(!empty($fee_detail) || !empty($cost_detail)){
            $fee_cost_common = array(
                'code_number'                   => $qcRow['qc_code'],                   //单号
                'code_type'                     => '',                                  //单号类型（1:区内单 2：区外单 3：ASN单, ）
                'customer_code'                 => $qcRow['customer_code'],             //客户代码
                'reference_no'                  => $qcRow['qc_code'],                   //客户参考号
                'tracking_number'               => '',                                  //服务商单号（跟踪号）
                'sm_code'                       => '',                                  //运输方式代码
                'country_code'                  => '',                                  //国际简称（二字码）
                'fee_code'                      => $otherFeeInfo['fee_code'],           //费用编号
                'fee_name'                      => $billConfig['binote'],               //费用名称
                'fee_amount_org'                => $otherFeeInfo['price'],              //费用金额（原始）
                'fee_currency_code_org'         => $otherFeeInfo['fee_currency_code'],  //费用币种（原始）
                'price_batch_number'            => '',                                  //运输价格编号
                'currency_batch_number'         => '',                                  //货币汇率编号
                'fee_time'                      => $date,                               //扣费时间
                'fee_time_recalculate'          => $date,                               //重新扣费时间
                'ip'                            => $remote_ip,                          //扣费操作IP
                'ip_recalculate'                => $remote_ip,                          //重新扣费操作IP
                'operator'                      => $userAuth->user['user_name'],        //扣费操作人
                'operator_recalculate'          => $userAuth->user['user_name'],        //重新扣费操作人
            );
            $fee_cost_detail = array_merge($fee_detail, $cost_detail, $fee_cost_common);
        }
        return array(
            'income' => $incomeArr,
            'payment' => $paymentArr,
            'cost_detail' => $fee_cost_detail
        );
    }

    /**
     * [doBusinessPaymentIncome 处理财务业务数据]
     * @param  [type] $qcRow           [质检单]
     * @param  [type] $sodRow          [易货单]
     * @param  [type] $incomeArr       [应收]
     * @param  [type] $paymentArr      [应付]
     * @param  [type] $fee_cost_detail [成本]
     * @param  [type] $weight          [重量]
     * @return [type]                  [description]
     */
    private static function doBusinessPaymentIncome($qcRow, $sodRow, $incomeArr, $paymentArr, $fee_cost_detail, $weight){
        $customerArr = Service_Customer::getByField($qcRow['customer_code'], 'customer_code', array('customer_saler_user_id','customer_currency'));
        //判断是否存在应收、应付
        if(!empty($incomeArr) || !empty($paymentArr)){
            //写入业务表
            $businessArr = array(
                'ds_code' => 'ot',
                'customer_code' => $qcRow['customer_code'],
                'warehouse_id' => $qcRow['warehouse_id'],
                'sm_code' => '',
                'bb_volume_weight' => $weight,
                'bb_charge_weight' => $weight,
                'bb_delivered_weight' => $weight,
                'bb_pieces' => $sodRow['quantity'],
                'bb_declared_value' => 0,
                'bb_declared_currency_code' => $incomeArr['currency_code'],
                'country_code' => '',
                'bb_postcode' => '',
                'bb_charge_time' => date("Y-m-d H:i:s"),
                'bb_declared_time' => date('Y-m-d H:i:s'), //发货时间 此时间与服务商对接
                'bb_sales_id' => $customerArr['customer_saler_user_id'],
                'bb_refer_code' => $qcRow['qc_code'],
                'bb_service_number' => '', //ref_tracking_number
                'bb_reference_no' => '',
            );
            $bsObj = new Process_Business();
            $businessResult = $bsObj->businessFee($businessArr, $incomeArr, $paymentArr);
            if($businessResult['state']!='1'){
                throw new Exception($businessResult['message']);
            }
        }
        //插入成本数据
        if(!empty($fee_cost_detail)){
            if(Service_FeeCostDetail::addMultiRows($fee_cost_detail) === false){
                throw new Exception('成本写入异常');
            }
        }
    }

    public static function sendToFenxiao($swo_code){
        $httpURL = "http://api.sinob2b.com/rs/oms/swapOrder/update";
        $postHeader = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        $appSercet = "1747dfbf884ac612e050007f01000ac5";
        $appKey = "1747dfbf884ac612e050007f01000ac5";
        $actionUrl = "/rs/oms/swapOrder/update";
        //$swo_code = "SWO150000045";
        $swapRow = Service_SwapOrder::getByField($swo_code,"swo_code","*");
        $swapOrderDetail = Service_SwapOrderDetail::getByCondition(array('swo_code'=>$swo_code),"*");
        $timestamp = strtotime($swapRow['last_update_time']);
        $order_code = $swapRow['swo_code'];
        $status = "S";
        $message = "易货成功";
        $finishTime = $swapRow['last_update_time'];
        //$shalstr = $actionUrl."appKey{$appKey}finishTime{$finishTime}message{$message}order_code{$order_code}status{$status}timestamp{$timestamp}{$appSercet}";
        //$sign = sha1($shalstr);
        $ch = curl_init($httpURL);
        curl_setopt($ch, CURLOPT_URL, $httpURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        $param = array(
            //'appKey'=>$appKey,
            'timestamp'=>$timestamp,
            'order_code'=>$order_code,
            'status'=>$status,
            'message'=>$message,
            'finishTime'=>$finishTime,
            //'sign'=>$sign,
        );
        $items = array();
        foreach($swapOrderDetail as $swod){
            $v = array(
                'customer_code'=>$swod['from_customer_code'],
                'product_sku'=>$swod['from_sku'],
                'to_sku'=>$swod['to_sku'],
                'quantity'=>$swod['quantity'],
                'qcRejectionRate'=>$swod['qualified_rate'],
                'qcOperator'=>$swod['qc_subject'],
                'qcRmk'=>$swod['qc_remark'],
                'qcQuantity'=>$swod['real_qc_quantity'],
            );
            $items[] = $v;
        }
        $shalArr = array();
        $shalArr[] = "appKey".$appKey;
        foreach($param as $key=>$val){
            $shalArr[] = $key.$val;
        }
        foreach($items as $k=>$v){
            foreach($v as $key=>$val){
                $shalArr[] = "items.".$key.$val;
            }
        }
        sort($shalArr);
        $shalStr = "";
        foreach($shalArr as $val){
            $shalStr.=$val;
        }
        $sign = sha1($shalStr.$appSercet);

        $requestParam = "appKey=".$appKey;
        foreach($param as $key=>$val){
            $requestParam.="&".$key."=".$val;
        }
        foreach($items as $k=>$v){
            foreach($v as $key=>$value){
                $requestParam.="&items.".$key."=".$value;
            }
        }
        $requestParam.="&sign=".$sign;

        $ch = curl_init($httpURL);
        curl_setopt($ch, CURLOPT_URL, $httpURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$requestParam);

        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }

        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        //echo $order_code.":".$response."</br>";
        $obj = json_decode($response);
        $result = Common_Common::objectToArray($obj);
        if($result['ack']=="Success"){
            $update = array(
                'has_send'=>1,
            );
            Service_SwapOrder::update($update,$order_code,'swo_code');
        }else{
            $update = array(
                'remark'=>$result['data'],
            );
            Service_SwapOrder::update($update,$order_code,'swo_code');
        }
    }

    public static function cancelToFenxiao($swo_code){
        $httpURL = "http://api.sinob2b.com/rs/oms/swapOrder/update";
        $postHeader = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        $appSercet = "1747dfbf884ac612e050007f01000ac5";
        $appKey = "1747dfbf884ac612e050007f01000ac5";
        $actionUrl = "/rs/oms/swapOrder/update";
        //$swo_code = "SWO150000045";
        $swapRow = Service_SwapOrder::getByField($swo_code,"swo_code","*");
        $timestamp = strtotime($swapRow['last_update_time']);
        $order_code = $swapRow['swo_code'];
        $status = "C";
        $message = "易货截单";
        $finishTime = $swapRow['last_update_time'];
        $shalstr = $actionUrl."appKey{$appKey}finishTime{$finishTime}message{$message}order_code{$order_code}status{$status}timestamp{$timestamp}{$appSercet}";
        $sign = sha1($shalstr);
        $ch = curl_init($httpURL);
        curl_setopt($ch, CURLOPT_URL, $httpURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        $param = array(
            'appKey'=>$appKey,
            'timestamp'=>$timestamp,
            'order_code'=>$order_code,
            'status'=>$status,
            'message'=>$message,
            'finishTime'=>$finishTime,
            'sign'=>$sign,
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($param));
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        //echo $order_code.":".$response."</br>";
        $obj = json_decode($response);
        $result = Common_Common::objectToArray($obj);
        if($result['ack']=="Success"){
            $update = array(
                'has_send'=>1,
                'remark'=>$result['data'],
            );
            Service_SwapOrder::update($update,$order_code,'swo_code');
        }
    }

    public function dealSerial($con1,$toProduct,$qty,$batch,$order_code){
        $inventoryBatchSerialList = Service_InventoryBatchSerial::getByCondition($con1, '*',0,0,'ib_id asc');
        if(!empty($inventoryBatchSerialList)){
            $forUseQty = $qty;
            foreach($inventoryBatchSerialList as $ibsl){
                $sumIbslBount = Service_InventoryBatchSerialOutbound::getByCondition(array('ibs_id'=>$ibsl['ibs_id']),"sum(ibso_quantity) as sumIbslBount");
                if (empty($sumIbslBount)) {
                    $haveUseQty = 0;
                } else {
                    $haveUseQty = $sumIbslBount[0]['sumIbslBount'];
                }
                $ibsl['ibs_quantity']-=$haveUseQty;
                if($forUseQty<=$ibsl['ibs_quantity']){
                    $inventoryBatchSerialRow = array(
                        'product_id' => $toProduct['product_id'],
                        'product_barcode' => $toProduct['product_barcode'],
                        'goods_id' => $toProduct['goods_id'],
                        'customer_code' => $toProduct['customer_code'],
                        'hs_serial_no'=>$ibsl['hs_serial_no'],
                        'swo_code'=>$order_code,
                        'ibs_quantity'=>$forUseQty,
                        'ibs_add_time'=>date("Y-m-d H:i:s"),
                        'from_ib_id' => $batch['ib_id'],
                        'batch_goods_id'=>$ibsl['batch_goods_id'],
                    );
                    Service_InventoryBatchSerial::add($inventoryBatchSerialRow);
                    //$forUseQuantity = $qty;
                    $IbsLBoundRow = array(
                        'reference_no' => $order_code,
                        'application_code' => 'pickup',
                        'ibso_quantity' => $forUseQty,
                        'ibs_id' => $ibsl['ibs_id'],
                        'ibso_add_time' => date('Y-m-d H:i:s')
                    );
                    Service_InventoryBatchSerialOutbound::add($IbsLBoundRow);
                    break;
                }else{
                    //$forUseQty = $ibsl['ibs_quantity'];
                    if ($ibsl['ibs_quantity'] <= 0) {
                        continue;
                    }
                    $inventoryBatchSerialRow = array(
                        'product_id' => $toProduct['product_id'],
                        'product_barcode' => $toProduct['product_barcode'],
                        'goods_id' => $toProduct['goods_id'],
                        'customer_code' => $toProduct['customer_code'],
                        'hs_serial_no'=>$ibsl['hs_serial_no'],
                        'swo_code'=>$order_code,
                        'ibs_quantity'=>$ibsl['ibs_quantity'],
                        'ibs_add_time'=>date("Y-m-d H:i:s"),
                        'from_ib_id' => $batch['ib_id'],
                        'batch_goods_id'=>$ibsl['batch_goods_id'],
                    );
                    Service_InventoryBatchSerial::add($inventoryBatchSerialRow);
                    $IbsLBoundRow = array(
                        'reference_no' => $order_code,
                        'application_code' => 'pickup',
                        'ibso_quantity' => $ibsl['ibs_quantity'],
                        'ibs_id' => $ibsl['ibs_id'],
                        'ibso_add_time' => date('Y-m-d H:i:s')
                    );
                    Service_InventoryBatchSerialOutbound::add($IbsLBoundRow);
                    $forUseQty -= $ibsl['ibs_quantity']; //扣除已经处理的
                }
            }
        }else{
            $inventoryBatchSerialRow = array(
                'product_id' => $toProduct['product_id'],
                'product_barcode' => $toProduct['product_barcode'],
                'goods_id' => $toProduct['goods_id'],
                'customer_code' => $toProduct['customer_code'],
                'hs_serial_no'=>$batch['hs_serial_no'],
                'swo_code'=>$order_code,
                'ibs_quantity'=>$qty,
                'ibs_add_time'=>date("Y-m-d H:i:s"),
                'from_ib_id' => $batch['ib_id'],
                'batch_goods_id'=>$batch['batch_goods_id'],
            );
            Service_InventoryBatchSerial::add($inventoryBatchSerialRow);
        }
        return true;
    }
}
