<?php
/*处理上架
 * @author Gilbert
 * @date 2015-08-28
 *
 */
class Service_Shelve{
    protected $_error = array();//错误信息
    protected $_code = null;//单号
    protected $_isDivided = false;
    protected $_shelveType = null;//上架类型
    protected $_shelveNumber = null;//上架数量
    protected $_shelfCode = null;//上架的货架号
    protected $_shelveBox = null;//上架的箱子
    protected $_qcCode = null;//上架的质检单号
    protected $_warehouseId = null;//仓库ID
    protected $_userId = null;//用户ID
    protected $_productQcType = 1;//1合格品 2不良品
    protected $_qcOrder = null;//质检单信息
    protected $_defectiveShelfCode = false;//是否是不良品货架
    protected $_product = null;//产品信息
    protected $_area = null;//分区信息
    protected $_receivingDetail = null;//入库单明细
    protected $_putAwayDetail = null;//上架明细
    protected $_receiving = null;//入库单信息
    protected $_box = null;//箱子信息
    public $_date = null;

    public function __construct($params=array()){
        $this->setParams($params);
        $this->setWarehouse();
        $this->setUser();
        $this->_date = date('Y-m-d H:i:s');
    }

    protected function setParams($params){
        foreach($params as $key=>$value){
            $p = "_$key";
            $this->$p = is_scalar($value)?trim($value):$value;
        }
    }

    public function getParam($name){
        if(empty($name) || !isset($this->$name)){
            return null;
        }
        return $this->$name;
    }

    public function getError(){
        return $this->_error;
    }

    protected function setWarehouse(){
        $this->_warehouseId = Service_User::getUserWarehouseId();
        if(!$this->_warehouseId){
            $this->_error[] = '初始化仓库失败';
        }
    }

    protected function setUser(){
        $this->_userId = Service_User::getUserId();
        if(!$this->_userId){
            $this->_error[] = '初始化登录用户失败';
        }
    }

    protected function setProduct(){
        //设置产品
        if($this->_qcOrder){
            $product = Service_Product::getByField($this->_qcOrder['product_id'],'product_id');
            if($product instanceof Zend_Db_Table_Row){
                $product = $product->toArray();
            }
            if(!$product){
                throw new Exception('找不到对应的产品信息');
            }
            $this->_product = $product;
        }
    }

    protected function setReceiving(){
        if($this->_qcOrder['qc_model']=="1"){
            $swoRow = Service_SwapOrder::getByField($this->_qcOrder['receiving_code'],'swo_code');
            $this->_receiving = $swoRow;
        }else{
            $receiving = Service_Receiving::getByField($this->_qcOrder['receiving_code'],'receiving_code');
            if($receiving instanceof Zend_Db_Table_Row){
                $receiving = $receiving->toArray();
            }
            if(!$receiving){
                throw new Exception('找不到相关入库单信息');
            }
            $this->_receiving = $receiving;
        }
    }

