<?php
class Ceive_UseController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "ceive/views/ceive_use/";
        $this->serviceClass = new Service_CeiveUse();
    }

    public function listAction()
    {
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $params = $this->_request->getParams();

            $condition = $this->serviceClass->getMatchFields($params);

            $count = $this->serviceClass->getByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                    
                'cu_code',
                'warehouse_id',
                'cu_username',
                'cu_status',
                'cu_type',
                'cu_create_user_id',
                'cu_add_time',
                'cu_confirm_time',
                'cu_back_time',
                'cu_update_time',
                'cu_id',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('cu_id desc'));
				if(!empty($rows)){
					foreach($rows as $key=>$vce){
						$condition = array(
							'cu_code'=>$vce['E1'],
						);
						$ceiveDetails = Service_CeiveUseDetail::getByCondition($condition);
						foreach($ceiveDetails as $kdetail=>$vdetail){
							$product = Service_Product::getByField($vdetail['product_id']);
              $categoryInfo = Service_ProductCategory::getByField((int) $product['pc_id']);
							$ceiveDetails[$kdetail]['product_sku'] = $product['product_sku'];
							$ceiveDetails[$kdetail]['product_title'] = $product['product_title'];
              $ceiveDetails[$kdetail]['category_name'] = empty($categoryInfo) ? '' : $categoryInfo['pc_name'];
						}
						$rows[$key]['ceiveDetail'] = $ceiveDetails;
					}
				}
                $return['ceive_status'] = Common_Status::ceiveUseStatus('auto');
                $return['ceive_types'] = Common_Status::ceiveUseType('auto');
                $return['kvWarehouse'] = Common_DataCache::getWarehouseSimple();
                $return['kvUser'] = Service_User::getKV();
                $return['kvUserCode'] = Service_User::getKV(0, 0, 1);
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->warehouseGroup = Common_DataCache::getWarehouse();
        echo Ec::renderTpl($this->tplDirectory . "ceive_use_index.tpl", 'layout');
    }

  /**
   * 获取借领用单信息
   */
  public function getAction() {
    $response = array('state' => 0);
    $cu_id = (int) $this->_request->getParam('cu_id', 0);
    
    if ($cu_id) {
      $ceiveUse = Service_CeiveUse::getByField($cu_id);

      if ($ceiveUse) {
        $response['state'] = 1;
        $response['data'] = $ceiveUse;
        $response['detail'] = array();
        $detail = Service_CeiveUseDetail::getByCondition(array('cu_code' => $ceiveUse['cu_code']));
        $response['user'] = array('user_id' => '', 'user_code' => '', 'user_name' => '');
        $user = Service_User::getByField($ceiveUse['cu_username'], 'user_code');

        if ($detail) {
          foreach ($detail as $key => $item) {
            $product = Service_Product::getByField($item['product_id']);

            if ($product) {
              $detail[$key]['product_title'] = $product['product_title'];
            }
            else {
              $detail[$key]['product_title'] = '';
            }
          }

          $response['detail'] = $detail;
        }

        if ($user) {
          $response['user']['user_code'] = $user['user_code'];
          $response['user']['user_id'] = $user['user_id'];
          $response['user']['user_name'] = $user['user_name'];
        }
      }
      else {
        $response['message'] = '借/领用单不存在';
      }
    }
    else {
      $response['message'] = '非法请求';
    }

    exit(Zend_Json::encode($response));
  }

  /**
   * 创建编辑借领用单
   */
  public function editAction() {
    $response = array('state' => 0, 'message' => '非法请求');

    if ($this->_request->isPost()) {
      $errorMessage = array();
      $warehouseGroup = Common_DataCache::getWarehouse();
      $cu_id = intval($this->_request->getPost('cu_id', 0));
      $cu_code = '';
      $warehose_id = intval($this->_request->getPost('warehouse_id', 0));
      $cu_type = trim($this->_request->getPost('cu_type', ''));
      $cu_username = trim($this->_request->getPost('cu_username', ''));
      $product_ids = $this->_request->getPost('product_ids', array());
      $product_ids = is_array($product_ids) ? $product_ids : array();
      $details = array();

      // 编辑情形，验证cu_id的有效性
      if ($cu_id) {
        $ceiveUse = Service_CeiveUse::getByField($cu_id, 'cu_id');

        if (!$ceiveUse) {
          exit(Zend_Json::encode($response));
        }

        $cu_code = $ceiveUse['cu_code'];
      }

      // 只提取仓库ID
      foreach ($warehouseGroup as $key => $warehouse) {
        $warehouseGroup[$key] = intval($warehouse['warehouse_id']);
      }

      // 验证仓库有效性
      if (!in_array($warehose_id, $warehouseGroup, TRUE)) {
        $errorMessage[] = '仓库必填';
      }

      // 验证类型有效性：0借用，1领用
      if (!in_array($cu_type, array('0', '1'), TRUE)) {
        $errorMessage[] = '类型必填';
      }

      // 验证借领用人的有效性
      if ('' === $cu_username || !Service_User::getByField($cu_username, 'user_code')) {
        $errorMessage[] = '借领用人必填';
      }

      // 验证是否有传递产品过来
      if (empty($product_ids)) {
        $errorMessage[] = '产品必填';
      }

      // 验证所选择产品的有效性
      foreach ($product_ids as $product_id) {
        $product = Service_Product::getByField($product_id, 'product_id');

        if ($product) {
          $cud_quantity = trim($this->_request->getPost('num' . $product_id, ''));

          // 验证产品数量有效性
          if (preg_match('/^[1-9][0-9]*$/', $cud_quantity)) {
            $details[] = array(
              'product_id' => $product['product_id'],
              'product_barcode' => $product['product_barcode'],
              'cud_quantity' => (int) $cud_quantity
            );
          }
          else {
            $errorMessage[] = '产品【' . $product['product_barcode'] . '】的数量不是正整数';
          }
        }
        else {
          $errorMessage[] = '不存在ID为' . $product_id . '的产品';
        }
      }

      if (!empty($errorMessage)) { // 数据验证都不通过
        $response['message'] = join($errorMessage, '；');
      }
      elseif ($cu_id) { // 修改借领用单
        $return = Service_CeiveUseProcess::modifyCeiveUse($cu_id, array(
          'warehouse_id' => $warehose_id,
          'cu_type' => (int) $cu_type,
          'cu_username' => $cu_username,
          'cu_code' => $cu_code
        ), $details);

        if (FALSE === $return) {
          $response['message'] = '修改借领用单时发生系统错误';
        }
        else {
          $response['state'] = 1;
          $response['message'] = ('0' == $cu_type ? '借用' : '领用') . '单【' . $return . '】修改成功';
        }
      }
      else { // 创建借领用单
        $return = Service_CeiveUseProcess::createCeiveUse(array(
          'warehouse_id' => $warehose_id,
          'cu_type' => (int) $cu_type,
          'cu_username' => $cu_username
        ), $details);

        if (FALSE === $return) {
          $response['message'] = '创建借领用单时发生系统错误';
        }
        else {
          $response['state'] = 1;
          $response['message'] = ('0' == $cu_type ? '借用' : '领用') . '单【' . $return . '】创建成功';
        }
      }
    }

    exit(Zend_Json::encode($response));
  }

  /**
   * 删除借领用单
   */
  public function deleteAction() {
    $response = array(
      'state' => 0,
      'message' => '非法请求'
    );

    if ($this->_request->isPost()) {
      $cu_id = intval($this->_request->getPost('paramId', 0));

      if ($cu_id) {
        $response = Service_CeiveUseProcess::deleteCeiveUse($cu_id);
      }
    }

    exit(Zend_Json::encode($response));
  }

  /**
   * 借领用单确认
   */
  public function confirmAction() {
    $response = array(
      'state' => 0,
      'message' => '非法请求',
      'data' => array()
    );

    if ($this->_request->isPost()) {
      $cu_id = intval($this->_request->getPost('cu_id', 0));
      $ceiveUse = Service_CeiveUse::getByField($cu_id);

      if ($ceiveUse && 0 === (int) $ceiveUse['cu_status']) {
        $return = Service_CeiveUseProcess::confirm($cu_id);

        if (TRUE === $return) {
          $response['state'] = 1;
          $response['message'] = '借领用单【' . $ceiveUse['cu_code'] . '】确认成功';
          $response['data'] = array(
            'cu_id' => $cu_id,
            'cu_code' => $ceiveUse['cu_code']
          );
        }
        else {
          $response['message'] = $return;
        }
      }
      elseif ($ceiveUse) {
        $response['message'] = '借领用单【' . $ceiveUse['cu_code'] . '】不是草稿状态';
      }
      else {
        $response['message'] = '借领用单不存在';
      }
    }

    exit(Zend_Json::encode($response));
  }

  /**
   * 借领用出库归还
   */
  public function finishAction() {
    $cu_id = $this->_request->getParam('cu_id','');
    $aCeiveUse = Service_CeiveUse::getByField($cu_id);

    if (empty($aCeiveUse)) {
      exit('借领用单不存在');
    }

    if ($aCeiveUse['cu_type'] == 0) {
      $title = '借用单';
      $this->view->finishBtn = '借用归还';
    }
    else {
      $title = '领用单';
      $this->view->finishBtn = '领用出库';
    }

    if ($aCeiveUse['cu_status'] != 1) {
      exit($title . '【' . $aCeiveUse['cu_code'] . '】不是确认状态');
    }

    $detailList = Service_CeiveUseDetail::getByCondition(array('cu_code' => $aCeiveUse['cu_code']));

    foreach ($detailList as $key => $item) {
      $product = Service_Product::getByField($item['product_id']);
      $item['product_title'] = $product ? $product['product_title'] : '';
      $detailList[$key] = $item;
    }

    $this->view->title = $title;
    $this->view->aCeiveUse = $aCeiveUse;
    $this->view->detailList = Zend_Json::encode($detailList);
    echo Ec::renderTpl($this->tplDirectory . 'ceive_finish.tpl', 'layout');
  }

  /**
   * 借领用出库归还操作
   */
  public function doFinishAction() {
    $response = array('state' => 0, 'message' => '');
    $cu_id = $this->_request->getParam('cu_id','');
    $aCeiveUse = Service_CeiveUse::getByField($cu_id);

    if (empty($aCeiveUse)) {
      exit(json_encode(array('state' => 0, 'message' => '借领用单不存在')));
    }

    if ($aCeiveUse['cu_type'] == 0) {
      $title = '借用单';
    }
    else {
      $title = '领用单';
    }

    if ($aCeiveUse['cu_status'] != 1) {
      exit(json_encode(array('state' =>0, 'message' => $title . '【' . $aCeiveUse['cu_code'] . '】不是确认状态')));
    }

    if ($aCeiveUse['cu_type'] == 0) {
      $result = Service_CeiveUseProcess::revert($aCeiveUse);
    }
    else {
      $result = Service_CeiveUseProcess::takeOut($aCeiveUse);
    }

    if ($result === true) {
      $response['state'] = 1;
      $response['message'] = $title . '【' . $aCeiveUse['cu_code'] . '】';
      $response['message'] .= (0 == $aCeiveUse['cu_type'] ? '归还' : '出库') . '操作成功';
    }
    else {
      $response['message'] = $result;
    }

    exit(Zend_Json::encode($response));
  }

    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'cu_id')) {
            $rows=$this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    /**
     * @author william-fan
     * @todo 打印功能
     */
    public function printAction(){
    	/* echo '<pre>';
    	print_r($this->_request->getParams());
    	echo '</pre>'; */
    	$ceive_idArr = $this->_request->getParam('ceive_id','');
    	//print_r($ceive_id);
    	$inventoryBOB = array();
      $printData = array();
      $kvUserCode = Service_User::getKV(0, 0, 1);
    	$error =array();
    	if(!empty($ceive_idArr)){
    		foreach($ceive_idArr as $key=>$value){
          $ceiveUse = Service_CeiveUse::getByField($value, 'cu_code');

          if (empty($ceiveUse)) {
            $error[] = '【' . $value . '】借领用单不存在';
            continue ;
          }

          // 0草稿状态，打印时变为1确认状态
          if (0 === intval($ceiveUse['cu_status'])) {
            $confirmResponse = Service_CeiveUseProcess::confirm($ceiveUse['cu_id']);

            if (TRUE !== $confirmResponse) {
              $error[] = '【' . $value . '】' . $confirmResponse;
              continue ;
            }
          }

    			$IBOB = Service_InventoryBatchOutbound::getByCondition(array('reference_no'=>$value,'application_code'=>''));
    			if(!empty($IBOB)){
    				foreach($IBOB as $kib=>$vib){
    					$inventoryBatchInfo = Service_InventoryBatch::getByField($vib['ib_id']);
    					$mgibob = array_merge($vib,$inventoryBatchInfo);
    					$productInfo = Service_Product::getByField($mgibob['product_id']);
    					$categoryInfo = Service_ProductCategory::getByField($productInfo['pc_id']);
    					if(!empty($categoryInfo)){
    						$mgibob['category_name'] = $categoryInfo['pc_name'];
    					}else{
    						$mgibob['category_name'] = '';
    					}
    					$mgibob['product_title'] = $productInfo['product_title'];
    					$inventoryBOB[] = $mgibob;
              $printData[$value]['detail'][] = $mgibob;
              $printData[$value]['shelf'][] = $mgibob['lc_code'];
    				}

            $printData[$value]['title'] = (0 === (int) $ceiveUse['cu_type']) ? '借用单' : '领用单';
            $printData[$value]['user'] = array(
                'title' => (0 === (int) $ceiveUse['cu_type']) ? '借用人' : '领用人',
                'account' => $ceiveUse['cu_username'],
                'name' => $kvUserCode[$ceiveUse['cu_username']] ? $kvUserCode[$ceiveUse['cu_username']] : $ceiveUse['cu_username']
            );
            $printData[$value]['shelf'] = array_unique($printData[$value]['shelf']);
    			}else{
    				$error[] = '【' . $value. "】核销表不存在数据";
    			}
    		}
    	}
    	
    	$this->view->error = $error;
    	$this->view->result =$inventoryBOB;
      $this->view->printData = $printData;
      $this->view->currentDate = date('Y-m-d');
    	//echo Ec::renderTpl($this->tplDirectory . 'print_ceive.tpl', 'layout');
      echo Ec::renderTpl($this->tplDirectory . 'ceive_print.tpl', 'layout');
    }
    /**
     * @author william-fan
     * @todo 借领用出库动作
     */
    public function chukuAction(){
    	if($this->_request->isPost()){
    		$result = array('state' => 0, 'message' => '领用单无效', 'data' => array());
    		$ceive_code = $this->_request->getParam('ceive_code','');
    		$type = $this->_request->getParam('type','');
    		switch($type){
    			case 'getreceive':
    				$ceiveInfo = Service_CeiveUse::getByField($ceive_code,'cu_code');
    				if(!empty($ceiveInfo)){
    					if($ceiveInfo['cu_status']!='1'){
    						$result['message'] = '领用单状态不为已确认';
    					}
              elseif (1 !== (int) $ceiveInfo['cu_type']) {
                $result['message'] = $ceive_code . '不是领用单号';
              }
              else{
    						$result['message'] = '领用单有效';
    						$result['state'] = '1';
    					}
    				}
    				die(Zend_Json::encode($result));
    				break;
    			case 'chuku':
    				$product_barcode = $this->_request->getParam('product_barcode','');
    				$return = Service_CeiveUseProcess::chukuProcess($ceive_code,$product_barcode);
    				if($return['state']=='1'){
    					$result['message'] = $return['message'];
    					$result['state'] = '1';
    				}else{
    					$result['message'] = $return['message'];
    				}
    				die(Zend_Json::encode($result));
    				break;	
    		}
    		
    		
    		
    		exit;
    	}

      $ceiveUseId = intval($this->_request->getParam('cu_id', 0));
      $ceiveUse = Service_CeiveUse::getByField($ceiveUseId);

      if ($ceiveUse && 1 === (int) $ceiveUse['cu_status'] && 1 === (int) $ceiveUse['cu_type']) {
        $this->view->ceiveUse = $ceiveUse;
      }

    	echo Ec::renderTpl($this->tplDirectory . 'chuku_ceive.tpl', 'layout');
    }
    /**
     * @author william-fan
     * @todo 归还操作
     */
    public function guihuanAction(){
    	//ceiveBackTransaction:
    	if($this->_request->isPost()){
    		$ceive_code 		= $this->_request->getParam('ceive_code','');
    		$product_barcode	= $this->_request->getParam('product_barcode','');
    		$qty				= $this->_request->getParam('qty','');
    		
    		$result = Service_CeiveUseProcess::guihuanProcess($ceive_code,$product_barcode,$qty);
    		die(Zend_Json::encode($result));
    	}

      $ceiveUseId = intval($this->_request->getParam('cu_id', 0));
      $ceiveUse = Service_CeiveUse::getByField($ceiveUseId);

      if ($ceiveUse && 1 === (int) $ceiveUse['cu_status'] && 0 === (int) $ceiveUse['cu_type']) {
        $this->view->ceiveUse = $ceiveUse;
      }

    	echo Ec::renderTpl($this->tplDirectory . 'guihuan_ceive.tpl', 'layout');
    }
    /**
     * @author william-fan
     * @todo 销毁操作
     */
    public function xiaohuiAction(){
    	if($this->_request->isPost()){
    		$ceive_id 		= $this->_request->getParam('ceive_id','');
    		$type			= $this->_request->getParam('type','');
    		switch($type){
    			case "all":
    				$result = Service_CeiveUseProcess::xiaohuiAllProcess($ceive_id,$type);
    				break;
    			case "singel":
    				$result = Service_CeiveUseProcess::xiaohuiSingleProcess($ceive_id,$type);
    				break;
    		}
    		die(Zend_Json::encode($result));
    	}
    }
}