<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 14-7-21
 * Time: 下午6:47
 * To change this template use File | Settings | File Templates.
 */
class Service_BoxUpShelf extends Common_Service
{
    protected $_putawayCode = null;
    protected $_putaway = array();
    protected $_putawayDetail = array();
    protected $_userWarehouseId = 0;
    protected $_userId = 0;
    protected $_errorArr = array();
    protected $_params = array();
    protected $_date = '';
    protected $_qcOrder = null;
    protected $_box = null;

    protected function setWarehouse(){
        $this->_userWarehouseId = Service_User::getUserWarehouseId();
    }

    protected function setUser(){
        $this->_userId = Service_User::getUserId();
    }

    public function __construct()
    {
        $this->setUser();
        $this->setWarehouse();
        $this->_date = date('Y-m-d H:i:s');
    }

    /*pda分箱
     * @author Gilbert
     * @date 2015-08-27
     * @param array $params
     * @return array
     */
    public function pdaDivision($params){
        $return = array('state'=>0,'message'=>'');
        $this->setWarehouse();
        $this->setUser();
        $this->checkPdaParams($params);
        if(!empty($this->_errorArr)){
            $return['message'] = implode(',',$this->_errorArr);
            return $return;
        }
        $putAwayOrder = Service_Putaway::getByCondition(array('receiving_code'=>$this->_qcOrder['receiving_code']));
        if(!$putAwayOrder){
            $return['message'] = '未生成上架单信息';
            return $return;
        }
        $db = Service_QualityControl::getModelInstance()->getAdapter();
        $db->beginTransaction();
        try{
            //检查是否生成默认的detail信息了（没有箱号的）,如果有，就清除
            $detailRows = Service_PutawayDetail::getByCondition(array('putaway_code'=>$putAwayOrder[0]['putaway_code'],'qc_code'=>$this->_qcOrder['qc_code']),array('pd_id','box_code','pd_lot_number'));
            $maxLotNumber = 1;
            $flag = false;
            if($detailRows){
                foreach($detailRows as $value){
                    //未分箱的情况
                    if($value['box_code']){
                        $flag = true;
                        //取出最大批次号
                        if($value['pd_lot_number']>$maxLotNumber){
                            $maxLotNumber = $value['pd_lot_number'];
                        }
                    }else{
                        $result = Service_PutawayDetail::delete($value['pd_id'],'pd_id');
                        if(!$result){
                            throw new Exception('清除历史上架信息失败');
                        }
                    }
                }
            }
            //如果存在箱号，说明是做过分箱的，就算QC有产品上架也可以继续分箱;否则不能再分箱;
            if(!$flag){
                $rows = Service_InventoryBatch::getByCondition(array('receiving_code'=>$this->_qcOrder['receiving_code'],'product_id'=>$this->_qcOrder['product_id'],'reference_no'=>$this->_qcOrder['qc_code']));
                //如果上架了 就不能再分箱
                if($rows){
                    throw new Exception('质检单已有产品上架了，不能再进行分箱');
                }
            }
            $add = array(
                'putaway_id' => $putAwayOrder[0]['putaway_id'],
                'putaway_code' => $putAwayOrder[0]['putaway_code'],
                'qc_code' => $this->_qcOrder['qc_code'],
                'box_code'=>$this->_params['box'],
                'receiving_code' => $putAwayOrder[0]['receiving_code'],
                'pd_type' => 2,
                'product_barcode' => $this->_qcOrder['product_barcode'],
                'product_id' => $this->_qcOrder['product_id'],
                'pd_quantity' =>$this->_params['division_number'],
                'pd_lot_number' => $maxLotNumber+1,
                'warehouse_id' => $this->_qcOrder['warehouse_id'],
                'pd_add_time' => $this->_date,
                'pd_product_type'=>$this->_params['product_type']
            );
            $result = Service_PutawayDetail::add($add);
            if(!$result){
                throw new Exception('生成上架信息失败');
            }

            $update = array(
                'box_status'=>2,
                'qc_code'=>$this->_qcOrder['qc_code'],
                'receiving_code'=>$this->_qcOrder['receiving_code'],
                'product_barcode'=>$this->_qcOrder['product_barcode'],
                'product_id'=>$this->_qcOrder['product_id'],
                'box_quantity'=>$this->_params['division_number'],
                'box_update_time'=>$this->_date
            );
            $result = Service_Box::update($update,$this->_box['box_id']);
            if(!$result){
                throw new Exception('更新箱子状态失败');
            }

            //分箱日志
            $log = array(
                'box_code'=>$this->_params['box'],
                'qc_code'=>$this->_qcOrder['qc_code'],
                'dl_quantity'=>$this->_params['division_number'],
                'dl_product_type'=>$this->_params['product_type'],
                'dl_note'=>'PDA分箱',
                'dl_operator_id'=>$this->_userId,
                'dl_add_time'=>$this->_date,
                'dl_ip'=>Common_Common::getIP(),
            );
            $result = Service_DivisionLog::add($log);
            if(!$result){
                throw new Exception('写入分箱日志失败');
            }

            $db->commit();
            $return['state'] = 1;
            $return['message'] = '分箱成功';
        }catch (Exception $e){
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        return $return;
    }

    protected function trimParams($params){
        foreach($params as $key=>$value){
            $params[$key] = is_scalar($value)?trim($value):$value;
        }
        return $params;
    }

    protected function checkPdaParams($params){
        if(!is_array($params) || empty($params)){
            $this->_errorArr[] = '缺少分箱信息';
            return;
        }

        $params = $this->trimParams($params);

        if(!isset($params['product_type']) || !is_numeric($params['product_type']) || !in_array($params['product_type'],array(1,2))){
            $this->_errorArr[] = '请选择正确的产品类型';
            return;
        }
        if(!isset($params['qc_code']) || empty($params['qc_code'])){
            $this->_errorArr[] = '质检单号为空';
            return;
        }else{
            $qcRow = Service_QualityControl::getByField($params['qc_code'],'qc_code');
            if($qcRow instanceof Zend_Db_Table_Row){
                $qcRow = $qcRow->toArray();
            }
            if(!$qcRow){
                $this->_errorArr[] = '质检单不存在';
                return;
            }
            if($qcRow['qc_status'] != 1){
                $this->_errorArr[] = '质检单不是质检完成状态，不能分箱';
                return ;
            }
            if($qcRow['warehouse_id'] != $this->_userWarehouseId){
                $this->_errorArr[] = '质检单不属于当前仓库';
                return ;
            }
            $this->_qcOrder = $qcRow;
        }
        if(!isset($params['box']) || empty($params['box'])){
            $this->_errorArr[] = '箱子为空';
            return;
        }else{
            $result = $this->checkBox($params['box']);
            if($result['ask']==0){
                $this->_errorArr[] = $result['msg'];
                return;
            }
            $this->_box = $result['data'];
        }
        //检查分箱数量
        if(!isset($params['division_number']) || !preg_match('/^[1-9]+[0-9]*$/',$params['division_number'])){
            $this->_errorArr[] = '数量必须是大于0的整数';
            return;
        }else{
            $passQty = 0;
            $defectiveQty = 0;
            $boxCode = array();
            //统计分箱数
            $detail = Service_PutawayDetail::joinBox(array('qc_code'=>$this->_qcOrder['qc_code'],'receiving_code'=>$this->_qcOrder['receiving_code']));
            if($detail){
                foreach($detail as $value){
                    //只检查有箱号的
                    if($value['box_code']){
                        switch($value['pd_product_type']){
                            case 1://合格品
                                $passQty += $value['pd_quantity'];
                                break;
                            case 2://不良品
                                $defectiveQty += $value['pd_quantity'];
                                break;
                            default:
                                $this->_errorArr[] = '箱子【'.$value['box_code'].'】的产品类型错误';
                                return;
                                break;
                        }
                    }
                }
            }
            if($params['product_type']==1){
                if($this->_qcOrder['qc_quantity_sellable']<($passQty+$params['division_number'])){
                    $this->_errorArr[] = '只有 '.($this->_qcOrder['qc_quantity_sellable']-$passQty).' 个合格品能用于分箱';
                    return;
                }
            }else{
                if($this->_qcOrder['qc_quantity_unsellable']<($defectiveQty+$params['division_number'])){
                    $this->_errorArr[] = '只有 '.($this->_qcOrder['qc_quantity_unsellable']-$defectiveQty).' 个不良品能用于分箱';
                    return;
                }
            }
        }
        $this->_params = $params;
    }
    /*检查箱号
     * @author Gilbert
     * @date 2015-08-27
     * @param string $box 箱号
     * @param string $receivingCode 入库单
     * @param string $qcCode 质检单
     * @return array
     *
     */
    public function checkBox($box,$receivingCode='',$qcCode=''){
        $return = array('ask'=>0,'msg'=>'');
        if(empty($box)){
            $return['msg'] = "箱号不能为空";
            return $return;
        }
        $boxRow = Service_Box::getByField($box,'box_code');
        if($boxRow instanceof Zend_Db_Table_Row){
            $boxRow = $boxRow->toArray();
        }
        if(empty($boxRow)){
            $return['msg'] = "箱号不存在";
            return $return;
        }
        if($boxRow['box_status']=="2"){
            $return['msg'] = "箱子已锁";
            return $return;
        }
        if($boxRow['box_status']=="1"){

        }
        if($boxRow['warehouse_id']!=$this->_userWarehouseId){
            $return['msg'] = "箱子不属于当前仓";
            return $return;
        }
        $return['ask'] = 1;
        $return['msg'] = 'Success';
        $return['data'] = $boxRow;
        return $return;
    }
}
