<?php
/**
 * 出区派车单
 */
class Shipment_OutAreaController extends Ec_Controller_Action {
  public function preDispatch() {
    $this->tplDir = 'shipment/views/out-area/';
  }

  /**
   * 新增动作
   */
  public function createAction() {
    $this->view->container = Service_OutArea::getContainer();
    $this->view->ieport = Service_IePort::getAll();
    echo Ec::renderTpl($this->tplDir . 'create.tpl', 'layout');
  }

  /**
   * 编辑动作
   */
  public function editAction() {
    $oaCode = trim($this->getRequest()->getParam('code', ''));

    if ('' === $oaCode) {
      exit('Warning: Invalid Request');
    }

    $outArea = Service_OutArea::getByCode($oaCode);

    if (empty($outArea)) {
      exit('Warning: Invalid Request');
    }

    if (Service_OutArea::STATUS_DRAFT !== (int) $outArea['status']) {
      exit('Error: Invalid Status');
    }

    $this->view->container      = Service_OutArea::getContainer();
    $this->view->outArea       = $outArea;
    $out=Service_OutArea::getDetailByCode($oaCode);
    foreach ($out as $key => $value) {
      $oa=Service_OutArea::getByCondition(array('oa_code'=>$value['oa_code']));
      $sb=Service_ShipBatchAttribute::getByCondition(array('sb_code'=>$value['sb_code']));
      $out[$key]['car_number']=$oa[0]['car_number'];
      $ieport=Service_IePort::getByField($oa[0]['ie_port'],'ie_port');
      $out[$key]['ie_port']=$ieport['ie_port_name'];
      $out[$key]['pack_no']=$sb[0]['pack_no'];
    }
    $this->view->outAreaDetail = $out;
	$this->view->ieport = Service_IePort::getAll();
    echo Ec::renderTpl($this->tplDir . 'edit.tpl', 'layout');
  }

  /**
   * 保存动作
   */
  public function saveAction() {
    $response = array('status' => 0, 'message' => '非法HTTP请求', 'code' => '');

    if ($this->getRequest()->isPost()) {
      $oaCode        = trim($this->getRequest()->getPost('oa_code', ''));
      $carNumber     = trim($this->getRequest()->getPost('car_number', ''));
      $containerType = intval($this->getRequest()->getPost('container_type', 0));
      $ieport = trim($this->getRequest()->getPost('ie_port', ''));
      $sbCode       = $this->getRequest()->getPost('selectedAsnCode', array());
      $outAreaRow   = array(
        'oa_code'        => $oaCode,
        'car_number'     => $carNumber,
        'container_type' => $containerType,
        'ie_port'        => $ieport,
        'sb_code'       => $sbCode
      );
      if ('' === $oaCode) { // 新增
        $result = Service_OutArea::create($outAreaRow);

        if (is_array($result)) {
          $response['message'] = '出区派车单创建失败：' . join('；', $result);
        }
        else {
          $response['status']  = 1;
          $response['message'] = '出区派车单已创建，单号【' . $result . '】';
          $response['code']    = $result;
        }
      }
      else { // 修改
        $result = Service_OutArea::update($outAreaRow);

        if (TRUE === $result) {
          $response['status']  = 1;
          $response['message'] = '出区派车单【' . $oaCode . '】于' . date('Y-m-d H:i:s') . '已更新';
        }
        else {
          $response['message'] = '出区派车单【' . $oaCode . '】于' . date('Y-m-d H:i:s') . '更新失败：' . $result;
        }
      }
    }

    exit(Zend_Json::encode($response));
  }

