<?php
class Merchant_OrderExportController extends Ec_Controller_Action {
  public function preDispatch() {
    // Intentionally left blank.
    $this->customerAuth = new Zend_Session_Namespace("customerAuth");
  }
    public function doAction()
    {
        $flagFile = APPLICATION_PATH . '/../data/log/order-'.date('YmdHis').'.csv';
        $link = fopen($flagFile, 'wb');
        fwrite($link,chr(0xEF).chr(0xBB).chr(0xBF));
        set_time_limit(0);
        @ini_set('memory_limit', '1024M');
        $queryType = trim($this->getRequest()->getParam('type', ''));
        $queryMode = trim($this->getRequest()->getParam('mode', 0));
        $queryCode = trim($this->getRequest()->getParam('code', ''));

        if ('' === $queryType) {
            exit('Export Data Type Is Empty');
        } elseif (!in_array((int)$queryType, array(0, 1), TRUE)) {
            exit('Export Data Type Is Error');
        } elseif (1 === (int)$queryType && '' === $queryCode) {
            exit('Export Data Code Is Empty');
        }
        $queryType = (int)$queryType;
        $csvTitle = array(
            '客户公司名称','订单模式','订单状态','订单号','使用自有渠道','服务商单号','仓库',
            '收件人国家','收件人国家（英文名称）','国家简码','国内海关总申报价值（USD）','目的海关申报总价（USD）','运输方式','交易订单号','收件人姓名','收件人公司名','收件人州\区域','收件人城市','收件人邮编','收件人地址1','收件人地址2','收件人电话','收件人电子邮件','成交币种','成交总价','提交时间','出货时间','物流完成时间','香港交货时间','体积重','长*宽*高','实重','收费重量','件数','产品总数','备注','是否运单投保','投保类型','承诺妥投日期','产品中文名称','sku','产品英文品名','海关品名','申报单价（USD）','目的海关申报单价（USD）','数量','海关编码');
        
        fputcsv($link, $csvTitle);
        if (1 === $queryType) {
            $queryCode = explode('|', $queryCode);
            $printOrderInfo = $this->getPrintOrderInfo($queryCode);
            foreach ($printOrderInfo['data'] as $item) {
                foreach ($item['product']['data'] as $product) {
                    $eachRow = $this->doCsvRow($item, $product);
                    fputcsv($link, $eachRow);
                }
            }
        } else {
            $orderCode = trim($this->getRequest()->getParam('order_code', ''));
            $orderStatus = trim($this->getRequest()->getParam('order_status', '1'));
            $orderType = trim($this->getRequest()->getParam('order_type', ''));
            $warehouseId = trim($this->getRequest()->getParam('warehouse_id', ''));
            $smCode = trim($this->getRequest()->getParam('shipping_method', ''));
            $addTimeStart = trim($this->getRequest()->getParam('add_time_start', ''));
            $addTimeEnd = trim($this->getRequest()->getParam('add_time_end', ''));
            $shipTimeStart = trim($this->getRequest()->getParam('ship_time_start', ''));
            $shipTimeEnd = trim($this->getRequest()->getParam('ship_time_end', ''));
            $serviceTracking = trim($this->getRequest()->getParam('service_tracking', ''));
            $insurance   = trim($this->getRequest()->getParam('buyInsurance', ''));
            $condition['new_reference_no'] = $orderCode;
            $condition['warehouse_id'] = $warehouseId;
            $condition['order_type'] = $orderType;
            $condition['sm_code'] = $smCode;
            $condition['order_status_arr'] = explode(',', $orderStatus);
            $condition['order_mode_type'] = $queryMode;
            $condition['add_time_start'] = $addTimeStart;
            $condition['add_time_end'] = $addTimeEnd;
            $condition['ship_time_start'] = $shipTimeStart;
            $condition['ship_time_end'] = $shipTimeEnd;
            $condition['insurance']    = $insurance;
            $customer = $this->_customerAuth;
            $condition['customer_id'] = $customer['id'];
            if ($serviceTracking != '' && $serviceTracking != 'undefined') {
                $shipOrderList = Service_ShipOrder::getByCondition(array('tracking_number' => $serviceTracking), 'order_code');
                if (!empty($shipOrderList)) {
                    $orderCodeArray = array();
                    foreach ($shipOrderList as $so) {
                        $orderCodeArray[] = $so['order_code'];
                    }
                    $condition['order_code'] = $orderCodeArray;
                } else {
                    $condition['ref_tracking_number'] = $serviceTracking;
                }
            }

            //print_r($condition);exit;
            $printOrderInfo = array(
                'data' => array(),
                'maxProductQuantity' => 0
            );
            // $orderRows = Service_Orders::getByCondition($condition);
            $orderModel = new Table_Orders();
            $sql = $orderModel->getSql($condition);
            $server = new Zend_Config_Ini(APPLICATION_PATH . '/configs/db.ini', 'production');
            $dsn = 'mysql:host=' . $server->resources->multidb->sandbox->host . ';dbname=' . $server->resources->multidb->sandbox->dbname;
            $db = new PDO(
                $dsn,
                $server->resources->multidb->sandbox->username,
                $server->resources->multidb->sandbox->password
            );
            $db -> query('set names utf8');
            $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
            $rs = $db -> query($sql);
            $rs->setFetchMode(PDO::FETCH_ASSOC);
            if ($rs->rowCount() > 200000) {
                        exit('数据量过大，请重新选择。');
            }
            while($row = $rs -> fetch()){
                $printOrder = $this->getPrintOrder($row);
                if ($printOrder == false) {
                    continue;
                }
                $item = $printOrder['data'];
                foreach ($item['product']['data'] as $product) {
                    $eachRow = $this->doCsvRow($item, $product);
                    fputcsv($link, $eachRow);
                }
            }
        }
        $fileName=basename($flagFile);
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.$fileName);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($flagFile));
        ob_clean();
        flush();
        readfile($flagFile);
        unlink($flagFile);
        die();
    }

  public function doOldAction() {
    set_time_limit(0);
    @ini_set('memory_limit','1024M');
    $queryType = trim($this->getRequest()->getParam('type', ''));
    $queryMode = trim($this->getRequest()->getParam('mode', 0));
    $queryCode = trim($this->getRequest()->getParam('code', ''));

    if ('' === $queryType) {
      exit('Export Data Type Is Empty');
    }
    elseif (!in_array((int) $queryType, array(0, 1), TRUE)) {
      exit('Export Data Type Is Error');
    }
    elseif (1 === (int) $queryType && '' === $queryCode) {
      exit('Export Data Code Is Empty');
    }
    $file      = 'order-' . date('YmdHis') . '.xls';
    $queryType = (int) $queryType;
        $csvTitle = array();
        $csvTitle =   array(
        '客户公司名称','订单模式','订单状态','订单号','使用自有渠道','服务商单号','仓库',
        '收件人国家','收件人国家（英文名称）','国家简码','国内海关总申报价值（USD）','目的海关申报总价（USD）','运输方式','交易订单号','收件人姓名','收件人公司名','收件人州\区域','收件人城市','收件人邮编','收件人地址1','收件人地址2','收件人电话','收件人电子邮件','成交币种','成交总价','提交时间','出货时间','物流完成时间','香港交货时间','体积重','长*宽*高','实重','收费重量','件数','产品总数','备注','产品中文名称','sku','产品英文品名','海关品名','申报单价（USD）','目的海关申报单价（USD）','数量','海关编码');
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';
        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体');
        $table->getDefaultStyle()->getFont()->setSize(10);
        $table->setActiveSheetIndex(0);
        $table->setActiveSheetIndex(0)->setTitle($file);
        $objActSheet=$table->setActiveSheetIndex(0);
        $objActSheet->getColumnDimension('A')->setWidth(15);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('F')->setWidth(15);
        $objActSheet->getColumnDimension('N')->setWidth(20);
        $objActSheet->getColumnDimension('S')->setWidth(20);
        $objActSheet->getColumnDimension('V')->setWidth(20);
        $objActSheet->getColumnDimension('W')->setWidth(15);
        $objActSheet->getColumnDimension('AB')->setWidth(25);
        $objActSheet->getColumnDimension('AI')->setWidth(15);
        $objActSheet->getColumnDimension('AJ')->setWidth(15);
        $objActSheet->getColumnDimension('AK')->setWidth(15);
        $objActSheet->getColumnDimension('AO')->setWidth(15);
        $ascii=65;
        foreach ($csvTitle as $key => $value) {
          if ($ascii>90) {
            $as=chr($ascii-26);
            $objActSheet->setCellValue("A".$as."1",$value);
          }else{
            $objActSheet->setCellValue(chr($ascii)."1",$value);
          }
           $ascii++;
        }
       //echo $this->exportCsvForNotKey($csvTitle);
        unset($csvTitle);
    if (1 === $queryType) {
      $queryCode = explode('|', $queryCode);
      $printOrderInfo = $this->getPrintOrderInfo($queryCode);
    }
    else {
      $orderCode     = trim($this->getRequest()->getParam('order_code', ''));
      $orderStatus   = trim($this->getRequest()->getParam('order_status', '1'));
      $orderType     = trim($this->getRequest()->getParam('order_type', ''));
      $warehouseId   = trim($this->getRequest()->getParam('warehouse_id', ''));
      $smCode        = trim($this->getRequest()->getParam('shipping_method', ''));
      $addTimeStart  = trim($this->getRequest()->getParam('add_time_start', ''));
      $addTimeEnd    = trim($this->getRequest()->getParam('add_time_end', ''));
      $shipTimeStart = trim($this->getRequest()->getParam('ship_time_start', ''));
      $shipTimeEnd   = trim($this->getRequest()->getParam('ship_time_end', ''));
      $serviceTracking   = trim($this->getRequest()->getParam('service_tracking', ''));
      $condition['new_reference_no'] = $orderCode;
      $condition['warehouse_id']     = $warehouseId;
      $condition['order_type']       = $orderType;
      $condition['sm_code']          = $smCode;
      $condition['order_status_arr'] = explode(',', $orderStatus);
      $condition['order_mode_type']  = $queryMode;
      $condition['add_time_start']   = $addTimeStart;
      $condition['add_time_end']     = $addTimeEnd;
      $condition['ship_time_start']  = $shipTimeStart;
      $condition['ship_time_end']    = $shipTimeEnd;
      $customer = $this->_customerAuth;
      $condition['customer_id'] =$customer['id'];
      if($serviceTracking!=''&&$serviceTracking!='undefined'){
                 $shipOrderList=Service_ShipOrder::getByCondition(array('tracking_number'=>$serviceTracking),'order_code');
                 if(!empty($shipOrderList)){
                     $orderCodeArray=array();
                     foreach($shipOrderList as $so){
                         $orderCodeArray[]=$so['order_code'];
                     }
                     $condition['order_code']=$orderCodeArray;
                 }else{
                     $condition['ref_tracking_number']=$serviceTracking;
                 }
        }

        //print_r($condition);exit;
      $printOrderInfo = array(
        'data'=>array(),
        'maxProductQuantity' => 0
      );
      $orderRows     = Service_Orders::getByCondition($condition);
     /*  $count = Service_Orders::getByCondition($condition, 'count(*)');
      if ($count>0) {
        $pageSize = 100;
        $totalPage = ceil($count/$pageSize);
    for($page=1;$page<=$totalPage;$page++){
        $orderRows = Service_Orders::getByCondition($condition,"*", $pageSize, $page, array('order_id desc'));*/
        
      if(!empty($orderRows)){
        foreach ($orderRows as $key => $order) {
          $printOrder = $this->getPrintOrder($order);
          if($printOrder == false){
            continue;
          }

          if($printOrder['maxProductQuantity'] > $printOrderInfo['maxProductQuantity']){
            $printOrderInfo['maxProductQuantity'] = $printOrder['maxProductQuantity'];
          }
          $printOrderInfo['data'][$order['order_code']] = $printOrder['data'];
        }
      }
    }
    $index=2;
    $csvData=array();
//print_r($printOrderInfo['data'] );exit;
    foreach ($printOrderInfo['data'] as $item) {
      foreach ($item['product']['data'] as $product) {
      $oot=Service_OrderOperationTime::getByField($item['order']['order_code'],'order_code');
      $so=Service_ShipOrder::getByField($item['order']['order_code'],'order_code');
      $objActSheet->setCellValue("A".$index,$item['customer']['customer_company_name']);
      $objActSheet->setCellValue("B".$index,$item['order']['order_mode_desc']);
      $objActSheet->setCellValue("C".$index,$item['order']['order_status_desc']);
      $objActSheet->setCellValue("D".$index,$item['order']['order_code']);
      $objActSheet->setCellValue("E".$index,$item['order']['change_order_desc']);
      $objActSheet->setCellValueExplicit("F".$index,$item['order']['tracking_number'],PHPExcel_Cell_DataType::TYPE_STRING);
      $objActSheet->setCellValue("G".$index,$item['warehouse']['warehouse_code']);
      $objActSheet->setCellValue("H".$index,$item['address']['country']['country_name']);
      $objActSheet->setCellValue("I".$index,$item['address']['country']['country_name_en']);
      $objActSheet->setCellValue("J".$index,$item['address']['country']['country_code']);
      $objActSheet->setCellValueExplicit("K".$index,$item['order']['total_value_1'],PHPExcel_Cell_DataType::TYPE_NUMERIC);
      $objActSheet->setCellValueExplicit("L".$index,$item['order']['total_value_2'],PHPExcel_Cell_DataType::TYPE_NUMERIC);
      $objActSheet->setCellValue("M".$index,$item['order']['sm_code']);
      $objActSheet->setCellValueExplicit("N".$index,$item['order']['reference_no'],PHPExcel_Cell_DataType::TYPE_STRING);
      $objActSheet->setCellValue("O".$index,$item['address']['oab_firstname'] . $item['address']['oab_lastname']);
      $objActSheet->setCellValue("P".$index,$item['address']['oab_company']);
      $objActSheet->setCellValue("Q".$index,$item['address']['oab_state']);
      $objActSheet->setCellValue("R".$index,$item['address']['oab_city']);
      $objActSheet->setCellValueExplicit("S".$index,$item['address']['oab_postcode'],PHPExcel_Cell_DataType::TYPE_STRING);
      $objActSheet->setCellValue("T".$index,$item['address']['oab_street_address1']);
      $objActSheet->setCellValue("U".$index,$item['address']['oab_street_address2']);
      $objActSheet->setCellValueExplicit("V".$index,$item['address']['oab_cell_phone'],PHPExcel_Cell_DataType::TYPE_STRING);
      $objActSheet->setCellValueExplicit("W".$index,$item['address']['oab_email'],PHPExcel_Cell_DataType::TYPE_STRING);
      $objActSheet->setCellValue("X".$index,$item['order']['currency_code']);
      $objActSheet->setCellValue("Y".$index,$item['order']['charge']);
      $objActSheet->setCellValue("Z".$index,$item['order']['submit_time']);
      $objActSheet->setCellValue("AA".$index,$item['order']['ship_time']);
      $objActSheet->setCellValue("AB".$index,$oot['shipment_time']);
      $objActSheet->setCellValue("AC".$index,$item['order']['sot_add_time']);
      $objActSheet->setCellValueExplicit("AD".$index,$item['order']['vol_weight'],PHPExcel_Cell_DataType::TYPE_NUMERIC);
      $objActSheet->setCellValue("AE".$index,$item['order']['lwh_desc']);
      $objActSheet->setCellValueExplicit("AF".$index,$item['order']['real_weight'],PHPExcel_Cell_DataType::TYPE_NUMERIC);
      $objActSheet->setCellValueExplicit("AG".$index,$item['order']['fee_weight'],PHPExcel_Cell_DataType::TYPE_NUMERIC);
      //$objActSheet->setCellValue("AH".$index,$item['order']['piece_desc']);
      $objActSheet->setCellValue("AH".$index,$so['so_piece']);
      $objActSheet->setCellValueExplicit("AI".$index,$item['product']['quantity'],PHPExcel_Cell_DataType::TYPE_NUMERIC);
      $objActSheet->setCellValue("AJ".$index,$item['order']['remark']);

      $objActSheet->setCellValue("AK".$index,($item['order']['insurance'] == 1 ? '是' : '否'));
      $feeItemName = '';
      $deliveryDate = '';
      if( $item['order']['insurance'] == 1 ) {
            if( !isset( $insurance[$item['order']['insurance_code']] ) ) {
                $feeItem = Service_OtherFee::getByField($item['order']['insurance_code'],'fee_code');
                $feeItemName = $feeItem ? $feeItem['fee_name'] : '';
            }
          if( !isset($area[$item['address']['country']['country_id']])) {
                $countryRow = Service_Country::getByField($item['address']['country']['country_id']);
              $area[$item['address']['country']['country_id']] = $countryRow['country_area'];
          }
          $smCode = $item['order']['sm_code'];
          $areaCode = $area[$item['address']['country']['country_id']];
          if( $oot['shipment_time'] && $oot['shipment_time'] != '0000-00-00 00:00:00' && isset($limitation[$smCode][$areaCode])) {
              $limit = $limitation[$smCode][$areaCode];
              $deliveryDate =  date('Y-m-d',strtotime('+'.($limit+1).' day '.$oot['shipment_time'] ));
          }
      }
      $objActSheet->setCellValueExplicit("AL".$index,$feeItemName);
      $objActSheet->setCellValue("AM".$index,$deliveryDate);
      
      $objActSheet->setCellValue("AN".$index,$product['product_title']);
      $objActSheet->setCellValueExplicit("AO".$index,$product['product_sku'],PHPExcel_Cell_DataType::TYPE_STRING);
      $objActSheet->setCellValue("AP".$index,$product['product_title_en']);
      $objActSheet->setCellValue("AQ".$index,$product['hs_goods_name']);
      $objActSheet->setCellValueExplicit("AR".$index,$product['declared_value_1'],PHPExcel_Cell_DataType::TYPE_NUMERIC);
      $objActSheet->setCellValueExplicit("AS".$index,$product['declared_value_2'],PHPExcel_Cell_DataType::TYPE_NUMERIC);
      $objActSheet->setCellValueExplicit("AT".$index,$product['quantity'],PHPExcel_Cell_DataType::TYPE_NUMERIC);
      $objActSheet->setCellValueExplicit("AU".$index,$product['hs_code'],PHPExcel_Cell_DataType::TYPE_STRING);
      $index++;
      }
    }
     $styleArray = array(  
        'borders' => array(  
            'allborders' => array(  
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                //'color' => array('argb' => 'FFFF0000'),  
            ),  
        ),  
    );  
    $objActSheet->getStyle('A1:AR'.($index-1))->applyFromArray($styleArray);
        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel2007');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename={$file}");
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');
        die();
  }
