<?php
class Service_CeiveUseProcess extends Common_Service
{
	/**
	 * 添加借领用单
	 * @param unknown_type $row
	 * @param unknown_type $details
	 * @return boolean
	 */
	public static function createCeiveUse($row, $details) {
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try {
			$row['cu_code'] = Common_GetNumbers::getCode('cuCode', $row['warehouse_id'], 'CU');
			$row['cu_status'] = 0;
			$userAuth = new Zend_Session_Namespace('userAuthorization');
			//$row['warehouse_id'] = $userAuth->warehouseId;
			$row['cu_create_user_id'] = $userAuth->userId;
			$row['cu_add_time'] = date('Y-m-d H:i:s');
			$cu_id = Service_CeiveUse::add($row);
			foreach($details as $aDetail) {
				//$aDetail['cu_id'] = $cu_id;
				$aDetail['cu_code'] = $row['cu_code'];
				$aDetail['cud_add_time'] = date('Y-m-d H:i:s');
				$aDetail['cud_username'] = $row['cu_username'];
				$aDetail['cud_status'] = 0;
				$aDetail['cud_type'] = $row['cu_type'];
				Service_CeiveUseDetail::add($aDetail);
			}
			$db->commit();
		} catch ( Exception $e ) {
			$db->rollback();
			return FALSE;
		}
		return $row['cu_code'];
	}
	
	/**
	 * 修改借领用单
	 * @param unknown_type $cu_id
	 * @param unknown_type $row
	 * @param unknown_type $details
	 * @return boolean
	 */
	public static function modifyCeiveUse($cu_id, $row, $details) {
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try {
			$userAuth = new Zend_Session_Namespace('userAuthorization');
			$row['cu_update_user_id'] = $userAuth->userId;
			$row['cu_update_time'] = date('Y-m-d H:i:s');
			Service_CeiveUse::update($row, $cu_id);
			//Service_CeiveUseDetail::delete($cu_id, 'cu_id');
			Service_CeiveUseDetail::delete($row['cu_code'], 'cu_code');
			foreach($details as $aDetail) {
				//$aDetail['cu_id'] = $cu_id;
				$aDetail['cu_code'] = $row['cu_code'];
				$aDetail['cud_add_time'] = date('Y-m-d H:i:s');
				$aDetail['cud_username'] = $row['cu_username'];
				$aDetail['cud_status'] = 0;
				$aDetail['cud_type'] = $row['cu_type'];
				Service_CeiveUseDetail::add($aDetail);
			}
			$db->commit();
		} catch ( Exception $e ) {
			$db->rollback();
			return FALSE;
		}
		return $row['cu_code'];
	}

  /**
   * 删除借领用单
   * 
   * @param integer $cu_id 借领用单ID
   * @return array
   */
  public static function deleteCeiveUse($cu_id) {
    $cu_id = intval($cu_id);
    $ceiveUse = Service_CeiveUse::getByField($cu_id);
    $response = array(
      'state' => 0,
      'message' => '借领用单不存在'
    );

    if ($ceiveUse && 0 === (int) $ceiveUse['cu_status']) {
      $db = Common_Common::getAdapter();
      $db->beginTransaction();

      try {
        Service_CeiveUse::delete($cu_id);
        Service_CeiveUseDetail::delete($ceiveUse['cu_code'], 'cu_code');
        $db->commit();
        $response['state'] = 1;
        $response['message'] = (0 === (int) $ceiveUse['cu_type'] ? '借' : '领') . '用单【' . $ceiveUse['cu_code'] . '】删除成功';
      }
      catch (Exception $e) {
        $db->rollBack();
        $response['message'] = '系统出错，删除借领用单失败';
        $response['exceptionMessage'] = $e->getMessage();
      }
    }
    elseif ($ceiveUse) {
      $response['message'] = (0 === (int) $ceiveUse['cu_type'] ? '借' : '领') . '用单【' . $ceiveUse['cu_code'] . '】不是草稿状态，删除失败';
    }

    return $response;
  }

