<?php
/**
 * 订单退货相关信息查询
 */
class Service_ReturnOrderQuery {
  /**
   * 获取缓存目录
   * 
   * @return string    返回缓存存放的目录
   */
  public static function getCacheDir() {
    return str_replace('\\', '/', realpath(APPLICATION_PATH . '/../data/cache')) . '/';
  }

  /**
   * 把Excel文件临时缓存为PHP数组，以便后续使用
   * 
   * @param string  $file    上传订单数据的EXCEL文件
   * @return array    array(
   *                    'status'  => 'integer|0：失败；1：成功',
   *                    'message' => 'string|失败：错误信息；成功：缓存文件名'
   *                  )
   */
  public static function buildCache($file) {
    $response = array('status' => 0, 'message' => '');

    if (!is_file($file)) { // 判断文件是否存在
      $response['message'] = '缓存文件【' . $file . '】不存在';

      return $response;
    }

    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); // 文件扩展名

    if (!in_array($ext, array('xls', 'xlsx'), TRUE)) { // 允许的文件类型
      $response['message'] = '文件类型【' . $ext . '】错误，仅支持xls或xlsx类型文件';
      @unlink($file); // 删除文件

      return $response;
    }

    require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
    require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

    set_time_limit(0); // 不限制执行时间
    ini_set('memory_limit', '2048M'); // 2G内存限制

    $loaderObj = PHPExcel_IOFactory::load($file); // 加载Excel文件

    if (!$loaderObj) {
      $response['message'] = '文件解析失败，请确保所上传的文件类型为xls或xlsx';
      @unlink($file); // 删除文件

      return $response;
    }

    $sheetObj = $loaderObj->getSheet(0); // 获取第一个工作表
    $maxCols  = PHPExcel_Cell::columnIndexFromString($sheetObj->getHighestColumn()); // 最大列数
    $maxRows  = $sheetObj->getHighestRow(); // 最大行数
    $cacheDir = self::getCacheDir();
    $data     = array();
    $repeat   = array(); // 缓存订单号，排查重复单号

    for ($i = 2; $i <= $maxRows; ++$i) { // 排除表头，从第2行开始读取
      $orderCode = trim($sheetObj->getCell('A' . $i)->getValue());

      if ('' !== $orderCode) {
        if (isset($repeat[$orderCode])) {
          continue ;
        }

        $repeat[$orderCode] = 1;
        $orderData          = self::queryOrderData(array($orderCode));

        if (!empty($orderData)) {
          foreach ($orderData as $item) {
            $data[] = $item;
          }
        }
      }
    }

    if (!empty($data)) {
      $tmp   = date('YmdHis-') . md5('RETURN-ORDER-' . microtime(TRUE)) . '.php'; // 临时文件名
      $cache = '<?php return ' . var_export($data, TRUE) . '; ?>'; // 缓存内容
  
      if (FALSE === file_put_contents($cacheDir . $tmp, $cache)) { // 生成缓存文件
        $response['message'] = '生成缓存文件时发生异常';
      }
      else {
        $response = array('status' => 1, 'message' => $tmp);
      }
    }
    else {
      $response['message'] = '没有找到相匹配的数据';
    }

    unset($data);
    unset($repeat);
    @unlink($file); // 删除文件

    return $response;
  }

  /**
   * 提取产品SKU
   * 
   * @param string $orderCode    输入的单号（订单号/交易订单号）
   * @param string $delimiter    分隔符
   * @return string|array
   */
  public static function splitOrderCode($productsku, $delimiter = '\r\n') {
    //$productsku = str_replace(array("\r"), '', $productsku);
    $productsku = trim($productsku);

    if ('' === $productsku) {
      return '请提供产品SKU';
    }

    //$productsku  = explode($delimiter, $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]);
      }
    }

    $total = count($productsku);
 //print_r($productsku);exit;
    if ($total > 0 && $total <= 10) {
      return $productsku;
    }

    return ($total > 10) ? '最多只接收10个SKU' : '请提供产品SKU';
  }

  /**
   * 查询所需要的产品信息
   * 
   * @param array $product    产品sku
   * @return array
   */
  public static function queryOrderData(array $productsku,$customerId) {
    $data = array();

    foreach ($productsku as $code) {
      $product = Service_Product::getByCondition(array(
        'product_sku' => $code,'customer_id'=>$customerId
      ));

      if (empty($product) || count($product) > 1) {
        continue ;
      }

      $product          = $product[0];
/*      if ($product['product_status']=='1') {
        $product['product_status']='已备案';
      }else if($product['product_status']=='2'){
        $product['product_status']='草稿';
      }else{
        $product['product_status']='备案中';
      }*/
      $data[]=array(
        'product_sku'=>$product['product_sku'],
        'product_barcode'=>$product['product_barcode'],
        'product_title'=>$product['product_title'],
        'product_status'=>$product['product_status'],
        'product_weight'=>$product['product_weight'],
        'product_add_time'=>$product['product_add_time']  
      );

    }
//print_r($data);exit;
    return $data;
  }

  /**
   * 计算组合产品各个产品比率
   * 
   * @param integer $productId    组合产品ID
   * @return array
   */
  public static function productRate($productId) {
    $rate           = array();
    $totalDeclare   = 0;
    $productCombine = Service_ProductCombineRelation::getByCondition(array('product_id' => (int) $productId));

    if (empty($productCombine)) {
      return $rate;
    }

    foreach ($productCombine as $item) {
      $product = Service_Product::getByField((int) $item['pcr_product_id'], 'product_id');

      if (empty($product)) {
        continue ;
      }

      $totalDeclare                += $product['product_declared_value'] * $item['pcr_quantity'];
      $rate[$product['product_id']] = array(
        'quantity'      => $item['pcr_quantity'],
        'hs_goods_name' => $product['hs_goods_name'],
        'product_sku'   => $product['product_sku'],
        'declare'       => $product['product_declared_value'],
        'tax_rate'      => $product['parcel_tax'],
      );
    }

    if ($totalDeclare > 0) { // 计算产品比重
      foreach ($rate as $id => $item) {
        $rate[$id]['proportion'] = $item['quantity'] * $item['declare'] / $totalDeclare;
      }

      return $rate;
    }

    return array();
  }
  public static function createSearchSkuTable($data){
        $table = "";
        foreach ($data as $key => $item) {
            $table .= '<tr class="table-module-b1">';
            $table .= '<td class="ec-center">' . ($key + 1) . '</td>';
            $table .= '<td class="ec-center">' . $item['product_sku'] . '</td>';
            $table .= '<td class="ec-center">' . $item['product_barcode'] . '</td>';
            $table .= '<td class="ec-center">' . $item['product_title'] . '</td>';
            if ($item['product_status'] == '2') {
                $table .= '<td class="ec-center">草稿</td>';
            } else if ($item['product_status'] == '1') {
                $table .= '<td class="ec-center">已备案</td>';
            } else {
                $table .= '<td class="ec-center">备案中</td>';
            }

            $table .= '<td class="ec-center">' . $item['product_weight'] . '</td>';
            $table .= '<td class="ec-center">' . $item['product_add_time'] . '</td>';
            $table .= '</tr>';
        }
        return $table;
      
  }
}