  /**
   * 列表动作
   */
  public function listAction() {
    if ($this->getRequest()->isPost()) {
      $page          = (int) trim($this->_request->getParam('page', 1));
      $size          = (int) trim($this->_request->getParam('pageSize', 20));
      $oaCode        = trim($this->_request->getParam('oa_code', ''));
      $status        = trim($this->_request->getParam('status', ''));
      $carNumber     = trim($this->_request->getParam('car_number', ''));
      $ieport     = trim($this->_request->getParam('ie_port', ''));
      $containerType = trim($this->_request->getParam('container_type', ''));
      $condition     = array();
      $condition['created_time_from'] = trim($this->_request->getParam('dateFor', ''));
      $condition['created_time_to'] = trim($this->_request->getParam('dateTo', ''));
      if ('' !== $oaCode) {
        $condition['oa_code'] = $oaCode;
      }

      if ('' !== $status) {
        $condition['status'] = (int) $status;
      }
      if ('' !== $ieport) {
        $condition['ie_port'] =  $ieport;
      }
      if ('' !== $carNumber) {
        $condition['car_number'] = $carNumber;
      }

      if ('' !== $containerType) {
        $condition['container_type'] = (int) $containerType;
      }

      $total  = Service_OutArea::getByCondition($condition, array('count' => TRUE));
      $record = Service_OutArea::getByCondition($condition, array('page' => $page, 'size' => $size, 'order' => 'oa_id DESC'));

		foreach ($record as $key => &$value) {
			$ieport=Service_IePort::getByField($value['ie_port'],'ie_port');
			$record[$key]['ie_port_name']=$ieport['ie_port_name'];
		}
      exit(Zend_Json::encode(array(
        'state' => $total ? 1 : 0,
        'total' => $total,
        'data'  => $record,
      )));
    }

    $this->view->container = Service_OutArea::getContainer();
    $this->view->type      = Service_OutArea::getType();
    $this->view->ieport = Service_IePort::getAll();
    echo Ec::renderTpl($this->tplDir . 'list.tpl', 'layout');
  }

  /**
   * 确认动作
   */
  public function confirmAction() {
    $iaCode   = trim($this->getRequest()->getParam('code', ''));
    $response = array('status' => 0, 'message' => '非法HTTP请求');

    if (!$this->getRequest()->isPost()) {
      exit(Zend_Json::encode($response));
    }

    if ('' === $iaCode) {
      $response['message'] = '出区派车单号不能为空';
      exit(Zend_Json::encode($response));
    }

    $outArea = Service_OutArea::getByCode($iaCode);

    if (empty($outArea)) {
      $response['message'] = '不存在出区派车单【' . $iaCode . '】';
      exit(Zend_Json::encode($response));
    }

    if (Service_OutArea::STATUS_DRAFT !== (int) $outArea['status']) {
      $response['message'] = '出区派车单【' . $iaCode . '】不是草稿状态';
      exit(Zend_Json::encode($response));
    }

    $result = Service_OutArea::confirm($iaCode);

    if (TRUE === $result) {
      $response['status']  = 1;
      $response['message'] = '出区派车单【' . $iaCode . '】已移至【确认】状态';
    }
    else {
      $response['message'] = $result;
    }

    exit(Zend_Json::encode($response));
  }

