<?php
class Order_ExportAlfaHfController extends Ec_Controller_Action {
  public function preDispatch() {
    $smCodes      = $this->getRequest()->getParam('E7', '');
    $smCode = '';
      if( !empty( $smCodes ) ) {
          if( is_array( $smCodes ) ) {
              $smCode = $smCodes[0];//原来的程序就是一次只能导出一种运输方式的
          } else {
              $smCode = $smCodes;
          }

      }
    $allowedCode = array('PNLN', 'PNLG'); // 允许的运输方式
    $caNumber    = array(
      'PNLN' => '45211351',
      'PNLG' => '45211351',
    );
    $pd         = array(
      'PNLN' => 'Gateway Mail Exp Mixed Priority',
      'PNLG' => 'Gateway Mail Exp Registered',
    );

    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;
        $allowedData[$country['country_code']]['country_name'] = $country['country_name_en'];
        $allowedData[$country['country_code']]['country_zone'] = Service_PostNl::getZone($country['country_code']);
      }

      // 计算发往各个国家的订单总重量
      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/PHPExcel1.8/PHPExcel.php';
    require_once APPLICATION_PATH . '/../libs/PHPExcel1.8/PHPExcel/IOFactory.php';

    $total     = count($allowedData);
    $startRow  = ('PNLG' === $this->smCode) ? 19 : 20; //PNLG 19行开始写数据，PNLN20行开始写数据
    $objLoad   = PHPExcel_IOFactory::load($this->templatePath);
    $objWriter = PHPExcel_IOFactory::createWriter($objLoad, 'Excel2007');
    $objPe     = $objWriter->getPHPExcel();
    $objSheet  = $objPe->setActiveSheetIndex(0);

    // 根据数据量，对需要填写的行进行增减
    if ($total < 4) {
      $objSheet->removeRow($startRow, 4 - $total);
    }
    elseif ($total > 4) {
      $objSheet->insertNewRowBefore($startRow + 1, $total - 4);
    }

    // 设置日期
    $objSheet->setCellValue('J14', date('Y/n/j', $shipTime));

    // 往Excel模板文件写内容
    foreach ($allowedData as $key => $item) {
      //$objSheet->setCellValue('B' . $startRow, '5912'); // 固定值
      if('PNLG' === $this->smCode){
          $objSheet->setCellValue('B' . $startRow, '5964');
      }
      else {
          $objSheet->setCellValue('B' . $startRow, '5962');
      }
      $objSheet->setCellValue('D' . $startRow, $this->productDesc); // 固定值
      $objSheet->setCellValue('H' . $startRow, 'PB'); // 固定值
      $objSheet->setCellValue('J' . $startRow, $item['country_zone']); // 区域码暂空

      $objSheet->setCellValue('L' . $startRow, $item['country_name']); // 国家代码
      $objSheet->setCellValue('N' . $startRow, $this->caNumber); // 固定值
      $objSheet->setCellValue('P' . $startRow, $item['count']); // 订单总数
      $objSheet->setCellValue('R' . $startRow, $item['weight'] / $item['count'] * 1000); // 平均重量，单位G

      if ('PNLG' === $this->smCode) {
        $objSheet->setCellValue('T' . $startRow, $item['count']); // 订单总数
      }
      else {
        $objSheet->setCellValue('T' . $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->getNewMatchFields($params);
    $allowedData = array();
    $shipTime    = 0;
      if( is_array( $condition['oab_country_id'] ) && count( $condition['oab_country_id'] ) == 1 && $condition['oab_country_id'][0] === '' ) {
          unset($condition['oab_country_id']);
      }
    if ('orderCode' == $params['searchType']) {
      $condition['order_code'] = $params['searchCode'];
    }
    else {
      $condition['reference_no'] = $params['searchCode'];
    }

      $time = Common_Common::getStartAndEndTime($params['dateFor'],$params['dateTo']);
      $conditionTemp['dateFor'] = $time[0];
      $conditionTemp['dateTo'] = $time[1];
      unset($condition['dateFor']);
      unset($condition['dateTo']);
    $searchDateType = isset($params['searchDateType']) ? $params['searchDateType'] : '';

      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['oab_type']         = '0';
    $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;
        $allowedData[$country['country_code']]['country_name'] = $country['country_name_en'];
        $allowedData[$country['country_code']]['country_zone'] = Service_PostNl::getZone($country['country_code']);
      }

      // 计算发往各个国家的订单总重量
      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/PHPExcel1.8/PHPExcel.php';
    require_once APPLICATION_PATH . '/../libs/PHPExcel1.8/PHPExcel/IOFactory.php';

    $total     = count($allowedData);
    $startRow  = ('PNLG' === $this->smCode) ? 19 : 20; //PNLG 19行开始写数据，PNLN20行开始写数据
    $objLoad   = PHPExcel_IOFactory::load($this->templatePath);
    $objWriter = PHPExcel_IOFactory::createWriter($objLoad, 'Excel2007');
    $objPe     = $objWriter->getPHPExcel();
    $objSheet  = $objPe->setActiveSheetIndex(0);

    // 根据数据量，对需要填写的行进行增减
      if ($total < 4) {
      $objSheet->removeRow($startRow, 4 - $total);
    }
    elseif ($total > 4) {
      $objSheet->insertNewRowBefore($startRow + 1, $total - 4);
    }

    // 设置日期
    $objSheet->setCellValue('J14', date('Y/n/j', $shipTime));

    // 往Excel模板文件写内容
    foreach ($allowedData as $key => $item) {
      //$objSheet->setCellValue('B' . $startRow, '5912'); // 固定值
        if('PNLG' === $this->smCode){
            $objSheet->setCellValue('B' . $startRow, '5964');
        }
        else {
            $objSheet->setCellValue('B' . $startRow, '5962');
        }
      $objSheet->setCellValue('D' . $startRow, $this->productDesc); // 固定值
      $objSheet->setCellValue('H' . $startRow, 'PB'); // 固定值
      $objSheet->setCellValue('J' . $startRow, $item['country_zone']); // 区域码
      $objSheet->setCellValue('L' . $startRow, $item['country_name']); // 国家代码
      $objSheet->setCellValue('N' . $startRow, $this->caNumber); // 固定值
      $objSheet->setCellValue('P' . $startRow, $item['count']); // 订单总数
      $objSheet->setCellValue('R' . $startRow, $item['weight'] / $item['count'] * 1000); // 平均重量，单位G
      $objSheet->setCellValue('T' . $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');
  }
}