    /*检查上架信息
     *
     */
    protected function checkParams(){
        //1：pda上架
        if(!isset($this->_shelveType) && !in_array($this->_shelveType,array(1))){
            $this->_error[] = '缺少上架来源类型';
            return;
        }
        if(!$this->_code || !$this->_code){
            $this->_error[] = '缺少质检单/箱子';
            return;
        }
        if(!isset($this->_shelfCode) || !$this->_shelfCode){
            $this->_error[] = '缺少货架号';
            return;
        }
        try{
            //检查货架号
            $this->checkShelfCode();
            //检查是箱子或QC单
            if(!$this->checkQc($this->_code)){//如果设置QC单失败，说明它是箱号
                $this->checkBox($this->_code);//检查箱子，同时设置质检单号
            }
            if($this->_shelveBox){
                $this->_isDivided = true;//箱号不为空，说明是质检单是分箱的
            }
            //设置产品
            $this->setProduct();
            //如果前面设置质检单成功，那么判断质检单是否有分箱，如果有分箱，必须扫箱子才能上架，而不是扫质检单
            $this->checkPutAwayDetail();
            //检查是否可以上到此货架
            $this->checkShelve();
        }catch (Exception $e){
            $this->_error[] = $e->getMessage();
            return;
        }
        return;
    }
    /*
     * 检查货架号
     */
    protected function checkShelfCode(){
        $shelfRow = Service_Location::getByField($this->_shelfCode,'lc_code');
        if($shelfRow instanceof Zend_Db_Table_Row){
            $shelfRow = $shelfRow->toArray();
        }
        if(!$shelfRow){
            throw new Exception('货架号不存在');
        }
        if($shelfRow['lc_status']!=1){
            throw new Exception('货架不可用');
        }
        if($shelfRow['warehouse_id'] != $this->_warehouseId){
            throw new Exception('货架不属于当前仓库');
        }
        //去分区类型
        $areaRow = Service_WarehouseArea::getByField($shelfRow['wa_code'],'wa_code');
        if($areaRow instanceof Zend_Db_Table_Row){
            $areaRow = $areaRow->toArray();
        }
        if(!$areaRow){
            throw new Exception('货架对应的分区不存在');
        }
        if($areaRow['wa_type']==2){
            $this->_defectiveShelfCode = true;
        }
        $this->_area = $areaRow;
    }
    /*检查QC单号
     *
     */
    public function checkQc($code){
        $qcRow = Service_QualityControl::getByField($code,'qc_code');
        if($qcRow instanceof Zend_Db_Table_Row){
            $qcRow = $qcRow->toArray();
        }
        if($qcRow){
            if($qcRow['qc_status'] != 1){
                throw new Exception('质检单['.$code.']必须是完成质检状态');
            }
            if($qcRow['warehouse_id'] != $this->_warehouseId){
                throw new Exception('质检单不属于当前仓库');
            }
            $this->_qcCode = $code;
            $this->_qcOrder = $qcRow;
            if(!$this->_shelveBox){
                $this->_shelveNumber = $qcRow['qc_quantity_sellable'];
            }
            //设置入库单信息
            $this->setReceiving();
            //检查设置入库单明细
            $this->setReceivingDetail();

            return true;
        }
        return false;
    }
    /*检查箱号
     *
     */
    public function checkBox($code){
        $box = Service_Box::getByField($code,'box_code');
        if($box instanceof Zend_Db_Table_Row){
            $box = $box->toArray();
        }
        if(!$box){
            throw new Exception('请确保质检单/箱号是正确的');
        }
        if($box['box_status']!=2){
            throw new Exception('箱子是不是锁定状态，不能上架');
        }
        $this->_shelveBox = $code;
        $this->_shelveNumber = $box['box_quantity'];
        $this->_box = $box;
        //设置质检单号
        if($box['qc_code']){
            $this->checkQc($box['qc_code']);
        }else{
            throw new Exception('箱子信息里缺少质检单号');
        }
        return true;
    }

    protected function setReceivingDetail(){
        if($this->_qcOrder['qc_model']=="1"){
            $swoRow = Service_SwapOrder::getByField($this->_qcOrder['receiving_code'],"swo_code","*");
            $this->_receivingDetail = $swoRow;
        }else{
            $receivingDetail = Service_ReceivingDetail::getByCondition(array('receiving_code'=>$this->_qcOrder['receiving_code'],'product_id'=>$this->_qcOrder['product_id']));
            if(!$receivingDetail){
                throw new Exception( '找不到对应的入库单信息');
            }
            $this->_receivingDetail = $receivingDetail[0];
        }
    }

