<?php
/**
 * 退货订单信息查询
 */
class Merchant_ReturnOrderController extends Ec_Controller_Action {
  public function preDispatch() {
    $this->tplDirectory = 'merchant/views/product/';
    $params = self::getFrontController()->getRequest()->getParams();
    $this->view->ac = $params['action'];
    $this->view->url = $_SERVER['REDIRECT_URL'];
    $this->customerAuth = new Zend_Session_Namespace("customerAuth");
    $productUnit           = Service_ProductUom::getByCondition();
    $this->productUnit     = array();
    $this->productCategory = Common_DataCache::getProductCategory();

    foreach ($productUnit as $item) {
      $this->productUnit[$item['pu_code']] = $item;
    }
    
  }

  /**
   * 普通查询
   */
  public function listAction() {
    $customer = $this->_customerAuth;
    if ($this->getRequest()->isPost()) {
      $page = $this->_request->getParam('page', 1);
      $pageSize = $this->_request->getParam('pageSize', 20);

      $page = $page ? $page : 1;
      $pageSize = $pageSize ? $pageSize : 20;
      $productsku = $this->getRequest()->getPost('product_sku', '');
      $productsku = Service_ReturnOrderQuery::splitOrderCode($productsku);
      $response  = array(
        'state' => 0,
        'total' => 0,
        'data'  => array(),
        'msg'   => '找不到相匹配的数据',
      );

      if (!is_array($productsku)) {
        $response['msg'] = $productsku;

        die(Zend_Json::encode($response));
      }
      $data = Service_ReturnOrderQuery::queryOrderData($productsku,$customer['id']);
      if (count($data) > 0) {
        $response['state'] = 1;
        $response['data']  = $data;
      }
      unset($data);
      die(Zend_Json::encode($response));
    }
    $this->view->table = '';
    $this->view->productsku = '';
    echo Ec::renderTpl($this->tplDirectory . "return-order-list.tpl",'noleftlayout');
  }
    public function batchImportTempleteAction(){
      $fullPath = APPLICATION_PATH."/../data/file/sku-import.xls";
      //方法2
      $filename = basename($fullPath);
      header("Content-Type: APPLICATION/OCTET-STREAM");
      //Force the download
      $header="Content-Disposition: attachment; filename=".$filename.";";
      header($header );
      //  header("Content-Transfer-Encoding: binary");
      //  header("Content-Length: ".$len);
      echo file_get_contents($fullPath);
      exit;
    }
  /**
   * 查询结果导出
   */
/*  public function exportAction() {
    $productsku = trim($this->getRequest()->getParam('product_sku', ''));
    if ('' === $productsku) {
      exit('Export Data Type Is Empty');
    }

    $productsku = Service_ReturnOrderQuery::splitOrderCode($productsku);

    $filename  = 'return-sku-' . date('YmdHis').'.xls';
     if (!is_array($productsku)) {
        exit('sku错误');
      }
    set_time_limit(0);
    $data = Service_ReturnOrderQuery::queryOrderData($productsku);

    header('Pragma: public');
    header('Content-Type: application/x-msexecl; name=' . $filename);
    header('Content-Disposition: attachment; filename=' . $filename);

    $exportContent  = '<meta http-equiv="content-type" content="text/html;charset=utf-8" /><table border="1">';
    $exportContent .= '<tr>';
    $exportContent .= '<td>产品SKU</td>';
    $exportContent .= '<td>产品条码</td>';
    $exportContent .= '<td>产品名称</td>';
    $exportContent .= '<td>产品状态</td>';
    $exportContent .= '<td>产品重量</td>';
    $exportContent .= '<td>添加时间</td>';
    $exportContent .= '</tr>';


      foreach ($data as $key=>$item) {
        $exportContent .= '<tr>';
        $exportContent .= '<td style="vnd.ms-excel.numberformat:@;">' . $item['product_sku']. '</td>';
        $exportContent .= '<td style="vnd.ms-excel.numberformat:@;">' . $item['product_barcode']. '</td>';
        $exportContent .= '<td style="vnd.ms-excel.numberformat:@;">' . $item['product_title_en']. '</td>';
        if ($item['product_status']=='1') {
          $exportContent .= '<td style="vnd.ms-excel.numberformat:@;">已备案</td>';
        }else if($item['product_status']=='2'){
          $exportContent .= '<td style="vnd.ms-excel.numberformat:@;">草稿</td>';
        }else{
          $exportContent .= '<td style="vnd.ms-excel.numberformat:@;">备案中</td>';
        }
      $exportContent .= '<td style="vnd.ms-excel.numberformat:@;">' . $item['product_weight']. '</td>';
      $exportContent .= '<td style="vnd.ms-excel.numberformat:@;">' . $item['product_add_time']. '</td>';
        $exportContent .= '</tr>';
      }


    $exportContent .= '</table>';

    echo $exportContent;
    unset($printOrderInfo);
    exit();
  }*/
   public function exportAction() { 
        //获取数据
    $customer = $this->_customerAuth;
    $productsku  = $this->getRequest()->getPost('product_sku', '');
    if(!empty($productsku)){
    $productsku = preg_split('/\r\n/',$productsku);
    $filterCode = array();
  
    foreach ($productsku as $key => $value) {
      if ('' === trim($value)) {
        unset($productsku[$key]);
      }
      elseif (!isset($filterCode[$value])) {
        $productsku[$key]    = trim($value);
        $filterCode[$value] = 1;
      }
      else {
        unset($productsku[$key]);
      }
    }
  }
    $maxHsCount = 0; // 最大申报要素个数
    $product    = array();
    $pid=array();
    
    foreach ($productsku as $key => $value) {
     $sk= Service_Product::getByCondition(array('product_sku'=>trim($value),'customer_id'=>$customer['id']), '*');
     $pid[]=$sk[0]['product_id'];
    }

    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;
      }
    }
    
        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($product){
            foreach($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');  
    }


  /**
   * 导入订单号/交易订单号进行查询
   */
  public function importAction() {
    set_time_limit(300);
    ini_set('memory_limit','512M');   
    $ReturnOrder = new Zend_Session_Namespace('ReturnOrder');
    $page=1;
    $pageSize=$this->_request->getParam('pageSize','20');
    $count=0;
    $field = 'skuFile';   
    $xlsData = self::getXLSData($_FILES, $field);
      $customer = $this->_customerAuth;
      $productsku=array();
      $sku='';
      foreach ($xlsData as $key => $value) {
        if ($key==0) {
          continue;
        }
       $sku=$value[0];
          if ('' === trim($sku)) {
              unset($productsku[$key]);
            }
            elseif (!isset($filterCode[$sku])) {
              $productsku[$key]    = trim($sku);
              $filterCode[$sku] = 1;
            }
            else {
              unset($productsku[$key]);
            }
        $productsku[]=$sku;
      }
      array_pop($productsku);
      $data = Service_ReturnOrderQuery::queryOrderData($productsku,$customer['id'],true);
      $ReturnOrder->data=$data;
      $start=($page-1)*$pageSize;
      $start=(int)$start>=0?(int)$start:0;
      $data=array_slice($ReturnOrder->data,$start,$pageSize);
      $table=  Service_ReturnOrderQuery::createSearchSkuTable($data);
      $count=count($ReturnOrder->data);
      $sku='';
      foreach ($ReturnOrder->data as $key => $value) {
          $sku.=$value['product_sku'].'&#13;&#10;';
      }
        $ReturnOrder->sku=$sku;
        $ReturnOrder->count=$count;
        $this->view->productsku=$sku;
        $this->view->table = $table;
        $this->view->count=$count;
        $this->view->page=$page;
        $this->view->pageSize=$pageSize;
      echo Ec::renderTpl($this->tplDirectory . "return-order-list.tpl",'noleftlayout');
  }
  public function importListAction() {
        $ReturnOrder = new Zend_Session_Namespace('ReturnOrder');
        $page = $this->_request->getParam('page', 1);
        $pageSize = $this->_request->getParam('pageSize', 20);
        if (!$ReturnOrder->data) {
            echo Ec::renderTpl($this->tplDirectory . "return-order-list.tpl", 'noleftlayout');
            die();
        }
        $start = ($page - 1) * $pageSize;
        $start = (int) $start >= 0 ? (int) $start : 0;
        $data = array_slice($ReturnOrder->data, $start, $pageSize,true);
        $table = Service_ReturnOrderQuery::createSearchSkuTable($data);
        $this->view->productsku = $ReturnOrder->sku;
        $this->view->table = $table;
        $this->view->count = $ReturnOrder->count;
        $this->view->page = $page;
        $this->view->pageSize = $pageSize;
        echo Ec::renderTpl($this->tplDirectory . "return-order-list.tpl", 'noleftlayout');
    }
    public static function getXLSData($uploadFile,$field){
    ini_set('memory_limit','1024M');
    
    $customerAuth = new Zend_Session_Namespace("customerAuth");

    $customer = $customerAuth->data;
    $customerId = $customer['id'];

    $path = APPLICATION_PATH.'/../data/productbatchupload/';
    $path.= $customerId;
    if(!file_exists($path)){
      if(!mkdir($path,0700,true)){
        $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('上传目录不存在创建文件目录失败'));
        return $result;
      }
    }   
    $config = array();
    $config['upload_path']    = $path;
    $config['allowed_types']  = 'xls|xlsx';
    $config['max_size']     = '5250000';
    $config['encrypt_name']   = true;   
    $upload = new Common_UploadFile($config);
    $upload->set_upload_path($path);    
    if (!$upload->do_upload($_FILES,$field) ){
      $result['ask'] = '0';
      $result['message'] = '上传文件失败';
      $result['error'] =  $upload->display_errors();
      return $result;
      exit;
    }
    
    $resultArray = $upload->data();
    $full_path = $resultArray['full_path'];
    if(empty($resultArray) || empty($full_path)){
      $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('数据不存在'));
      return $result;
      exit;
    }
    
    $resultArray = Common_Upload::readEXCEL($full_path);
    /* if(empty($resultArray) || !is_array($resultArray)){
      $result = array("ask"=>0,"message"=>"文件内容不符合格式或数据为空.",'error'=>array());
      echo json_encode($result);
      exit;
    } */
    
    @unlink($full_path);
    return $resultArray;
  } 
    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 '';
  }
}