	/**
	 * 借领用单确认
	 * @param unknown_type $cu_id
	 * @throws Exception
	 * @return boolean
	 */
	public static function confirm($cu_id) {
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try {
			$aCeiveUse = Service_CeiveUse::getByField($cu_id);
			$detailList = Service_CeiveUseDetail::getByCondition(array('cu_code'=>$aCeiveUse['cu_code']));
			foreach($detailList as $detailRow) {
				$aProduct = Service_Product::getByField($detailRow['product_id']);
				if($aProduct['product_status']!=1) {
					throw new Exception('产品【'.$aProduct['product_barcode'].'】不是处于正常状态');
				}
				$aInventory = Service_ProductInventory::getByField($detailRow['product_id'], 'product_id');	
				if(empty($aInventory)) throw new Exception('产品【'.$aProduct['product_barcode'].'】找不到库存记录');
				if($detailRow['cud_quantity']>$aInventory['pi_sellable']) throw new Exception('产品【'.$aProduct['product_barcode'].'】库存不足');
				$ibCondition = array(
						'product_barcode'=>$detailRow['product_barcode'],
						'warehouse_id'=>$aCeiveUse['warehouse_id'],
						'ib_status'=>1,
						'ib_hold_status'=>0
				);
				$quantity = $detailRow['cud_quantity'];
				$batchList = Service_InventoryBatch::getByCondition($ibCondition);
				if(empty($batchList)) throw new Exception('产品【'.$aProduct['product_barcode'].'】找不到批次库存记录');
				foreach($batchList as $aBatch) {
					$aOutbound['warehouse_id'] = $aBatch['warehouse_id'];
					$aOutbound['lc_code'] = $aBatch['lc_code'];
					$aOutbound['reference_no'] = $aCeiveUse['cu_code'];
					$aOutbound['ib_id'] = $aBatch['ib_id'];
					$aOutbound['ibo_add_time'] = date('Y-m-d H:i:s');

          // 先去核销表找找，有没有用过该批次的记录，有的话统计使用的总量
          $reservedTotal = Service_InventoryBatchOutbound::getByCondition(array(
            'ib_id' => $aBatch['ib_id']
          ), 'SUM(ibo_quantity) AS total');

          // 批库存的数量需减去核销表中的用去的数量总量
          if ($reservedTotal) {
            $aBatch['ib_quantity'] -= (int) $reservedTotal[0]['total'];
          }

          // 批库存数量小于等于0，继续下一批吧
          if ($aBatch['ib_quantity'] <= 0) {
            continue ;
          }

					if($aBatch['ib_quantity']>=$quantity) {
						$aOutbound['ibo_quantity'] = $quantity;
						Service_InventoryBatchOutbound::add($aOutbound);
						//Service_InventoryBatch::update(array('ib_hold_status'=>2), $aBatch['ib_id']); // 借领用无需加锁
						$quantity = 0;
						break;
					} else {
						$aOutbound['ibo_quantity'] = $aBatch['ib_quantity'];
						Service_InventoryBatchOutbound::add($aOutbound);
						//Service_InventoryBatch::update(array('ib_hold_status'=>2), $aBatch['ib_id']); // 借领用无需加锁
						$quantity = $quantity - $aBatch['ib_quantity'];
						continue;
					}
				}
				if($quantity!=0) throw new Exception('产品【'.$aProduct['product_barcode'].'】库存不足');
				$piProccess = new Service_ProductInventoryProcess();
				$params = array(
						'product_id' => $detailRow['product_id'],
						'quantity' => $detailRow['cud_quantity'],
						'operationType' => 5,
						'warehouse_id' => $aCeiveUse['warehouse_id'],
						'reference_code' => $aCeiveUse['cu_code'], //操作单号
						'application_code' => '', //操作类型
						'note' => '借/领用确认'
				);
				$piResult = $piProccess->update($params);
				if($piResult['state']==0) throw new Exception('产品【'.$aProduct['product_barcode'].'】更新库存失败');
				$aDetail['cud_status'] = 1;
				$aDetail['cud_update_time'] = date('Y-m-d H:i:s');
				Service_CeiveUseDetail::update($aDetail,$detailRow['cud_id']);
			}
			$uCeiveUse['cu_status'] = 1;
			$uCeiveUse['cu_confirm_time'] = date('Y-m-d H:i:s');
			Service_CeiveUse::update($uCeiveUse, $cu_id);
			//提交事务
			$db->commit();
		} catch ( Exception $e ) {
			$db->rollback();
			return $e->getMessage();
		}
		return true;
	}
	
	/**
	 * 借用归还
	 * @author solar
	 * @param unknown_type $aCeiveUse
	 * @throws Exception
	 * @return boolean
	 */
	public static function revert($aCeiveUse) {
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try {
			$aQuantity = array();
			$iboList = Service_InventoryBatchOutbound::getByCondition(array('reference_no'=>$aCeiveUse['cu_code']));
			$cuDetail= Service_CeiveUseDetail::getByCondition(array('cu_code'=>$aCeiveUse['cu_code']));
			foreach($cuDetail as $key=>$val){
				$cuDetailParam	= array(
					'cud_back_quantity'	=> $val['cud_quantity'],
					'cud_status'=>2,
					'cud_back_time'=>date('Y-m-d H:i:s'),
					'cud_username'=>$aCeiveUse['cu_username'],
				);
				Service_CeiveUseDetail::update($cuDetailParam,$val['cud_id']);
			}
			foreach($iboList as $iboRow) {
				$ibRow = Service_InventoryBatch::getByField($iboRow['ib_id']);
				$product_id = $ibRow['product_id'];
				if(!isset($aQuantity[$product_id])) $aQuantity[$product_id] = 0;
				$aQuantity[$product_id] += $iboRow['ibo_quantity'];
				Service_InventoryBatchOutbound::delete($iboRow['ibo_id']);
				Service_InventoryBatchOutboundLog::log($iboRow, '借用归还');
				$updateRow['ib_hold_status'] = 0;
				$updateRow['ib_update_time'] = date('Y-m-d H:i:s');
				//Service_InventoryBatch::update($updateRow, $ibRow['ib_id']); // 竟然不加锁，自然也不用更新
			}
			$piProccess = new Service_ProductInventoryProcess();
			foreach($aQuantity as $product_id=>$quantity) {
				$params = array(
						'product_id' => $product_id,
						'quantity' => $quantity,
						'operationType' => 7,
						'warehouse_id' => $aCeiveUse['warehouse_id'],
						'reference_code' => $aCeiveUse['cu_code'], //操作单号
						'application_code' => '', //操作类型
						'note' => '借用归还'
				);
				$result = $piProccess->update($params);
				if($result['state']==0) throw new Exception('更新库存失败');
			}
			$uCeiveUse['cu_status'] = 2;
			$uCeiveUse['cu_back_time'] = date('Y-m-d H:i:s');
			Service_CeiveUse::update($uCeiveUse, $aCeiveUse['cu_id']);
			//提交事务
			$db->commit();
		} catch (Exception $e) {
			$db->rollback();
			return $e->getMessage();
		}
		return true;
	}
	