    public function checkPutAwayDetail(){
        $detailRows = Service_PutawayDetail::getByCondition(array('qc_code'=>$this->_qcCode));
        if($detailRows){
            //如果是用QC单上架的（QC上架的，不良品是没有putaway_detail数据的）
            if(!$this->_shelveBox){
                foreach($detailRows as $value){
                    if($value['box_code']){
                        throw new Exception( '质检单已分箱，请扫箱号上架');
                    }
                }
                //没分箱的情况下,一次上架就会把合格（不良）品上完
                //根据货架类型，自动设置上架数量
                $this->_shelveNumber = $this->_defectiveShelfCode?$this->_qcOrder['qc_quantity_unsellable']:$this->_qcOrder['qc_quantity_sellable'];
                if($this->_shelveNumber==0){
                    throw new Exception( '可上架数量不足，不能上架');
                }
                //检测是否已经上架了
                if($this->_defectiveShelfCode){
                    $tmpDefectiveQty = 0;
                    $batch = Service_InventoryBatch::getByCondition(array('receiving_code'=>$this->_qcOrder['receiving_code'],'product_id'=>$this->_qcOrder['product_id']));
                    if($batch){
                        foreach($batch as $value){
                            $tmpArea = Service_Location::joinArea(array('lc_code'=>$value['lc_code'],'warehouse_id'=>$value['warehouse_id'],'wa_type'=>2));
                           //不是不良品货架都跳过
                            if(!$tmpArea){
                                continue;
                            }
                            $tmpDefectiveQty += $value['ib_quantity']+$value['frozen'];
                        }
                    }
                    if($this->_qcOrder['qc_quantity_unsellable'] < $tmpDefectiveQty+$this->_shelveNumber){
                        throw new Exception('不良品上架数量异常');
                    }
                }else{
                    //收货数量 >= 已上架数量+当前上架数量
                    if($this->_qcOrder['qc_received_quantity']<$this->_receivingDetail['rd_putaway_qty']+$this->_shelveNumber){
                        throw new Exception('合格品上架数量异常');
                    }
                }
                $this->_putAwayDetail = $detailRows[0];
            }else{
                $detail = array();
                foreach($detailRows as $value){
                    if($value['box_code']==$this->_shelveBox){
                        $detail = $value;
                        break;
                    }
                }
                if(!$detail){
                    throw new Exception( '上架单【'.$detailRows[0]['putaway_code'].'】里找不到箱子【'.$this->_shelveBox.'】');
                }
                $this->_putAwayDetail = $detail;
            }
        }else{
            throw new Exception( '找不到上架信息');
        }
    }

    protected function checkShelve(){
        //品类=0 表示可以放所有产品
        if($this->_area['pc_id']>0){
            if($this->_product['pc_id'] != $this->_area['pc_id']){
                throw new Exception('货架的品类与产品品类不一致');
            }
        }
        //分箱了才进去判断
        if($this->_isDivided){
            switch($this->_putAwayDetail['pd_product_type']){
                case 1:
                    if($this->_defectiveShelfCode){
                        throw new Exception( '不良品货架不能放合格品');
                    }
                    break;
                case 2:
                    if(!$this->_defectiveShelfCode){
                        throw new Exception( '合格品货架不能放不良品');
                    }
                    break;
            }
        }
        //判断单签货架是否有相同保质期的产品
        /*if($this->_product['is_flash']==1){
            $condition = array(
                'product_id'=>$this->_product['product_id'],
                'warehouse_id'=>$this->_warehouseId,
                'lc_code'=>$this->_shelfCode,
            );
            $inventoryBatch = Service_InventoryBatch::getByCondition($condition,"*",0,0,"ib_id desc");
            if(!empty($inventoryBatch)){
                if($inventoryBatch[0]['production_time']!=$this->_putAwayDetail['production_time']){
                    throw new Exception('存在不同保质期的相同产品');
                }
            }
        }*/
    }
    /*@desc pda上架
     *
     */
    public function pdaShelve(){
        $this->checkParams();
        if(!empty($this->_error)){
            return false;
        }
        $db = Service_QualityControl::getModelInstance()->getAdapter();
        $db->beginTransaction();
        try{
            $this->updatePutAwayDetail();
            $this->inventoryBatch();
            $this->updateReceivingDetail();
            $this->updateInventory();
            $this->updateProductLocationMap();
            $this->updateQc();
            $this->releaseBox();
            //环球客户才写入
            if( Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner( $this->_qcOrder['customer_code'] ) ) {
                $this->inventoryNotify();
            }
            $db->commit();
            return true;
        }catch (Exception $e){
            $db->rollBack();
            $this->_error[] = $e->getMessage();
            return false;
        }

    }

    /**
     * @todo 添加gs库存通知
     */
    private function inventoryNotify(){
        $notify = array(
            'product_id' => $this->_qcOrder['product_id'],
            'product_sku' => $this->_product['product_sku'],
            'customer_code' => $this->_qcOrder['customer_code'],
            'reason' => '入库上架',
            'quantity' => $this->_shelveNumber,
            'referecne_no' => $this->_qcOrder['qc_code'],
            'reftype' => 1,
            'gstype' => 'InboundInventory',

        );
        Service_GsNotifyProcess::addNotify( $notify );
    }