  /**
   * 打印动作
   */
  public function printAction() {
    $iaCode                   = trim($this->getRequest()->getParam('code', ''));
    $this->view->isError      = TRUE;
    $this->view->errorContent = '出区派车单号不能为空';

    if ('' !== $iaCode) {
      $outArea = Service_OutArea::getByCode($iaCode);

      if (empty($outArea)) {
        $this->view->errorContent = '出区派车单号【' . $iaCode . '】不存在';
      }
      elseif (Service_OutArea::STATUS_CONFIRMED !== (int) $outArea['status']) {
        $this->view->errorContent = '出区派车单号【' . $iaCode . '】不是确认状态';
      }
      else {
        $outAreaDetail = Service_OutArea::getDetailByCode($iaCode);
        $outDetail      = array();
        $errorMessage   = array();

        if (empty($outAreaDetail)) {

          $container                  = Service_OutArea::getContainer();
          $outArea['car_number']     = preg_replace('/([a-zA-Z0-9]+)/', '<span class="english">\1</span>', $outArea['car_number']);
            $outArea['container_type'] = $container[$outArea['container_type']];
           $ieport=Service_IePort::getByField($outArea['ie_port'],'ie_port');
           $outArea['ie_port_name']=$ieport['ie_port_name'];
           $total                      = count($outDetail);
           $this->view->isError        = FALSE;
          $this->view->outArea       = $outArea;
          $this->view->outAreaDetail ='';
          $this->view->totalAsn       = $total;
          //$this->view->errorContent = '出区派车单号【' . $iaCode . '】不存在出货总单';
        }
        else {
              $total_pack=0;
            	$total_gross=0;
            	$total_net=0;
            	$total_price=0;
          foreach ($outAreaDetail as $item) {
                //$price=0;
                $sbaRow = Service_ShipBatchAttribute::getByCondition(array('sb_code' => $item['sb_code']));
     		    $ShipBatch = Service_ShipBatch::getByCondition(array('sb_code' => $item['sb_code']));
                $gross_weight = Service_ShipBatchDetail::sumGrossWeight($item['sb_code']);
                $net_weight = number_format(Service_ShipBatchDetail::sumNetWeight($item['sb_code']),2,'.','');
                $sbaRow = Service_ShipBatchAttribute::getByField($item['sb_code'], 'sb_code');
                $price = Service_ShipBatchDetail::getTotalPrice($item['sb_code']);
                $outDetail[]            = array(
                      'sb_code'  => $item['sb_code'],
                      'pack_no'  => $sbaRow['pack_no'],
                      'gross_wt' => $gross_weight,
                      'net_wt'   => $net_weight,
                      'total_price'=>$price,
                );
                $total_pack+= $sbaRow['pack_no'];
                $total_gross+=$gross_weight;
                $total_net+=$net_weight;
                $total_price+=$price;

          }
          if (empty($errorMessage)) {
            $container                  = Service_OutArea::getContainer();
            $outArea['car_number']     = preg_replace('/([a-zA-Z0-9]+)/', '<span class="english">\1</span>', $outArea['car_number']);
            $outArea['container_type'] = $container[$outArea['container_type']];
  			   $ieport=Service_IePort::getByField($outArea['ie_port'],'ie_port');
			     $outArea['ie_port_name']=$ieport['ie_port_name'];
            $size                       = 10;
            $total                      = count($outDetail);
            $this->view->isError        = FALSE;
            $this->view->total_net		= $total_net;
            $this->view->total_gross	= $total_gross;
            $this->view->total_pack		= $total_pack;
            $this->view->total_price	= $total_price;
            $this->view->outArea       = $outArea;
            $this->view->outAreaDetail = array_chunk($outDetail, $size);
            $this->view->totalAsn       = $total;
            $this->view->totalPage      = ceil($total / $size);
            $this->view->size           = $size;
          }else {
            $this->view->errorContent = join('；', $errorMessage);
          }
        }
  	 }
    }
      $this->view->year           = date('Y');
      $this->view->month          = date('n');
      $this->view->day            = date('j');
    echo $this->view->render($this->tplDir . 'print.tpl');
  }