	/**
	 * 领用出库
	 * @param unknown_type $aCeiveUse
	 * @throws Exception
	 * @return boolean
	 */
	public static function takeOut($aCeiveUse) {
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try {
			$aQuantity = array();
			$iboList = Service_InventoryBatchOutbound::getByCondition(array('reference_no'=>$aCeiveUse['cu_code']));
			$cuDetail= Service_CeiveUseDetail::getByCondition(array('cu_code'=>$aCeiveUse['cu_code']));
			foreach($iboList as $iboRow) {
				$ibRow = Service_InventoryBatch::getByField($iboRow['ib_id']);
				$product_id = $ibRow['product_id'];
				if(!isset($aQuantity[$product_id])) $aQuantity[$product_id] = 0;
				$aQuantity[$ibRow['product_id']] += $iboRow['ibo_quantity'];
				Service_InventoryBatchOutbound::delete($iboRow['ibo_id']);
				Service_InventoryBatchOutboundLog::log($iboRow, '领用出库');
				$ib_quantity = $ibRow['ib_quantity']-$iboRow['ibo_quantity'];
				if($ib_quantity==0) {
					Service_InventoryBatch::delete($ibRow['ib_id']);
					$note = '领用出库删除批次库存';
				} else if($ib_quantity>0) {
					$updateRow['ib_quantity'] = $ib_quantity;
					//$updateRow['ib_hold_status'] = 0; // 竟然不加锁，自然也不用更新
					$updateRow['ib_update_time'] = date('Y-m-d H:i:s');
					Service_InventoryBatch::update($updateRow, $ibRow['ib_id']);
					$note = '领用出库修改批次库存';
				} else throw new Exception('库存异常，请通知系统管理员');
				Service_InventoryBatchLog::log($ibRow, $ibRow['ib_quantity'], $ib_quantity, $note);
			}
			foreach($cuDetail as $key=>$val){
				$cuDetailParam	= array(
					'cud_back_quantity'	=> $val['cud_quantity'],
					'cud_status'=>2,
					'cud_back_time'=>date('Y-m-d H:i:s'),
					'cud_username'=>$aCeiveUse['cu_username'],
				);
				Service_CeiveUseDetail::update($cuDetailParam,$val['cud_id']);
			}
			$piProccess = new Service_ProductInventoryProcess();
			foreach($aQuantity as $product_id=>$quantity) {
				$params = array(
						'product_id' => $product_id,
						'quantity' => $quantity,
						'operationType' => 6,
						'warehouse_id' => $aCeiveUse['warehouse_id'],
						'reference_code' => $aCeiveUse['cu_code'], //操作单号
						'application_code' => '', //操作类型
						'note' => '领用出库'
				);
				$result = $piProccess->update($params);
				if($result['state']==0) throw new Exception('更新库存失败');
			}
			$uCeiveUse['cu_status'] = 2;
			//$uCeiveUse['cu_finish_time'] = date('Y-m-d H:i:s');
			Service_CeiveUse::update($uCeiveUse, $aCeiveUse['cu_id']);
			//提交事务
			$db->commit();
		} catch (Exception $e) {
			$db->rollback();
			return $e->getMessage();
		}
		return true;
	}
	