    /**
     * @desc 更新上架数据状态
     */
    protected function updatePutAwayDetail(){
        //只有在分箱 或 是合格品上架的情况下才去更新
        if($this->_isDivided || $this->_putAwayDetail['pd_product_type']==1){
            $update = array(
                'pd_status' => 1,
                'lc_code' => $this->_shelfCode,
                'putaway_user_id' => $this->_userId,
                'pd_putaway_time' => $this->_date,
                'pd_update_time' => $this->_date
            );
            $result = Service_PutawayDetail::update($update,$this->_putAwayDetail['pd_id']);
            if(!$result){
                throw new Exception('更新上架单信息失败');
            }
        }
    }

    /**
     * @desc 更新ASN上架数量
     */
    protected function updateReceivingDetail(){
        //合格品才更新上架数量（为什么不良品上架不更新？）
        if($this->_qcOrder['qc_model']=="1"){
            $qcObj = new Service_QualityControl();
            $rows = Service_InventoryBatch::getByCondition(array('receiving_code'=>$this->_qcOrder['receiving_code'],'product_id'=>$this->_qcOrder['product_id'],'reference_no'=>$this->_qcOrder['qc_code']));
            $total = 0;
            foreach($rows as $value){
                $total += $value['ib_quantity'];
            }
            if($total==$this->_qcOrder['qc_received_quantity']){
                Service_SwapOrderDetail::update(array('swod_status'=>5),$this->_qcOrder['rd_id'],'swod_id');
                $qcObj->update(array('qc_status' => 2, 'qc_update_time' => $this->_date), $this->_qcOrder['qc_id']);
                $con = array(
                    'receiving_code'=>$this->_qcOrder['receiving_code'],
                    'not_qc_status'=>2,
                );
                $existQc = Service_QualityControl::getByCondition($con,'count(*)');
                if(!$existQc){
                    $updateSwapOrder =array(
                        'swo_status'=>5,
                        'last_update_time'=>date("Y-m-d H:i:s"),
                        'putway_time'=>date("Y-m-d H:i:s"),
                    );
                    Service_SwapOrder::update($updateSwapOrder,$this->_qcOrder['receiving_code'],'swo_code');
                    Service_SwapOrderProcess::sendToFenxiao($this->_qcOrder['receiving_code']);
                }
            }
        }else{
            if(!$this->_defectiveShelfCode){
                $updateRdt = array(
                    'rd_putaway_qty'=>$this->_receivingDetail['rd_putaway_qty']+$this->_shelveNumber,
                    'rd_update_time'=>$this->_date
                );
                $result = Service_ReceivingDetail::update($updateRdt,$this->_receivingDetail['rd_id'],"rd_id");
                if(!$result){
                    throw new Exception('更新入库单上架数量失败');
                }
                //添加入库单批次信息
                $receivingDetailBatch = array(
                    'receiving_id'=>$this->_receivingDetail['receiving_id'],
                    'receiving_code'=>$this->_receivingDetail['receiving_code'],
                    'receiving_line_no'=>'',
                    'product_barcode'=>$this->_receivingDetail['product_barcode'],
                    'product_id'=>$this->_receivingDetail['product_id'],
                    'rdb_weight'=>'',
                    'rdb_putaway_qty'=>$this->_putAwayDetail['pd_quantity'],
                    'rdb_received_qty'=>$this->_putAwayDetail['pd_quantity'],
                    'receiving_user_id'=>$this->_userId,
                    'rdb_add_time'=>$this->_date,
                    'rdb_update_time'=>$this->_date,
                );
                $result = Service_ReceivingDetailBatch::add($receivingDetailBatch);
                if(!$result){
                    throw new Exception('添加入库单批次信息失败');
                }
            }
        }
    }
    /**
     * @desc 添加货架批次库存
     */
    protected function inventoryBatch(){
        if($this->_qcOrder['qc_model']=="1"){
            //获取from_sku的产品ID
            $detail = Service_SwapOrderDetail::getByField( $this->_qcOrder['rd_id'] );
            $product = Service_Product::getByCondition( array( 'product_sku' => $detail['from_sku'], 'customer_code' => $detail['from_customer_code'] ) );
            $row = array(
                'lc_code' => $this->_shelfCode,
                'product_id' => $this->_qcOrder['product_id'],
                'customer_code'=>$this->_qcOrder['customer_code'],
                'product_barcode' => $this->_qcOrder['product_barcode'],
                'reference_no' => $this->_qcOrder['qc_code'],
                'application_code' => 'Putaway',
                'warehouse_id' =>$this->_warehouseId,
                'receiving_code' => $this->_receiving['swo_code'],
                'receiving_id' => $this->_receiving['swo_id'],
                'supplier_id' => "",
                'lot_number' => $this->_putAwayDetail['pd_lot_number'],
                'ib_status' => $this->_defectiveShelfCode?0:1,//不良品上架，状态为不可用
                'ib_quantity' => $this->_shelveNumber,
                'ib_fifo_time' => $this->_date,
                'ib_add_time' => $this->_date,
                'from_product_id' => $product[0]['product_id'],
                //'production_time'=>$this->_putAwayDetail['production_time']
            );
            if($this->_shelveBox){
                $row['box_code'] = $this->_shelveBox;
            }
            $ibId = Service_InventoryBatch::add($row);
            if(!$ibId){
                throw new Exception('添加批次库存失败');
            }
            $ibsList = Service_InventoryBatchSerial::getByCondition(array('product_id' => $this->_qcOrder['product_id'],'swo_code'=>$this->_receiving['swo_code']),"*");
            if(!empty($ibsList)){
                foreach($ibsList as $ibs){
                    Service_InventoryBatchSerial::update(array('ib_id'=>$ibId,'ibs_status'=>1),$ibs['ibs_id'],"ibs_id");
                }
            }
            $log = array(
                'lc_code' => $this->_shelfCode,
                'product_id' => $this->_qcOrder['product_id'],
                'product_barcode' => $this->_qcOrder['product_barcode'],
                'reference_no' => $this->_qcOrder['qc_code'],
                'application_code' => 'Putaway',
                'warehouse_id' => $this->_warehouseId,
                'receiving_code' => $this->_receiving['swo_code'],
                'supplier_id' => "",
                'ib_id' => $ibId,
                'ibl_quantity_before' => 0,
                'ibl_quantity_after' => $this->_putAwayDetail['pd_quantity'],
                'user_id' => $this->_userId,
                'ibl_ip' => Common_Common::getIP(),
                'ibl_add_time' => $this->_date,
            );
            if($this->_shelveBox){
                $log['box_code'] = $this->_shelveBox;
            }
            $result = Service_InventoryBatchLog::add($log);
            if(!$result){
                throw new Exception('添加库存日志失败');
            }
        }else{
            $row = array(
                'lc_code' => $this->_shelfCode,
                'product_id' => $this->_qcOrder['product_id'],
                'customer_code'=>$this->_qcOrder['customer_code'],
                'product_barcode' => $this->_qcOrder['product_barcode'],
                'reference_no' => $this->_qcOrder['qc_code'],
                'application_code' => 'Putaway',
                'warehouse_id' =>$this->_warehouseId,
                'receiving_code' => $this->_receiving['receiving_code'],
                'receiving_id' => $this->_receiving['receiving_id'],
                'supplier_id' => $this->_receiving['supplier_id'],
                'lot_number' => $this->_putAwayDetail['pd_lot_number'],
                'ib_status' => $this->_defectiveShelfCode?0:1,//不良品上架，状态为不可用
                'ib_quantity' => $this->_shelveNumber,
                'ib_fifo_time' => $this->_date,
                'ib_add_time' => $this->_date,
                //'production_time'=>$this->_putAwayDetail['production_time']
            );
            if($this->_shelveBox){
                $row['box_code'] = $this->_shelveBox;
            }
            $ibId = Service_InventoryBatch::add($row);
            if(!$ibId){
                throw new Exception('添加批次库存失败');
            }
            $log = array(
                'lc_code' => $this->_shelfCode,
                'product_id' => $this->_qcOrder['product_id'],
                'product_barcode' => $this->_qcOrder['product_barcode'],
                'reference_no' => $this->_qcOrder['qc_code'],
                'application_code' => 'Putaway',
                'warehouse_id' => $this->_warehouseId,
                'receiving_code' => $this->_receiving['receiving_code'],
                'supplier_id' => $this->_receiving['supplier_id'],
                'ib_id' => $ibId,
                'ibl_quantity_before' => 0,
                'ibl_quantity_after' => $this->_putAwayDetail['pd_quantity'],
                'user_id' => $this->_userId,
                'ibl_ip' => Common_Common::getIP(),
                'ibl_add_time' => $this->_date,
            );
            if($this->_shelveBox){
                $log['box_code'] = $this->_shelveBox;
            }
            $result = Service_InventoryBatchLog::add($log);
            if(!$result){
                throw new Exception('添加库存日志失败');
            }
        }
    }

