<?php
class Order_ExportPnlpHfController extends Ec_Controller_Action {
  public function preDispatch() {
    $smCode      = trim($this->getRequest()->getParam('code', ''));
    $allowedCode = array('PNLN', 'PNLG'); // 允许的运输方式
    $caNumber    = array(
      'PNLN' => '45199747',
      'PNLG' => '45184943',
    );
    $pd         = array(
      'PNLN' => 'Packet Encombrant Priority',
      'PNLG' => 'Registered Mail (aangetekenden)',
    );

    if (!in_array($smCode, $allowedCode, TRUE)) {
      exit('No Data ...');
    }

    $this->smCode         = $smCode;
    $this->caNumber       = $caNumber[$smCode];
    $this->productDesc    = $pd[$smCode];
    $this->exportFilename = $smCode . '-P1700-' . date('YmdHis') . '.xlsx';
    $this->templatePath   = APPLICATION_PATH . '/../data/file/' . $smCode . '-P1700-template.xlsx';
    $this->serviceClass   = new Service_Orders();
  }

  public function printAction() {
    set_time_limit(0);

    $exportType = (int) trim($this->getRequest()->getParam('type', 0));

    if (1 === $exportType) {
      $this->printSelected();
    }
    else {
      $this->printAll();
    }
  }

  private function printSelected() {
    $selectedOrder = $this->getRequest()->getPost('orderId', array());
    $allowedData   = array();
    $shipTime      = 0;

    if (empty($selectedOrder)) {
      exit('No Data ...');
    }

    foreach ($selectedOrder as $selected) {
      if (!is_numeric($selected)) {
        continue ;
      }

      $selected = (int) $selected;

      if ($selected < 1) {
        continue ;
      }

      $order = Service_Orders::getByField($selected, 'order_id');

      if (empty($order) || $this->smCode !== $order['sm_code']) {
        continue ;
      }

      $address   = Service_OrderAddressBook::getByField($order['order_code'], 'order_code');
      $shipOrder = Service_ShipOrder::getByField($order['order_code'], 'order_code');
      $country   = Service_Country::getByField((int) $address['oab_country_id'], 'country_id');
      //$products  = Service_OrderProduct::getByCondition(array('order_code' => $order['order_code']));
      $operation = Service_OrderOperationTime::getByField($order['order_code'], 'order_code');
      $allWeight = $shipOrder ? $shipOrder['so_weight'] : 0;

      /*foreach ($products as $item) {
        $product   = Service_Product::getByField((int) $item['product_id'], 'product_id');
        $allWeight = $item['op_quantity'] * $product['product_weight'];
      }*/

      // 订单发货时间
      if (!empty($operation) && strtotime($operation['ship_time']) > $shipTime) {
        $shipTime = strtotime($operation['ship_time']);
      }

      // 计算发往各个国家的订单数量
      if (isset($allowedData[$country['country_code']]['count'])) {
        ++$allowedData[$country['country_code']]['count'];
      }
      else {
        $allowedData[$country['country_code']]['count'] = 1;
      }

      // 计算发往各个国家的订单总重量
      if (isset($allowedData[$country['country_code']]['weight'])) {
        $allowedData[$country['country_code']]['weight'] += $allWeight;
      }
      else {
        $allowedData[$country['country_code']]['weight'] = $allWeight;
      }
    }

    if (empty($allowedData)) {
      exit('No Data ...');
    }

    require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
    require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

    $total     = count($allowedData);
    $startRow  = 20; // Excel模板中开始写入数据的行号
    $objLoad   = PHPExcel_IOFactory::load($this->templatePath);
    $objWriter = PHPExcel_IOFactory::createWriter($objLoad, 'Excel2007');
    $objPe     = $objWriter->getPHPExcel();
    $objSheet  = $objPe->setActiveSheetIndex(0);

    // 根据数据量，对需要填写的行进行增减
    if ($total < 2) {
      $objSheet->removeRow($startRow, 1);
    }
    elseif ($total > 2) {
      $objSheet->insertNewRowBefore($startRow + 1, $total - 2);
    }

    // 设置日期
    $objSheet->setCellValue('J14', date('Y/n/j', $shipTime));

    // 往Excel模板文件写内容
    foreach ($allowedData as $key => $item) {
      $objSheet->setCellValue('B' . $startRow, '5912'); // 固定值
      $objSheet->setCellValue('D' . $startRow, $this->productDesc); // 固定值
      $objSheet->setCellValue('H' . $startRow, 'NL'); // 固定值
      $objSheet->setCellValue('J' . $startRow, $key); // 国家代码
      $objSheet->setCellValue('L' . $startRow, $this->caNumber); // 固定值
      $objSheet->setCellValue('R' . $startRow, $item['count']); // 订单总数
      $objSheet->setCellValue('V' . $startRow, $item['weight'] / $item['count'] * 1000); // 平均重量，单位G

      if ('PNLG' === $this->smCode) {
        $objSheet->setCellValue('X' . $startRow, $item['count']); // 订单总数
      }
      else {
        $objSheet->setCellValue('X' . $startRow, $item['weight']); // 总重量，单位KG
      }

      ++$startRow;
    }

    header('pragma: public');
    header('expires: 0');
    header('accept-ranges: bytes');
    header('cache-control: must-revalidate');
    header('content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8');
    header('content-disposition: attachment; filename=' . $this->exportFilename);
    $objWriter->save('php://output');
  }