	public function ceiveBackTransaction($cuId,$qty){

		$result = array (
				"ask" => 0,
				"message" => "Create Order Fail"
		);
		$db = Common_Common::getAdapter ();
		$db->beginTransaction ();
		try {
			$result = $this->ceiveBack ( $cuId,$qty );
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollback ();
			$result = array (
					"ask" => 0,
					"message" => $e->getMessage (),
					'errorCode' => $e->getCode ()
			);
		}
		return $result;
		
	}
	public function ceiveBack($cuId,$qty){
    	//更新归还时间，归还数量，领用状态
    	//更新库存数量，
    	//创建库存批次等
		$cuRow = Service_CeiveUse::getByField($cuId,'cu_id');
		if(empty($cuRow)){
			throw new Exception('Data Not Exists');
		}

		if($cuRow['cu_status']!=1){
			throw new Exception('Ceive Use Operation Fail,Status Forbidden,Only Confirm Status Could Operation');
		}
		$qty = trim($qty);
		if(empty($qty)||preg_match('/^[^0-9]+$/',$qty)){
			throw new Exception('Qty Empty Or Not Numeric');			
		}
		$rowUpdate = array('cu_back_date'=>date('Y-m-d H:i:s'),'cu_back_qty'=>$qty,'cu_status'=>2);
		
		if(!Service_CeiveUse::update($rowUpdate, $cuId,'cu_id')){
			throw new Exception('Inner Error.');
		}
		//该处还有其他逻辑。。。。。。
		
		$result = array (
				"ask" => 1,
				"message" => "Ceive Use Operation Success!",
		);
		
		return $result;
	}
	/**
	 * 校验输入数据
	 */
	public static function valid($row){
		$errors = array();
		if($row['warehouse_id']==''){
			$errors[] = "仓储必填";
		}
		if($row['cu_username']==''){
			$errors[] = "借领人必填";
		}
		if($row['cu_type']==''){
			$errors[] = "借领类型必填";
		}
		$cu_products = $row['cu_products'];
		if(!empty($cu_products)){
			foreach($cu_products as $keyp=>$vp){
				/* print_r($vp);
				var_dump(is_int($vp['qty']));
				var_dump(preg_match('/^[1-9]+[0-9]*$/i', $vp['qty']));
				exit; */
				if(!preg_match('/^[1-9]+[0-9]*$/i', $vp['qty']) || $vp['qty']<=0){
					$errors[] = '产品数量必须是大于0的数字';
				}
			}
		}else{
			$errors[] = "产品不能为空";
		}
		return $errors;
	}
	/**
	 * @author william-fan
	 * @todo 创建借领用单
	 */
	public static function createCeiveUseProcess($row){
		$result = array('state' => 0, 'message' => '创建借领用单失败', 'errorMessage' => array());
				
		$errors = self::valid($row);
		if(!empty($errors)){
			$result['errorMessage'] = $errors;
			return $result;
		}
		$db = Common_Common::getAdapter ();
		$db->beginTransaction ();
		try{
			$warehouseId = $row['warehouse_id'];
			$cu_code = Common_GetNumbers::getCode('cuCode', $warehouseId, 'CU'); // 借领用号
			$_userAuth = new Zend_Session_Namespace('userAuthorization');
						
			$ceiveUseRow = array(
				'warehouse_id'=>$warehouseId,
				'cu_username'=>$row['cu_username'],
				'cu_type'=>$row['cu_type'],
				'cu_create_user_id'=>isset($_userAuth->userId) ? $_userAuth->userId : '0',
				'cu_add_time'=>date('Y-m-d H:i:s'),
			);
			$ceiveUseRow['cu_code'] = $cu_code;
			
			Service_CeiveUse::add($ceiveUseRow);
			
			//ceive_use_detail
			$cu_products = $row['cu_products'];
			foreach($cu_products as $kedetail=>$vdetail){
				$ceiveUseDetailRow = array(
					'cu_code'=>$cu_code,
					'cud_type'=>'0',
					'product_id'=>$vdetail['product_id'],
					'product_barcode'=>$vdetail['product_barcode'],
					'cud_quantity'=>$vdetail['qty'],
					'cud_add_time'=>date('Y-m-d H:i:s',time()),			
				);
				Service_CeiveUseDetail::add($ceiveUseDetailRow);	
			}
			$result['state'] = '1';
			$result['message'] = '创建借领用单成功';
			$db->commit();
			//$db->rollback();
			return $result;
		} catch (Exception $e) {
            $db->rollBack();
            $result['errorMessage'][] = $e->getMessage();
        }
        return $result;
	}
	/**
	 * @author william-fan
	 * @todo 修改借领用单
	 */
	public static function updateCeiveUseProcess($row){
		$result = array('state' => 0, 'message' => '修改借领用单失败', 'errorMessage' => array());
		
		$errors = self::valid($row);
		if(!empty($errors)){
			$result['errorMessage'] = $errors;
			return $result;
		}
		$db = Common_Common::getAdapter ();
		$db->beginTransaction ();
		try{
			$warehouseId = $row['warehouse_id'];
			//$cu_code = Common_GetNumbers::getCode('cuCode', $warehouseId, 'CU'); // 借领用号
			$ceiveInfo = Service_CeiveUse::getByField($row['cu_id']);
			if(!empty($ceiveInfo)){
				if($ceiveInfo['cu_status']!='0'){
					throw new Exception('借领用单不为草稿,无法修改！');
				}
			}else{
				throw new Exception('借领用单无效！');
			}
			$_userAuth = new Zend_Session_Namespace('userAuthorization');
		
			$ceiveUseRow = array(
					'warehouse_id'=>$warehouseId,
					'cu_username'=>$row['cu_username'],
					'cu_type'=>$row['cu_type'],
					'cu_update_user_id'=>isset($_userAuth->userId) ? $_userAuth->userId : '0',
					'cu_update_time'=>date('Y-m-d H:i:s'),
			);
			//$ceiveUseRow['cu_code'] = $cu_code;
				
			Service_CeiveUse::update($ceiveUseRow,$row['cu_id']);

			//删除ceive_use_detail数据
			Service_CeiveUseDetail::delete($ceiveInfo['cu_code'],'cu_code');
			
			
			//ceive_use_detail
			$cu_products = $row['cu_products'];
			foreach($cu_products as $kedetail=>$vdetail){
				$ceiveUseDetailRow = array(
						'cu_code'=>$ceiveInfo['cu_code'],
						'cud_type'=>'0',
						'product_id'=>$vdetail['product_id'],
						'product_barcode'=>$vdetail['product_barcode'],
						'cud_quantity'=>$vdetail['qty'],
						'cud_add_time'=>date('Y-m-d H:i:s',time()),
				);
				Service_CeiveUseDetail::add($ceiveUseDetailRow);
			}
			$result['state'] = '1';
			$result['message'] = '修改借领用单成功';
			$db->commit();
			//$db->rollback();
			return $result;
		} catch (Exception $e) {
			$db->rollBack();
			$result['errorMessage'][] = $e->getMessage();
		}
		return $result;
	}
	/**
	 * @author william-fan
	 * @todo 用于借领用单的确认
	 */
	public static function confirmProcess($ceive_id){
		$result = array('state' => 0, 'message' => '确认借领用单失败', 'errorMessage' => array());
		
		$db = Common_Common::getAdapter ();
		$db->beginTransaction ();
		try{
			$ceiveInfo = Service_CeiveUse::getByField($ceive_id);
			if(!empty($ceiveInfo)){
				if($ceiveInfo['cu_status']!='0'){
					throw new Exception('借领用单不为草稿,不能确认！');
				}
			}else{
				throw new Exception('借领用单无效！');
			}
			$_userAuth = new Zend_Session_Namespace('userAuthorization');
			
			$ceiveDetail = Service_CeiveUseDetail::getByCondition(array('cu_code'=>$ceiveInfo['cu_code']));

			//print_r($ceiveDetail);
			if(!empty($ceiveDetail)){
				foreach($ceiveDetail as $keyp=>$valuep){
					/* $productInventory=Service_ProductInventory::getByField($valuep['product_id'],'product_id');
					if(!empty($productInventory)){
						if($productInventory['pi_sellable']<=$valuep['cud_quantity']){
							throw new Exception($valuep['product_barcode']."库存不足");
						}
					}else{
						throw new Exception($valuep['product_barcode']."没有库存");
					} */
					$inventory_batch = Service_InventoryBatch::getByCondition(array('product_id'=>$valuep['product_id']),'*',0,0,'ib_id asc');
					/* print_r($inventory_batch);
					exit; */
					if(!empty($inventory_batch)){
						$checkInventoryNumber = 0; //可用数量
						$yijieyongNumber = 0; //已借用数量
						$insertNumber = 0; //插入次数
						foreach($inventory_batch as $keyib=>$vib){
							$sumIBO = Service_InventoryBatchOutbound::sumQuantity($vib['ib_id']);
							$keyongNumber = $vib['ib_quantity']-$sumIBO; //批次数量减去已用数量
							$jieyongNumber = $valuep['cud_quantity']; //借用数量
							if($keyongNumber>0){
								if($keyongNumber>=$valuep['cud_quantity']){
									//直接插入
									$InventoryBbatchOutboundRow = array(
										'lc_code'=>$vib['lc_code'],
										'warehouse_id'=>$ceiveInfo['warehouse_id'],
										'reference_no'=>$ceiveInfo['cu_code'],
										'application_code'=>'ceive', //为借领用
										'ibo_quantity'=>$valuep['cud_quantity'],
										'ib_id'=>$vib['ib_id'],
										'ibo_add_time'=>date('Y-m-d H:i:s',time()),					
												
									);
									
									Service_InventoryBatchOutbound::add($InventoryBbatchOutboundRow);
								}else{
									//插入部分数量
									
									if($insertNumber<=0){
										$InventoryBbatchOutboundRow = array(
												'lc_code'=>$vib['lc_code'],
												'warehouse_id'=>$ceiveInfo['warehouse_id'],
												'reference_no'=>$ceiveInfo['cu_code'],
												'application_code'=>'ceive', //为借领用
												'ibo_quantity'=>$vib['ib_quantity'],
												'ib_id'=>$vib['ib_id'],
												'ibo_add_time'=>date('Y-m-d H:i:s',time()),
										);
										Service_InventoryBatchOutbound::add($InventoryBbatchOutboundRow);
										$insertNumber++;
										$yijieyongNumber+=$vib['ib_quantity'];
									}else{

										$yijieyongNumber+=$vib['ib_quantity'];
											
										$nowjieyong = $valuep['cud_quantity']-$yijieyongNumber;
											$InventoryBbatchOutboundRow = array(
												'lc_code'=>$vib['lc_code'],
												'warehouse_id'=>$ceiveInfo['warehouse_id'],
												'reference_no'=>$ceiveInfo['cu_code'],
												'application_code'=>'ceive', //为借领用
												'ibo_quantity'=>$vib['ib_quantity'],
												'ib_id'=>$vib['ib_id'],
												'ibo_add_time'=>date('Y-m-d H:i:s',time()),
										);
										Service_InventoryBatchOutbound::add($InventoryBbatchOutboundRow);

									}
									
								}
								$checkInventoryNumber+=$keyongNumber;
							}else{
								$keyongNumber = 0;
							}
						}
						if($checkInventoryNumber<$valuep['cud_quantity']){
							throw new Exception($valuep['product_barcode']."库存不足");
						}
						
						$productInventory=Service_ProductInventory::getByField($valuep['product_id'],'product_id');
						if(!empty($productInventory)){
							$productInventoryRow = array(
								'pi_hold'=>$productInventory['pi_hold']+$valuep['cud_quantity'],
								'pi_sellable'=>$productInventory['pi_sellable']-$valuep['cud_quantity'],
								'pi_update_time'=>date('Y-m-d H:i:s',time()),		
							);
							Service_ProductInventory::update($productInventoryRow, $productInventory['pi_id']);
						}
						
					}else{
						throw new Exception($valuep['product_barcode']."没有批次库存");
					}
					
				}
			}
      $date = date('Y-m-d H:i:s');
			$ceiveRow = array(
				'cu_status'=>'1',
				'cu_update_time'=>$date,
        'cu_confirm_time' => $date
			);
			Service_CeiveUse::update($ceiveRow,$ceiveInfo['cu_id']);
			
			$result['state'] = '1';
			$result['message'] = '确认借领用单成功';
			$result['cu_code'] = $ceiveInfo['cu_code'];
			$db->commit();
			//$db->rollback();
			return $result;
		} catch (Exception $e) {
			$db->rollBack();
			$result['message'] = $e->getMessage();
			$result['errorMessage'][] = $e->getMessage();
		}
		return $result;
	}
	