  /**
   * 详情动作
   */
  public function detailAction() {
    $oaCode   = trim($this->getRequest()->getParam('code', ''));
    $response = array('status' => 0, 'message' => '非法HTTP请求', 'data' => array());

    if ('' === $oaCode) {
      $response['message'] = '出区派车单号不能为空';
    }
    else {
      $outArea = Service_OutArea::getByCode($oaCode);

      if (empty($outArea)) {
        $response['message'] = '入区派车单【' . $oaCode . '】不存在';
      }
      else {
        $outAreaDetail = Service_OutArea::getDetailByCode($oaCode);
        $shipBatchDetail      = array();

        foreach ($outAreaDetail as $item) {
          $ShipBatch = Service_ShipBatchDetail::getByCondition(array('sb_code' => $item['sb_code']));
            $shipBatchDetail[] = array(
              'sb_code'     => $item['sb_code'],
            );
         
        }

		$ieport=Service_IePort::getByField($outArea['ie_port'],'ie_port');
		$outArea['ie_port_name']=$ieport['ie_port_name'];
        $response['status']  = 1;
        $response['message'] = '出区派车单【' . $oaCode . '】数据已返回';
        $response['data']    = array(
          'outArea'       => $outArea,
          'outAreaDetail' => $outAreaDetail,
        );
      }
    }

    exit(Zend_Json::encode($response));
  }
     /**
     * @desc 导出出区派车单
     */
    public function exportAction()
    {
        if ($this->_request->isPost()) {
            $oaCodes =$this->_request->getParam('oaCodes',array());
            if(!empty($oaCodes) && is_array($oaCodes) ){
            }else{
                die('请选择出区派车单单号');
            }
            $filename = "outArea".date("YmdHis");
            require_once("PHPExcel.php");
            require_once("PHPExcel/Reader/Excel2007.php");
            require_once("PHPExcel/Reader/Excel5.php");
            require_once ('PHPExcel/IOFactory.php');

            $objExcel = new PHPExcel();
            $objProps = $objExcel->getProperties();
            $objProps->setCreator('EC');
            $objProps->setTitle('Template');
            $objExcel->setActiveSheetIndex(0);

            $objActSheet = $objExcel->getActiveSheet();

            $objActSheet->getColumnDimension('A')->setWidth(20);
            $objActSheet->getColumnDimension('B')->setWidth(15);
            $objActSheet->getColumnDimension('C')->setWidth(10);
            $objActSheet->getColumnDimension('D')->setWidth(30);
            $objActSheet->getColumnDimension('E')->setWidth(10);
            $objActSheet->getColumnDimension('F')->setWidth(20);

            $objActSheet->setCellValue('A1','出区派车单号');
            $objActSheet->setCellValue('B1','车牌号');
            $objActSheet->setCellValue('C1','柜型');
            $objActSheet->setCellValue('D1','进出口口岸');
            $objActSheet->setCellValue("E1",'状态');
            $objActSheet->setCellValue('F1','创建时间');
            $index = 2;
            foreach($oaCodes as $code){
                $sbRow = Service_OutArea::getByCondition(array('oa_code'=>$code));
                $sbRow=$sbRow[0];
                $ieport=Service_IePort::getByField($sbRow['ie_port'],'ie_port');  
                $objActSheet->setCellValue("A".$index,$sbRow['oa_code']);
                $objActSheet->setCellValueExplicit("B".$index,$sbRow['car_number'],PHPExcel_Cell_DataType::TYPE_STRING);
                if($sbRow['container_type']){
                  $objActSheet->setCellValue("C".$index,"集装箱");
                }else{
                  $objActSheet->setCellValue("C".$index,"吨车");
                }
                $objActSheet->setCellValue("D".$index,$ieport['ie_port_name']);
                if($sbRow['status']){
                  $objActSheet->setCellValue("E".$index,"确认");
                }else{
                  $objActSheet->setCellValue("E".$index,"草稿");
                }   
                $objActSheet->setCellValue("F".$index,$sbRow['created_time']);
                $index++;
            }

            header('Pragma:public');
            header('Content-Type:application/x-msexecl;name="' . $filename . '.xls');
            header("Content-Disposition:inline;filename=" . $filename . '.xls');
            $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
            $objWriter->save('php://output');
        }
    }

    /*修改车牌*/
    public function modnumAction() {
    $oaCode   = trim($this->getRequest()->getParam('code', ''));
    $carNum   = trim($this->getRequest()->getParam('num', ''));
    $response = array('status' => 0, 'message' => '非法HTTP请求');
    if (!$this->getRequest()->isPost()) {
      exit(Zend_Json::encode($response));
    }

    if ('' === $carNum) {
      $response['message'] = '车牌号不能为空';
      exit(Zend_Json::encode($response));
    }
    $row=array(
      'oa_code'=>$oaCode,
      'car_number'=>$carNum,
      );
    $outArea = Service_OutArea::updateByCode($row,$oaCode);
    if ($outArea==TRUE) {
      $response['status']=1;
    }
    exit(Zend_Json::encode($response));
  }

}