    /**
     * @desc 更新产品库存
     * @throws Exception
     */
    protected function updateInventory(){
        $inventoryObj = new Service_ProductInventoryProcess();
        $row = array(
            'product_id' => $this->_qcOrder['product_id'],
            'quantity' => 0,
            'customQty' => 0, //用于其它
            //'operationType' => 3,
            'unsellable' => 0,
            'warehouse_id' => $this->_warehouseId,
            'reference_code' => $this->_qcOrder['qc_code'], //操作单号
            'application_code' => 'Putaway', //操作类型
            'note' => 'PDA确认上架',
            'production_time'=>$this->_putAwayDetail['production_time']
        );
        if($this->_defectiveShelfCode){
            $row['operationType'] = 4;
            $row['quantity'] = $this->_shelveNumber;
        }else{
            $row['operationType'] = 3;
            $row['quantity'] = $this->_shelveNumber;
        }

        $qcRow = Service_QualityControl::getByField($this->_qcOrder['qc_code'],'qc_code',"*");
        if($qcRow['qc_model']=="1"){
            $swd = Service_SwapOrderDetail::getByField($qcRow['rd_id'],"swod_id","*");
            $fromProduct = Service_Product::getByField($swd['product_id'],"product_id","*");
            $exSwp = Service_SwapProduct::getByCondition(array('product_id'=>$swd['product_id'],'from_goods_id'=>$fromProduct['goods_id']),"*");
            if(!empty($exSwp)){
                $updateSwp = array(
                    'sp_quantity'=>$exSwp[0]['sp_quantity']-$this->_shelveNumber,
                );
                Service_SwapProduct::update($updateSwp,$exSwp[0]['sp_id'],"sp_id");
            }
        }

        $productRow = Service_Product::getByField($this->_qcOrder['product_id'],"product_id","*");
        $exSwp = Service_SwapProduct::getByCondition(array('product_id'=>$productRow['product_id'],'from_goods_id'=>$productRow['goods_id']),"*");
        if(!empty($exSwp)){
            $updateSwp = array(
                'sp_quantity'=>$exSwp[0]['sp_quantity']+$this->_shelveNumber,
            );
            Service_SwapProduct::update($updateSwp,$exSwp[0]['sp_id'],"sp_id");
        }else{
            $swapProductRow = array(
                'product_id'=>$productRow['product_id'],
                'product_sku'=>$productRow['product_sku'],
                'customer_code'=>$productRow['customer_code'],
                'product_barcode'=>$productRow['product_barcode'],
                'from_goods_id'=>$productRow['goods_id'],
                'sp_quantity'=>$this->_shelveNumber,
            );
            Service_SwapProduct::add($swapProductRow);
        }

        //print_r($row);throw new Exception("break");
        $result = $inventoryObj->update($row);
        if (!isset($result['state']) || $result['state'] != '1') {
            throw new Exception('更新总库存失败');
        }
    }