	/**
	 * @author william-fan
	 * @todo 借领用单出库
	 */
	public static function chukuProcess($ceive_code,$product_barcode){
		$result = array('state' => 0, 'message' => '领用出库失败', 'errorMessage' => array());
		$db = Common_Common::getAdapter ();
		$db->beginTransaction ();
		try{
			$ceiveInfo = Service_CeiveUse::getByField($ceive_code,'cu_code');
			if(!empty($ceiveInfo)){
				if($ceiveInfo['cu_status']!='1'){
					throw new Exception('领用单状态不对');
				}
        elseif (1 !== (int) $ceiveInfo['cu_type']) {
          throw new Exception('【' . $ceive_code . '】不是领用单');
        }
			}else{
				throw new Exception('领用单无效');
			}
			$ceiveDetail = Service_CeiveUseDetail::getByCondition(array('cu_code'=>$ceive_code,'product_barcode'=>$product_barcode));
			if(!empty($ceiveDetail)){
				$ceive_detail = $ceiveDetail[0];
				if($ceive_detail['cud_status']!='0'){
					throw new Exception($product_barcode.'状态不对');
				}
				$ceiveUseDetailRow = array(
					'cud_status'=>'2',
					'cud_update_time'=>date('Y-m-d H:i:s',time())	
				);
				Service_CeiveUseDetail::update($ceiveUseDetailRow, $ceive_detail['cud_id']);
			}else{
				throw new Exception($product_barcode.'不属于借领用单');
			}
			$ceiveNotDetail = Service_CeiveUseDetail::getByCondition(array('cu_code'=>$ceive_code,'not_product_barcode'=>$product_barcode));
			$updateCeive = true;
			if(!empty($ceiveNotDetail)){
				foreach($ceiveNotDetail as $kcn=>$vcn){
					if($vcn['cud_status']!='2'){
						$updateCeive = false;
					}
				}	
			}
			if($updateCeive){
				$ceiveRow = array(
					'cu_status'=>'2',
					'cu_update_time'=>date('Y-m-d H:i:s',time()),	
				);
				Service_CeiveUse::update($ceiveRow, $ceiveInfo['cu_id']);
			}
			

			if($updateCeive){
				$ceiveDetailForProduct = Service_CeiveUseDetail::getByCondition(array('cu_code'=>$ceive_code));
				if(!empty($ceiveDetailForProduct)){
					foreach($ceiveDetailForProduct as $keydp=>$vdp){
						$productInventory=Service_ProductInventory::getByField($vdp['product_id'],'product_id');
						if(!empty($productInventory)){
							$productInventoryRow = array(
									'pi_hold'=>$productInventory['pi_hold']-$vdp['cud_quantity'],
									'pi_shipped'=>$productInventory['pi_shipped']+$vdp['cud_quantity'],
									'pi_update_time'=>date('Y-m-d H:i:s',time()),
							);
							Service_ProductInventory::update($productInventoryRow, $productInventory['pi_id']);
						}
					}
				}
			}
			$result['state'] = '1';
			$result['message'] = '出库成功';
			$db->commit();
			//$db->rollback();
		} catch (Exception $e) {
			$db->rollBack();
			$result['message'] = $e->getMessage();
			$result['errorMessage'][] = $e->getMessage();
		}
		//print_r($result);
		return $result;
	}
	
