<?php
class Merchant_ProductExportController extends Ec_Controller_Action {
  public function preDispatch() {
    // Intentionally left blank

    $productUnit           = Service_ProductUom::getByCondition();
    $this->productUnit     = array();
    $this->productCategory = Common_DataCache::getProductCategory();

    foreach ($productUnit as $item) {
      $this->productUnit[$item['pu_code']] = $item;
    }
  }

  public function indexAction() {
    echo 'Intentionally left blank ...';
    exit();
  }

  /**
   * 产品信息导出动作
   */
    public function exportAction() { 
        //获取数据
        $export = $this->exportProduct();
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';
        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体')->setSize(10); 
        $objActSheet    =   $table->setActiveSheetIndex(0);    
        $objActSheet->setTitle(Ec_Lang::getInstance()->getTranslate('product'));
        //单元样式
        $tableStyle =   array(
                            'allborders' => array(
                                 'style' => PHPExcel_Style_Border::BORDER_THIN,
                                 'color' => array(
                                      'rgb' => '000000'
                                 )
                            )
                       );
        //设置标题
        $objTitleArr    =   array ('a' => '客户代码','b' => '产品SKU','c' => '条码类型','d' => '产品代码','e' => '产品名称','f' => '英文名','g' => '状态','h' => '单位','i' => '申报币种','j' => '申报价值','k' => '产品重量（KG）','l' => '海关编码','m' => '海关品名','n' => '招海料号','o' => '产品品类','p' => '供应商代码','q' => '长（CM）','r' => '宽（CM）','s' => '高（CM）','t' => '产品接收类型','u' => '质检类型','v' => '产品分类','w' => '产品添加时间','x' => '是否属于零件类','y' => '有无发票','z' => '产品型号','aa' => '法定单位','ab' => '法定数量','ac' => '第二法定单位','ad' => '第二法定数量','ae' => '要素代码','af' => '要素名称','ag' => '申报要素内容','ah' => '法定单位','ai' => '法定数量','aj' => '第二法定单位','ak' => '第二法定数量','al' => '要素代码','am' => '要素名称','an' => '申报要素内容','ao' => '法定单位','ap' => '法定数量','aq' => '第二法定单位','ar' => '第二法定数量','as' => '要素代码','at' => '要素名称','au' => '申报要素内容','av' => '法定单位','aw' => '法定数量','ax' => '第二法定单位','ay' => '第二法定数量','az' => '要素代码','ba' => '要素名称','bb' => '申报要素内容','bc' => '法定单位','bd' => '法定数量','be' => '第二法定单位','bf' => '第二法定数量','bg' => '要素代码','bh' => '要素名称','bi' => '申报要素内容');
        foreach($objTitleArr AS $key=>$val){                
            $objActSheet->getColumnDimension($key)->setWidth(10);
            $objActSheet->setCellValue("{$key}1",$val);
            $objActSheet->getStyle("{$key}1")->getBorders()->applyFromArray($tableStyle);
        } 
        //数据起始行
        $index		= 2;
        if($export['product']){
            foreach($export['product'] AS $productInfo){
                $objActSheet->setCellValueExplicit("A".$index,$productInfo['customer_code'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("B".$index,$productInfo['product_sku'],PHPExcel_Cell_DataType::TYPE_STRING);                                                    
                $objActSheet->setCellValueExplicit("C".$index,$this->getStatusText($productInfo['product_barcode_type'], 'BARCODE'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("D".$index,$productInfo['product_barcode'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("E".$index,$productInfo['product_title'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("F".$index,$productInfo['product_title_en'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("G".$index,$this->getStatusText($productInfo['product_status'], 'PS'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("H".$index,$this->getStatusText($productInfo['pu_code'], 'UNIT'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("I".$index,$productInfo['currency_code'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("J".$index,$productInfo['product_declared_value'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("K".$index,$productInfo['product_weight'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("L".$index,$productInfo['hs_code'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("M".$index,$productInfo['hs_goods_name'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("N".$index,$productInfo['goods_id'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("O".$index,$this->getStatusText($productInfo['pc_id'], 'CATEGORY'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("P".$index,$this->getStatusText($productInfo['distributor_id'], 'DISTRIBUTOR'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("Q".$index,$productInfo['product_length'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("R".$index,$productInfo['product_width'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("S".$index,$productInfo['product_height'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("T".$index,$this->getStatusText($productInfo['product_receive_status'], 'PRS'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("U".$index,$this->getStatusText($productInfo['product_is_qc'], 'QC'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("V".$index,$this->getStatusText($productInfo['product_type'], 'PT'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("W".$index,$productInfo['product_add_time'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("X".$index,$this->getStatusText($productInfo['is_accessories'], 'PART'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("Y".$index,$this->getStatusText($productInfo['has_invoice'], 'INVOICE'),PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("Z".$index,$productInfo['model_serial'],PHPExcel_Cell_DataType::TYPE_STRING);
                $Pi = 'AA';
                if(isset($productInfo['hs_info']['data']) && $productInfo['hs_info']['data']){                    
                    foreach ($productInfo['hs_info']['data'] as $key => $value) {
                        $objActSheet->setCellValueExplicit($Pi++.$index , $productInfo['hs_info']['first_unit'] , PHPExcel_Cell_DataType::TYPE_STRING);
                        $objActSheet->setCellValueExplicit($Pi++.$index , $productInfo['hs_info']['first_quantity'], PHPExcel_Cell_DataType::TYPE_NUMERIC);
                        $objActSheet->setCellValueExplicit($Pi++.$index , $productInfo['hs_info']['second_unit']  , PHPExcel_Cell_DataType::TYPE_STRING);
                        $objActSheet->setCellValueExplicit($Pi++.$index , $productInfo['hs_info']['second_quantity'] , PHPExcel_Cell_DataType::TYPE_NUMERIC);
                        $objActSheet->setCellValueExplicit($Pi++.$index , $value['name'] , PHPExcel_Cell_DataType::TYPE_STRING);#要素代码
                        $objActSheet->setCellValueExplicit($Pi++.$index , $value['name'] , PHPExcel_Cell_DataType::TYPE_STRING);#要素名称
                        $objActSheet->setCellValueExplicit($Pi++.$index , $value['description'] , PHPExcel_Cell_DataType::TYPE_STRING);                                  
                    }
                }
                $index++;
            }
        }
  
        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel5');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename=product".date('Y-m-d').".xls");
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');  
    }

  /**
   * 导出产品信息
   */
  private function exportProduct() {
    $type = trim($this->getRequest()->getParam('type', ''));

    if ('' !== $type) {
      $type = (int) $type;
    }

    if (0 === $type) {
      return $this->exportSelectedProduct();
    }
    elseif (1 === $type) {
      return $this->exportAllProduct();
    }

    exit('ERROR: EXPORT TYPE IS NOT AVALID ...');
  }

  /**
   * 导出所选的产品信息
   */
  private function exportSelectedProduct() {
    $pid        = $this->getRequest()->getParam('pid', array());
    $maxHsCount = 0; // 最大申报要素个数
    $product    = array();

    if (is_string($pid)) {
      $pid = explode('|', $pid);
    }

    foreach ($pid as $productId) {
      $item = Service_Product::getByField((int) trim($productId), 'product_id');

      if (!empty($item)) {
        $distributor     = array();

        if (0 !== $item['distributor_id']) {
          $distributor = Service_Distributor::getByPrimaryKey($item['distributor_id']);
        }

        $item['distributor_code'] = $distributor ? $distributor['distributor_code'] : '';

        // START - 申报要素整合
        $item['hs_info']['first_unit']      = '';
        $item['hs_info']['second_unit']     = '';
        $item['hs_info']['first_quantity']  = '';
        $item['hs_info']['second_quantity'] = '';
        $item['hs_info']['data']            = array();
        $hsUnit                             = array();
        $hsElement                          = array();

        if ('' !== trim($item['hs_code'])) { // 有海关编码才去数据库检索数据
          $hsUnit = Service_HsUom::getByCondition(array( // 法定单位
            'hs_code'   => $item['hs_code'],
            'hu_status' => 1,
          ));

          $hsElement = Service_HsElement::getByCondition(array( // 申报要素
            'hs_code'   => $item['hs_code'],
            'he_status' => 1,
          ));
        }

        if (!empty($hsUnit)) {
          $hsUnit = $hsUnit[0];

          if ('' !== $hsUnit['pu_code_law']) {
            $item['hs_info']['first_unit'] =  $this->getStatusText($hsUnit['pu_code_law'], 'UNIT');
          }

          if ('' !== $hsUnit['pu_code_second']) {
            $item['hs_info']['second_unit'] = $this->getStatusText($hsUnit['pu_code_second'], 'UNIT');
          }

          // 凭法定单位ID提取法定数量
          $hum_condition    = array(
            'hu_id'         => (int) $hsUnit['hu_id'],
            'product_id'    => $item['product_id'],
          );
          $hsQuantity                         = Service_HsUomMap::getByCondition($hum_condition);
          $item['hs_info']['first_quantity']  = (!empty($hsQuantity)) ? $hsQuantity[0]['hum_quantity_law']    : '';
          $item['hs_info']['second_quantity'] = (!empty($hsQuantity)) ? $hsQuantity[0]['hum_quantity_second'] : '';
        }

        if (!empty($hsElement)) {
          $hsCount    = count($hsElement);
          $maxHsCount = $hsCount > $maxHsCount ? $hsCount : $maxHsCount;

          foreach ($hsElement as $e) {
            $hem_condition              = array(
                'he_id'         => (int) $e['he_id'],
                'product_id'    => $item['product_id'],
            );
            $hsElementMap               = Service_HsElementMap::getByCondition($hem_condition);
            $item['hs_info']['data'][] = array(
              'code'        => $e['he_code'],
              'name'        => $e['he_name'],
              'description' => (!empty($hsElementMap)) ? $hsElementMap[0]['hem_detail'] : '',
            );
          }
        }
        // END - 申报要素整合

        $product[] = $item;
      }
    }

    return array(
      'max_element' => $maxHsCount,
      'product'     => $product,
    );
  }

  /**
   * 导出所有产品信息
   */
  private function exportAllProduct() {
    $params        = $this->getRequest()->getParams();
    $productSku    = isset($params['E1'])  ? trim($params['E1'])  : '';
    $customerCode  = isset($params['E3'])  ? trim($params['E3'])  : '';
    $productStatus = isset($params['E7'])  ? trim($params['E7'])  : '';
    $productIsQc   = isset($params['E18']) ? trim($params['E18']) : '';
    $has_invoice = isset($params["E26"])? trim($params['E26']):"";
    $condition     = array(
      'product_type' => '0', // 只能导出普通产品
    );

    $condition	= array(
        'customer_id'		=> $this->_customerAuth['id'],
        'product_type'		=> $this->getRequest()->getParam('product_type'),
        'comefrom'              => 1,
        'product_sku'		=> $this->getRequest()->getParam('sku'),
        'product_title'		=> $this->getRequest()->getParam('title'),
        'product_add_time'	=> $this->getRequest()->getParam('start_time'),
        'product_end_time'	=> $this->getRequest()->getParam('end_time'),
        'product_status'	=> $this->getRequest()->getParam('status')			
    );

    $maxHsCount = 0; // 最大申报要素个数
    $product    = Service_Product::getAllByCondition($condition);
//print_r($product);
//die();
    if (!empty($product)) {
      foreach ($product as $key => $item) {
        $distributor     = array();

        if (0 !== $item['distributor_id']) {
          $distributor = Service_Distributor::getByPrimaryKey($item['distributor_id']);
        }

        $item['distributor_code'] = $distributor ? $distributor['distributor_code'] : '';

        // START - 申报要素整合
        $item['hs_info']['first_unit']      = '';
        $item['hs_info']['second_unit']     = '';
        $item['hs_info']['first_quantity']  = '';
        $item['hs_info']['second_quantity'] = '';
        $item['hs_info']['data']            = array();
        $hsUnit                             = array();
        $hsElement                          = array();

        if ('' !== trim($item['hs_code'])) { // 有海关编码才去数据库检索数据
          $hsUnit = Service_HsUom::getByCondition(array( // 法定单位
            'hs_code'   => $item['hs_code'],
            'hu_status' => 1,
          ));

          $hsElement = Service_HsElement::getByCondition(array( // 申报要素
            'hs_code'   => $item['hs_code'],
            'he_status' => 1,
          ));
        }

        if (!empty($hsUnit)) {
          $hsUnit = $hsUnit[0];

          if ('' !== $hsUnit['pu_code_law']) {
            $item['hs_info']['first_unit'] = $this->getStatusText($hsUnit['pu_code_law'], 'UNIT');
          }

          if ('' !== $hsUnit['pu_code_second']) {
            $item['hs_info']['second_unit'] = $this->getStatusText($hsUnit['pu_code_second'], 'UNIT');
          }

          // 凭法定单位ID提取法定数量
          $hum_condition    = array(
            'hu_id'         => (int) $hsUnit['hu_id'],
            'product_id'    => $item['product_id'],
          );
          $hsQuantity                         = Service_HsUomMap::getByCondition($hum_condition);
          $item['hs_info']['first_quantity']  = (!empty($hsQuantity)) ? $hsQuantity[0]['hum_quantity_law']    : '';
          $item['hs_info']['second_quantity'] = (!empty($hsQuantity)) ? $hsQuantity[0]['hum_quantity_second'] : '';
        }

        if (!empty($hsElement)) {
          $hsCount    = count($hsElement);
          $maxHsCount = $hsCount > $maxHsCount ? $hsCount : $maxHsCount;

          foreach ($hsElement as $e) {
            $hem_condition              = array(
                'he_id'         => (int) $e['he_id'],
                'product_id'    => $item['product_id'],
            );
            $hsElementMap               = Service_HsElementMap::getByCondition($hem_condition);
            $item['hs_info']['data'][] = array(
              'code'        => $e['he_code'],
              'name'        => $e['he_name'],
              'description' => (!empty($hsElementMap)) ? $hsElementMap[0]['hem_detail'] : '',
            );
          }
        }
        // END - 申报要素整合

        $product[$key] = $item;
      }

      return array(
        'max_element' => $maxHsCount,
        'product'     => $product,
      );
    }

    return array(
      'max_element' => $maxHsCount,
      'product'     => array(),
    );
  }

  /**
   * 获取状态值相对应的文本值
   * 
   * @param integer|string $status 状态值
   * @param string $type 类型
   */
  private function getStatusText($status, $type) {
    $status = $status;
    $type = strtoupper($type);
    $text = array(
      'PT' => array( // 产品类型
        0 => '普通产品',
        1 => '组合产品',
      ),
      'PS' => array( // 产品状态
        0 => '备案中',
        1 => '已备案',
        2 => '草稿',
      ),
      'BARCODE' => array( // 条码类型
        0 => '默认条码',
        1 => '自定义条码',
        2 => '序列号',
      ),
      'QC' => array( // 是否质检
        0 => '不质检',
        1 => '质检',
      ),
      'PART' => array( // 是否零件
        0 => '否',
        1 => '是',
      ),
      'INVOICE' => array( // 是否带发票
        1 => '有',
        2 => '无',
      ),
      'UNIT' => array(
        'EA'   => '个',
        'KG'   => '公斤',
        'MT'   => '米',
        'CASE' => '盒',
        'PC'   => '件',
        'SET'  => '套',
      ),
      'PRS' => array( // 产品接收类型
        0 => '新产品',
        1 => '已收过货产品',
      ),
    );

    if ('UNIT' === $type && isset($this->productUnit[$status])) {
      return $this->productUnit[$status]['pu_name'];
    }
    elseif ('CATEGORY' === $type && isset($this->productCategory[$status])) {
      return $this->productCategory[$status]['pc_name'];
    }
    elseif (isset($text[$type][$status])) {
      return $text[$type][$status];
    }else if($type == 'DISTRIBUTOR'){
        $distributor    = Service_Distributor::getByPrimaryKey($status);
        return $distributor['distributor_code'];
    }

    return '';
  }
}