    /**
     * @desc 更新产品历史货架
     * @throws Exception
     */
    protected function updateProductLocationMap(){
        $obj = new Service_ProductLocationMap();
        $condition = array(
            'product_id' => $this->_qcOrder['product_id'],
            'warehouse_id' => $this->_warehouseId,
        );
        $result = false;
        $rows = $obj->getByCondition($condition);
        if (!empty($rows)) {
            if ($rows[0]['lc_code'] != $this->_shelfCode) {
                $result = $obj->update(array('lc_code' => $this->_shelfCode), $rows[0]['plm_id'], 'plm_id');
            }else{
                $result = true;
            }
        } else {
            $condition['lc_code'] = $this->_shelfCode;
            $result = $obj->add($condition);
        }
        if (!$result) {
            throw new Exception('更新产品货架失败');
        }
    }

    /*@desc 更新质检单状态
     *
     */
    protected function updateQc(){
        if($this->_qcOrder['qc_model']=="1"){
            $rows = Service_InventoryBatch::getByCondition(array('receiving_code'=>$this->_qcOrder['receiving_code'],'product_id'=>$this->_qcOrder['product_id'],'reference_no'=>$this->_qcOrder['qc_code']));
        }else{
            $rows = Service_InventoryBatch::getByCondition(array('receiving_code'=>$this->_qcOrder['receiving_code'],'product_id'=>$this->_qcOrder['product_id']));
        }
        $total = 0;
        foreach($rows as $value){
            $total += $value['ib_quantity'];
        }
        if($total==$this->_qcOrder['qc_received_quantity']){
            $update = array(
                'qc_status'=>2,
                'qc_update_time'=>$this->_date
            );
            Service_QualityControl::update($update,$this->_qcOrder['qc_id'],'qc_id');
        }
        if(isset($this->_qcOrder['qc_model'])&&$this->_qcOrder['qc_model']!="1"){
            $condition = array(
                'receiving_code'=>$this->_qcOrder['receiving_code'],
                'unshelf_status'=>'1'
            );
            $total = Service_QualityControl::getByCondition($condition,"count(*)");
            if(!$total){
                Service_Receiving::update(array('receiving_status' => 7, 'receiving_update_time' =>date("Y-m-d H:i:s")), $this->_qcOrder['receiving_code'],"receiving_code");
                $updateRa = array(
                    'shelf_time'=>date("Y-m-d H:i:s"),
                    'complete_received_time'=>date("Y-m-d H:i:s"),
                );
                Service_ReceivingAttribute::update($updateRa,$this->_qcOrder['receiving_code'],"receiving_code");
            }
        }
    }