	/**
	 * @author william-fan
	 * @todo 归还操作
	 */
	public static function guihuanProcess($ceive_code,$product_barcode,$qty){
		$result = array('state' => 0, 'message' => '借领用归还失败', 'errorMessage' => array());
		$db = Common_Common::getAdapter ();
		$db->beginTransaction ();
		try{
			$ceiveInfo = Service_CeiveUse::getByField($ceive_code,'cu_code');
			if(!empty($ceiveInfo)){
				if($ceiveInfo['cu_status']!='1'){
					throw new Exception('借领用单状态不对');
				}
			}else{
				throw new Exception('借领用单无效');
			}
			if(empty($qty)||preg_match('/^[^0-9]+$/',$qty)){
				throw new Exception('归还数量比为数字');
			}
			$ceiveDetail = Service_CeiveUseDetail::getByCondition(array('cu_code'=>$ceive_code,'product_barcode'=>$product_barcode));
			if(!empty($ceiveDetail)){
				$ceive_detail = $ceiveDetail[0];
				if($ceive_detail['cud_status']!='2'){
					throw new Exception($product_barcode.'未完成不能归还');
				}
				if($qty>=$ceive_detail['cud_quantity']){
					/* $ceiveUseDetailRow = array(
							'cud_status'=>'2',
							'cud_update_time'=>date('Y-m-d H:i:s',time())
					); */

				}else{
					
				}
				
				$cubb_code = Common_GetNumbers::getCode('cubb_code', $ceiveInfo['warehouse_id'], 'GH'); // 归还单
				$_userAuth = new Zend_Session_Namespace('userAuthorization');
					
					
					
				$ceive_use_back_batchRow = array(
						'cu_code'=>$ceive_detail['cu_code'],
						'cud_id'=>$ceive_detail['cud_id'],
						'cubb_status'=>'0',
						'cubb_username'=>isset($_userAuth->userId) ? $_userAuth->userId : '0',
						'cubb_add_user_id'=>isset($_userAuth->userId) ? $_userAuth->userId : '0',
						'product_id'=>$ceive_detail['product_id'],
						'product_barcode'=>$ceive_detail['product_barcode'],
						'cubb_back_quantity'=>$qty,
						'cubb_add_time'=>date('Y-m-d H:i:s',time()),
				);
				$ceive_use_back_batchRow['cubb_code'] = $cubb_code;
				Service_CeiveUseBackBatch::add($ceive_use_back_batchRow);
				
				//Service_CeiveUseDetail::update($ceiveUseDetailRow, $ceive_detail['cud_id']);
			}else{
				throw new Exception($product_barcode.'不属于该借领用单');
			}
			$ceiveNotDetail = Service_CeiveUseDetail::getByCondition(array('cu_code'=>$ceive_code,'not_product_barcode'=>$product_barcode));
			$updateCeive = true;
			if(!empty($ceiveNotDetail)){
				foreach($ceiveNotDetail as $kcn=>$vcn){
					if($vcn['cud_status']!='2'){
						$updateCeive = false;
					}
				}
			}
			if($updateCeive){
				$ceiveRow = array(
						'cu_status'=>'2',
						'cu_update_time'=>date('Y-m-d H:i:s',time()),
				);
				Service_CeiveUse::update($ceiveRow, $ceiveInfo['cu_id']);
			}
				
		
			if($updateCeive){
				$ceiveDetailForProduct = Service_CeiveUseDetail::getByCondition(array('cu_code'=>$ceive_code));
				if(!empty($ceiveDetailForProduct)){
					foreach($ceiveDetailForProduct as $keydp=>$vdp){
						$productInventory=Service_ProductInventory::getByField($vdp['product_id'],'product_id');
						if(!empty($productInventory)){
							$productInventoryRow = array(
									'pi_hold'=>$productInventory['pi_hold']-$vdp['cud_quantity'],
									'pi_shipped'=>$productInventory['pi_shipped']+$vdp['cud_quantity'],
									'pi_update_time'=>date('Y-m-d H:i:s',time()),
							);
							Service_ProductInventory::update($productInventoryRow, $productInventory['pi_id']);
						}
					}
				}
			}
			$result['state'] = '1';
			$result['message'] = '创建归还单成功';
			$db->commit();
			//$db->rollback();
		} catch (Exception $e) {
			$db->rollBack();
			$result['message'] = $e->getMessage();
			$result['errorMessage'][] = $e->getMessage();
		}
		//print_r($result);
		return $result;
	}
	/**
	 * @author william-fan
	 * @todo 归还入库单
	 */
	public static function scanProcess($cubb_code){
		$result = array('state' => 0, 'message' => '归还单确认失败', 'errorMessage' => array());
		$db = Common_Common::getAdapter ();
		$db->beginTransaction ();
		$datetime = date('Y-m-d H:i:s');
		try{
			$ceiveuserbatchInfo = Service_CeiveUseBackBatch::getByField($cubb_code,'cubb_code');
			if(!empty($ceiveuserbatchInfo)){
				if($ceiveuserbatchInfo['cubb_status']=='1'){
					throw new Exception($cubb_code.'已归还');
				}
			}else{
				throw new Exception($cubb_code.'归还单不存在');
			}
			$ceiveuserbatchRow = array(
				'cubb_status'=>'1',
			);
			Service_CeiveUseBackBatch::update($ceiveuserbatchRow, $ceiveuserbatchInfo['cubb_id']);
			$ceiveDetail=Service_CeiveUseDetail::getByField($ceiveuserbatchInfo['cud_id']);
			if(!empty($ceiveDetail)){
				if($ceiveDetail['cud_quantity']==$ceiveuserbatchInfo['cubb_back_quantity']){
					//数量一致
					$ceiveDetailRow = array(
						'cud_back_quantity'=>$ceiveuserbatchInfo['cubb_back_quantity'],
						'cud_status'=>'2',
						'cud_back_time'=>$datetime,
						'cud_update_time'=>$datetime,			
					);
				}else{
					//数量不一致 部分归还
					$ceiveDetailRow = array(
							'cud_back_quantity'=>$ceiveuserbatchInfo['cubb_back_quantity'],
							'cud_status'=>'1',
							'cud_back_time'=>$datetime,
							'cud_update_time'=>$datetime,
					);
				}
				Service_CeiveUseDetail::update($ceiveDetailRow, $ceiveDetail['cud_id']);
				//$ceiveDetail['']
			}
			//$db->rollBack();
			$db->commit();
			$result['message'] = "归还单{$cubb_code}确认成功";
			$result['state'] = '1';
		}catch (Exception $e) {
			$db->rollBack();
			$result['message'] = $e->getMessage();
			$result['errorMessage'][] = $e->getMessage();
		}
		//print_r($result);
		return $result;
	}
	/**
	 * @author william-fan
	 * @todo 用于整单销毁
	 */
	public static function xiaohuiAllProcess($ceive_id){
		$result = array('state' => 0, 'message' => '销毁借领用单失败', 'errorMessage' => array());
		$db = Common_Common::getAdapter ();
		$db->beginTransaction ();
		$datetime = date('Y-m-d H:i:s');
		try{
			$ceiveInfo = Service_CeiveUse::getByField($ceive_id);
			if(!empty($ceiveInfo)){
				if($ceiveInfo['cu_status']!='2'){
					throw new Exception($ceiveInfo['cu_code'].'状态不为已出库无法销毁');
				}
			}else{
				throw new Exception('该借领用单不存在');
			}
			$ceiveDetailRow = array(
				'cud_type'=>'1',
				'cud_update_time'=>date('Y-m-d H:i:s')	
			);
			Service_CeiveUseDetail::update($ceiveDetailRow,$ceiveInfo['cu_code'],'cu_code');
			//$db->rollBack();
			$db->commit();
			$result['message'] = "借领用单{$ceiveInfo['cu_code']}销毁成功";
			$result['state'] = '1';
		}catch (Exception $e) {
			$db->rollBack();
			$result['message'] = $e->getMessage();
			$result['errorMessage'][] = $e->getMessage();
		}
		//print_r($result);
		return $result;
	}
	/**
	 * @author william-fan
	 * @todo 用于单个单销毁
	 */
	public static function xiaohuiSingleProcess($cud_id){
		$result = array('state' => 0, 'message' => '销毁借领用单失败', 'errorMessage' => array());
		$db = Common_Common::getAdapter ();
		$db->beginTransaction ();
		$datetime = date('Y-m-d H:i:s');
		try{
			$ceiveDetailInfo = Service_CeiveUseDetail::getByField($cud_id);
			if(!empty($ceiveDetailInfo)){
				if($ceiveDetailInfo['cud_status']!='2'){
					throw new Exception($ceiveDetailInfo['cu_code'].'状态不为已出库无法销毁');
				}
			}else{
				throw new Exception('该借领用单不存在');
			}
			$ceiveDetailRow = array(
					'cud_type'=>'1',
					'cud_update_time'=>date('Y-m-d H:i:s')
			);
			Service_CeiveUseDetail::update($ceiveDetailRow,$ceiveDetailInfo['cud_id']);
			//$db->rollBack();
			$db->commit();
			$result['message'] = "借领用单{$ceiveDetailInfo['cu_code']}销毁成功";
			$result['state'] = '1';
		}catch (Exception $e) {
			$db->rollBack();
			$result['message'] = $e->getMessage();
			$result['errorMessage'][] = $e->getMessage();
		}
		//print_r($result);
		return $result;
	}
	
}