public  function exportCsvForNotKey($data = array()){
        $str = '';
        if(!empty($data)){
            foreach ($data as $key => $val) {
              $new=array();
              $chars    = array( "\r\n" ,  "\n" ,  "\r" );
              foreach ($val as $key => $v) {
                 $newVal=str_replace(',','，',$v);
                 $newVal=str_replace($chars , " " , $newVal);
                 $newVal=iconv("UTF-8", "GBK//IGNORE" , $newVal);
                 $new[$key]=$newVal;
              }
              $str .= implode(',' , $new)."\r\n";
            }   
        }
        return $str;
    }


    public  function isNumericHandle($item){
        $item = str_replace(',','，',(string)$item);
        $chars    = array( "\r\n" ,  "\n" ,  "\r" );
        $item = str_replace($chars , ' ' , $item);
        $item = iconv("UTF-8", "GBK//IGNORE", $item);
        if(!is_numeric($item)){
            return "\t{$item}";
        }else{
           return "{$item}";
        }
    }
  private function getPrintOrder($order)
  {
    $response = array(
      'data'               => array(),
      'maxProductQuantity' => 0,
    );


    if(!$order){
      return false;
    }

    $orderCode = $order['order_code'];

    if (1 === (int) $order['order_mode_type']) { // 订单模式
        $order['order_mode_desc'] = '集货模式';
      }
      else {
        $order['order_mode_desc'] = '备货模式';
      }

      switch ((int) $order['order_status']) { // 订单状态描述
        case 0:
          $order['order_status_desc'] = '删除';
          break ;
        case 1:
          $order['order_status_desc'] = '草稿';
          break ;
        case 2:
          $order['order_status_desc'] = '确认';
          break ;
        case 3:
          $order['order_status_desc'] = '异常';
          break ;
        case 4:
        case 5:
        case 6:
        case 7:
        case 14:
          $order['order_status_desc'] = '已提交';
          break ;
        case 8:
        case 9:
        case 10:
        case 11:
        case 12:
          $order['order_status_desc'] = '仓库出货';
          break ;
        case 13:
          $order['order_status_desc'] = '已签收';
          break ;
        default:
          break ;
      }

      if (0 === (int) $order['change_order']) {
        $order['change_order_desc'] = '是';
      }
      else {
        $order['change_order_desc'] = '否';
      }

      $shipOrder    = Service_ShipOrder::getByField($orderCode, 'order_code');
      $orderTime    = Service_OrderOperationTime::getByField($orderCode, 'order_code');
      $shipTracking = Service_ShipOrderTracking::getByCondition(array('order_code' => $orderCode));
      $orderAddress = Service_OrderAddressBook::getByField($orderCode, 'order_code');
      $customer     = Service_Customer::getByField((int) $order['customer_id'], 'customer_id');
      $warehouse    = Service_Warehouse::getByField((int) $order['warehouse_id'], 'warehouse_id');
      $orderProduct = Service_OrderProduct::getByCondition(array('order_code' => $orderCode));
      $product      = array('data' => array(), 'quantity' => 0);
      $totalProduct = count($orderProduct); // 订单不重复产品数量
      $totalValue1  = 0; // 国内海关申报总值
      $totalValue2  = 0; // 目的海关申报总值

      $order['tracking_number'] = $order['ref_tracking_number']; // 订单跟踪号
      $order['real_weight']     = ''; // 订单实重
      $order['vol_weight']      = ''; // 订单体积重
      $order['lwh_desc']        = ''; // 长*宽*高
      $order['piece_desc']      = 0; // 件数

      // ship_order存在跟踪号则使用，否则使用order的跟踪号
      if (!empty($shipOrder) && '' !== trim($shipOrder['tracking_number'])) {
        $order['tracking_number'] = $shipOrder['tracking_number'];
      }
      else {
        $order['tracking_number'] = $order['ref_tracking_number'];
      }

      $fee_weight = '';
      if (!empty($shipOrder)) { // 订单实重
        $order['real_weight'] = $shipOrder['so_weight'];
        $fee_weight = $shipOrder['so_weight'];
      }

      if(!empty($shipOrder) && $shipOrder['so_fee_weight']>0){
          $fee_weight = $shipOrder['so_fee_weight'];
      }
      $order['fee_weight'] = $fee_weight;

      $shipTrackingRow['sot_add_time'] = '';//香港交货时间
      foreach ($shipTracking as $key => $value) {
        if($value['sot_info_type'] == '2'){
          $shipTrackingRow['sot_add_time'] = $value['sot_add_time'];
        }
      }

      foreach ($orderProduct as $item) {
        $p = Service_Product::getByField((int) $item['product_id'], 'product_id');

        if (1 === (int) $p['product_type']) { // 组合产品分拆
          $pc            = Service_ProductCombineRelation::getByCondition(array('product_id' => (int) $p['product_id']));
          $rate          = $this->calculateRate($p['product_id']); // 组合产品各个产品的申报价值比重
          $totalProduct += count($pc) - 1;

          foreach ($pc as $spi) {
            $sp                     = Service_Product::getByField((int) $spi['pcr_product_id'], 'product_id');
            $sp['quantity']         = $item['op_quantity'] * $spi['pcr_quantity']; // 单产品数量
            $sp['product_title_en'] = $item['product_title_en']; // 产品英文名称取order_product的值，组合产品各个子产品标题相同
            $sp['declared_value_1'] = $rate[$sp['product_id']] * $item['op_declared_value'];
            $sp['declared_value_2'] = $rate[$sp['product_id']] * $item['op_purpose_declared_value'];
            $product['data'][]      = $sp;
            $product['quantity']   += $sp['quantity']; // 计算订单总产品数量
            $totalValue1           += $sp['quantity'] * $sp['declared_value_1'];
            $totalValue2           += $sp['quantity'] * $sp['declared_value_2'];
          }
        }
        else { // 普通产品
          $p['quantity']         = $item['op_quantity'];
          $p['product_title_en'] = $item['product_title_en']; // 产品英文名称取order_product的值
          $p['declared_value_1'] = $item['op_declared_value'];
          $p['declared_value_2'] = $item['op_purpose_declared_value'];
          $product['data'][]     = $p;
          $product['quantity']  += $p['quantity'];
          $totalValue1          += $p['quantity'] * $p['declared_value_1'];
          $totalValue2          += $p['quantity'] * $p['declared_value_2'];
        }
      }

      $shipOrderDetail = Service_ShipOrderDetail::getByCondition(array('order_code' => $orderCode));
      $shippingMethod  = Service_ShippingMethod::getByField($order['sm_code'], 'sm_code');
      $tempLwh         = array();

      if (!empty($shipOrderDetail)) {
        $tempOtn = array();

        foreach ($shipOrderDetail as $sod) {
          if ('' !== trim($sod['sub_tracking_number'])) {
            $tempOtn[] = $sod['sub_tracking_number'];
          }

          if (1 === (int) $shippingMethod['sm_is_volume']) {
            $tempLwh[] = $sod['sod_length'] . '*' . $sod['sod_width'] . '*' . $sod['sod_height'];

            if (!empty($shippingMethod['sm_vol_rate'])) {
              $order['vol_weight'] += $sod['sod_length'] * $sod['sod_width'] * $sod['sod_height'] / $shippingMethod['sm_vol_rate'];
            }
          }
        }

        if (1 !== (int) $shippingMethod['sm_is_volume']) {
          $order['piece_desc'] = 1;
        }
        elseif ('HKDHL' === trim($order['sm_code'])) {
          $order['piece_desc'] = count($shipOrderDetail);
        }
        else {
          $order['piece_desc'] = count(array_unique($tempOtn));
        }
      }

      if (1 !== (int) $shippingMethod['sm_is_volume'] && !empty($shipOrder)) {
        $order['vol_weight'] = $shipOrder['so_vol_weight'];
        $tempLwh             = array($shipOrder['so_length'] . '*' . $shipOrder['so_width'] . '*' . $shipOrder['so_height']);
      }

      if ($order['piece_desc'] < 1) {
        $order['piece_desc'] = 1;
      }

      if ('' !== $order['vol_weight']) { // 保留两位小数
        $order['vol_weight'] = number_format($order['vol_weight'], 2);
      }

      $order['lwh_desc']   = join('/', $tempLwh);

      $order['total_value_1']       = number_format($totalValue1, 2); // 保留两位小数
      $order['total_value_2']       = number_format($totalValue2, 2); // 保留两位小数
      $order['total_product']       = $totalProduct;
      $order['ship_time']           = ('0000-00-00 00:00:00' !== $orderTime['ship_time']) ? $orderTime['ship_time'] : '';
      $order['submit_time']           = ('0000-00-00 00:00:00' !== $orderTime['submit_time']) ? $orderTime['submit_time'] : '';
      $order['sot_add_time']           = ('0000-00-00 00:00:00' !== $shipTrackingRow['sot_add_time']) ? $shipTrackingRow['sot_add_time'] : '';
      $orderAddress['country']      = Service_Country::getByField((int) $orderAddress['oab_country_id'], 'country_id');
      $response['data'] = array(
        'order'     => $order,
        'address'   => $orderAddress,
        'warehouse' => $warehouse,
        'customer'  => $customer,
        'product'   => $product,
      );    
      $response['maxProductQuantity'] = $totalProduct;    

      return $response;
  }
  /**
   * 获取需要导出的订单综合信息
   */
  private function getPrintOrderInfo($code = array()) {
    $response = array(
      'data'               => array(),
      'maxProductQuantity' => 0,
    );

    foreach ($code as $orderCode) {
      $order = Service_Orders::getByField($orderCode, 'order_code');

      if (empty($order)) {
        continue ;
      }

      $printOrder = $this->getPrintOrder($order);
      if($printOrder == false){
        continue;
      }

      if($printOrder['maxProductQuantity'] > $response['maxProductQuantity']){
        $response['maxProductQuantity'] = $printOrder['maxProductQuantity'];
      }

      $response['data'][$orderCode] = $printOrder['data'];        

    }

    return $response;
  }

  /**
   * 计算组合产品各个产品的申报价值比重
   */
  private function calculateRate($productId) {
    $pc = Service_ProductCombineRelation::getByCondition(array('product_id' => (int) $productId));

    if (empty($pc)) {
      return array();
    }

    $res   = array();

    foreach ($pc as $spi) {
      $sp                     = Service_Product::getByField((int) $spi['pcr_product_id'], 'product_id');
      $res[$sp['product_id']] = $sp['product_declared_value'] * $spi['pcr_quantity'];
    }

    $total = array_sum($res);

    foreach ($res as $i => $v) {
      $res[$i] = $v / $total;
    }

    return $res;
  }
    // doAction 拼接数组
    private function doCsvRow($item, $product)
    {
        $limitation = Service_ShippingMethod::getDeliveryLimitation();//时效
        $eachRow = array();
        $oot = Service_OrderOperationTime::getByField($item['order']['order_code'], 'order_code');
        $so = Service_ShipOrder::getByField($item['order']['order_code'], 'order_code');
        $eachRow[] = $item['customer']['customer_company_name'];
        $eachRow[] = $item['order']['order_mode_desc'];
        $eachRow[] = $item['order']['order_status_desc'];
        $eachRow[] = $item['order']['order_code'];
        $eachRow[] = $item['order']['change_order_desc'];
        $eachRow[] = $item['order']['tracking_number'] . "\t";
        $eachRow[] = $item['warehouse']['warehouse_code'];
        $eachRow[] = $item['address']['country']['country_name'];
        $eachRow[] = $item['address']['country']['country_name_en'];
        $eachRow[] = $item['address']['country']['country_code'];
        $eachRow[] = $item['order']['total_value_1'] . "\t";
        $eachRow[] = $item['order']['total_value_2'] . "\t";
        $eachRow[] = $item['order']['sm_code'];
        $eachRow[] = $item['order']['reference_no'] . "\t";
        $eachRow[] = $item['address']['oab_firstname'] . $item['address']['oab_lastname'];
        $eachRow[] = $item['address']['oab_company'];
        $eachRow[] = $item['address']['oab_state'];
        $eachRow[] = $item['address']['oab_city'];
        $eachRow[] = $item['address']['oab_postcode'] . "\t";
        $eachRow[] = $item['address']['oab_street_address1'];
        $eachRow[] = $item['address']['oab_street_address2'];
        $eachRow[] = $item['address']['oab_cell_phone'] . "\t";
        $eachRow[] = $item['address']['oab_email'] . "\t";
        $eachRow[] = $item['order']['currency_code'];
        $eachRow[] = $item['order']['charge'];
        $eachRow[] = $item['order']['submit_time'];
        $eachRow[] = $item['order']['ship_time'];
        $eachRow[] = $oot['shipment_time'];
        $eachRow[] = $item['order']['sot_add_time'];
        $eachRow[] = $item['order']['vol_weight'] . "\t";
        $eachRow[] = $item['order']['lwh_desc'];
        $eachRow[] = $item['order']['real_weight'] . "\t";
        $eachRow[] = $item['order']['fee_weight'] . "\t";
        $eachRow[] = $so['so_piece'] . "\t";
        $eachRow[] = $item['product']['quantity'] . "\t";
        $eachRow[] = $item['order']['remark'];

        $eachRow[] = $item['order']['insurance'] == 1 ? '是' : '否';
        $feeItemName = '';
          $deliveryDate = '';
          if( $item['order']['insurance'] == 1 ) {
                if( !isset( $insurance[$item['order']['insurance_code']] ) ) {
                    $feeItem = Service_OtherFee::getByField($item['order']['insurance_code'],'fee_code');
                    $feeItemName = $feeItem ? $feeItem['fee_name'] : '';
                }
              if( !isset($area[$item['address']['country']['country_id']])) {
                    $countryRow = Service_Country::getByField($item['address']['country']['country_id']);
                  $area[$item['address']['country']['country_id']] = $countryRow['country_area'];
              }
              $smCode = $item['order']['sm_code'];
              $areaCode = $area[$item['address']['country']['country_id']];
              if( $oot['shipment_time'] && $oot['shipment_time'] != '0000-00-00 00:00:00' && isset($limitation[$smCode][$areaCode])) {
                  $limit = $limitation[$smCode][$areaCode];
                  $deliveryDate =  date('Y-m-d',strtotime('+'.($limit+1).' day '.$oot['shipment_time'] ));
              }
          }
       $eachRow[] = $feeItemName;
       $eachRow[] = $deliveryDate;

        $eachRow[] = $product['product_title'];
        $eachRow[] = $product['product_sku'] . "\t";
        $eachRow[] = $product['product_title_en'];
        $eachRow[] = $product['hs_goods_name'];
        $eachRow[] = $product['declared_value_1'] . "\t";
        $eachRow[] = $product['declared_value_2'] . "\t";
        $eachRow[] = $product['quantity'] . "\t";
        $eachRow[] = $product['hs_code'] . "\t";
        return $eachRow;
    }
}