    /*@desc 释放箱子
     *
     */
    protected function releaseBox(){
        if($this->_isDivided){
            //释放箱子
            $updateBox = array(
                'receiving_code'=>'',
                'product_barcode'=>'',
                'product_id'=>'',
                'box_quantity'=>'0',
                'box_status'=>'0',
                'qc_code'=>'',
            );
            $result = Service_Box::update($updateBox,$this->_box['box_id'],"box_id");
            if(!$result){
                throw new Exception('释放箱子失败');
            }
        }
    }

    /*@desc 获取待上架数量
     *@param string $type 上架类型
     */
    public function getQtyPendedToShelve($type){
        $return = array('qty'=>0,'defectiveQty'=>0);
        if(empty($this->_qcOrder)){
            return $return;
        }
        if($type=='qc'){
            $return['qty'] = $this->_qcOrder['qc_quantity_sellable']-$this->_receivingDetail['rd_putaway_qty'];
            $defectiveQty = 0;
            if($this->_qcOrder['qc_quantity_unsellable']>0){//有不良品才去查询
                $batch = Service_InventoryBatch::getByCondition(array('receiving_code'=>$this->_qcOrder['receiving_code'],'product_id'=>$this->_qcOrder['product_id']));
                if($batch){
                    foreach($batch as $value){
                        $tmpArea = Service_Location::joinArea(array('lc_code'=>$value['lc_code'],'warehouse_id'=>$value['warehouse_id'],'wa_type'=>2));
                        if($tmpArea){
                            foreach($tmpArea as $v){
                                $defectiveQty += $value['ib_quantity']+$value['frozen'];
                            }
                        }
                    }
                }
            }
            $return['defectiveQty'] = $this->_qcOrder['qc_quantity_unsellable']-$defectiveQty;
        }else{
            $detail = Service_PutawayDetail::getByCondition(array('receiving_code'=>$this->_qcOrder['receiving_code'],'product_id'=>$this->_qcOrder['product_id'],'pd_status'=>1));
            $qty = 0;
            $defectiveQty = 0;
            foreach($detail as $value){
                switch($value['pd_product_type']){
                    case 1:
                        $qty += $value['pd_quantity'];
                        break;
                    case 2:
                        $defectiveQty += $value['pd_quantity'];
                        break;
                }
            }
            $return['qty'] = $this->_qcOrder['qc_quantity_sellable']-$qty;
            $return['defectiveQty'] = $this->_qcOrder['qc_quantity_unsellable']-$defectiveQty;
        }
        return $return;
    }

}