  private function printAll() {
    $params      = $this->_request->getParams();
    $condition   = $this->serviceClass->getMatchFields($params);
    $allowedData = array();
    $shipTime    = 0;

    if ('orderCode' == $params['searchType']) {
      $condition['order_code'] = $params['searchCode'];
    }
    else {
      $condition['reference_no'] = $params['searchCode'];
    }

    $conditionTemp['dateFor'] = isset($params['dateFor']) ? $params['dateFor'] : '';
    $conditionTemp['dateTo']  = isset($params['dateTo']) ? $params['dateTo'] : '';
    $searchDateType = isset($params['searchDateType']) ? $params['searchDateType'] : '';
    $isSearchDate = FALSE;

    if (!empty($conditionTemp['dateFor'])) {
      $isSearchDate = TRUE;
      $conditionTemp['dateFor']=date('Y-m-d H:i:s',strtotime($conditionTemp['dateFor']));
    }

    if (!empty($conditionTemp['dateTo'])) {
      $isSearchDate = TRUE;
      $conditionTemp['dateTo'] = date('Y-m-d H:i:s', strtotime($conditionTemp['dateTo']));
    }

    if ($isSearchDate) {
      switch ($searchDateType) {
        case 'createDate':
          $condition['dateFor'] = $conditionTemp['dateFor'];
          $condition['dateTo']  = $conditionTemp['dateTo'];
          break;
        case 'printTime':
          $condition['printDateFor'] = $conditionTemp['dateFor'];
          $condition['printDateTo']  = $conditionTemp['dateTo'];
          break;
        case 'packTime':
          $condition['packDateFor'] = $conditionTemp['dateFor'];
          $condition['packDateTo']  = $conditionTemp['dateTo'];
          break;
        case 'shipTime':
          $condition['shipDateFor'] = $conditionTemp['dateFor'];
          $condition['shipDateTo']  = $conditionTemp['dateTo'];
          break;
        default:
          break;
      }
    }

    $condition['product_barcode']  = isset($params['product_barcode']) ? $params['product_barcode'] : '';
    $condition['product_category'] = isset($params['product_category']) ? $params['product_category'] : '';
    $condition['oab_type']         = '0';
    $condition['tracking_number']  = $params['tracking_number'];
    $condition['oab_country_id']   = $params['oab_country_id'];
    $condition['sm_code']          =  $this->smCode;

    if ($condition['tracking_number']) {
      $shipOrder = Service_ShipOrder::getByField($condition['tracking_number'], 'tracking_number');

      if (!empty($shipOrder)) {
        $condition['order_id'] = $shipOrder['order_id'];
      }
      else {
        $condition['order_id'] = 'none';
      }
    }

    $selectedOrder = $this->serviceClass->getOrderInnerJoinProductByCondition($condition);

    foreach ($selectedOrder as $order) {
      if (empty($order) ||  $this->smCode !== $order['sm_code']) {
        continue ;
      }

      $address   = Service_OrderAddressBook::getByField($order['order_code'], 'order_code');
      $shipOrder = Service_ShipOrder::getByField($order['order_code'], 'order_code');
      $country   = Service_Country::getByField((int) $address['oab_country_id'], 'country_id');
      //$products  = Service_OrderProduct::getByCondition(array('order_code' => $order['order_code']));
      $operation = Service_OrderOperationTime::getByField($order['order_code'], 'order_code');
      $allWeight = $shipOrder ? $shipOrder['so_weight'] : 0;

      /*foreach ($products as $item) {
        $product   = Service_Product::getByField((int) $item['product_id'], 'product_id');
        $allWeight = $item['op_quantity'] * $product['product_weight'];
      }*/

      // 订单发货时间
      if (!empty($operation) && strtotime($operation['ship_time']) > $shipTime) {
        $shipTime = strtotime($operation['ship_time']);
      }

      // 计算发往各个国家的订单数量
      if (isset($allowedData[$country['country_code']]['count'])) {
        ++$allowedData[$country['country_code']]['count'];
      }
      else {
        $allowedData[$country['country_code']]['count'] = 1;
      }

      // 计算发往各个国家的订单总重量
      if (isset($allowedData[$country['country_code']]['weight'])) {
        $allowedData[$country['country_code']]['weight'] += $allWeight;
      }
      else {
        $allowedData[$country['country_code']]['weight'] = $allWeight;
      }
    }

    if (empty($allowedData)) {
      exit('No Data ...');
    }

    require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
    require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

    $total     = count($allowedData);
    $startRow  = 20; // Excel模板中开始写入数据的行号
    $objLoad   = PHPExcel_IOFactory::load($this->templatePath);
    $objWriter = PHPExcel_IOFactory::createWriter($objLoad, 'Excel2007');
    $objPe     = $objWriter->getPHPExcel();
    $objSheet  = $objPe->setActiveSheetIndex(0);

    // 根据数据量，对需要填写的行进行增减
    if ($total < 2) {
      $objSheet->removeRow($startRow, 1);
    }
    elseif ($total > 2) {
      $objSheet->insertNewRowBefore($startRow + 1, $total - 2);
    }

    // 设置日期
    $objSheet->setCellValue('J14', date('Y/n/j', $shipTime));

    // 往Excel模板文件写内容
    foreach ($allowedData as $key => $item) {
      $objSheet->setCellValue('B' . $startRow, '5912'); // 固定值
      $objSheet->setCellValue('D' . $startRow, $this->productDesc); // 固定值
      $objSheet->setCellValue('H' . $startRow, 'NL'); // 固定值
      $objSheet->setCellValue('J' . $startRow, $key); // 国家代码
      $objSheet->setCellValue('L' . $startRow, $this->caNumber); // 固定值
      $objSheet->setCellValue('R' . $startRow, $item['count']); // 订单总数
      $objSheet->setCellValue('V' . $startRow, $item['weight'] / $item['count'] * 1000); // 平均重量，单位G
      $objSheet->setCellValue('X' . $startRow, $item['weight']); // 总重量，单位KG
      ++$startRow;
    }

    header('pragma: public');
    header('expires: 0');
    header('accept-ranges: bytes');
    header('cache-control: must-revalidate');
    header('content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8');
    header('content-disposition: attachment; filename=' . $this->exportFilename);
    $objWriter->save('php://output');
  }
}
