<?php
/**
 * 区外仓运单，导入运单数据进行装袋的同时进行收货相关动作
 */
class Service_LogisticsPr {
  /**
   * 获取缓存目录
   * 
   * @return string    返回缓存存放的目录
   */
  public static function getCacheDir() {
    return APPLICATION_PATH . '/../data/cache/';
  }

  /**
   * 判断是否存在缓存文件
   * 
   * @param string $cache    缓存文件名
   * @return boolean
   */
  public static function isCache($cache) {
    $cache = trim($cache);

    // 合法缓存文件名为后缀为'.php'
    if (FALSE === strpos($cache, '.php')) {
      return FALSE;
    }

    return is_file(self::getCacheDir() . $cache);
  }

  /**
   * 删除缓存文件
   * 
   * @param string $cache    文件名
   * @return boolean
   */
  public static function removeCache($cache) {
    $cache = trim($cache);

    if (!self::isCache($cache)) {
      return FALSE;
    }

    return unlink(self::getCacheDir() . $cache);
  }

  /**
   * 适用运输方式
   * 
   * @return array
   */
  public static function getShippingMethod() {
    return array(
      '香港挂号' => 'HKPG', // 香港挂号
      '香港平邮' => 'HKPP', // 香港平邮
      '香港敦豪国际速递' => 'HKDHL', // 香港平邮
      '区外DHL' => 'HKDHL-BQC',
      'HKDHL区外' => 'HKDHL-JLY',
      '俄罗斯小包挂号'=> 'SF-RUPR',
      '俄罗斯小包平邮'=> 'SF-RUPT',
      'HKDHL小货促销价'=>'BH-HKDHL',
      '新加坡小包挂号'=>'BH-SGG',
      '新加坡小包平邮'=>'BH-SGP',
    );
  }

  /**
   * 把Excel文件临时缓存为PHP数组，以便后续使用
   * 
   * @param string  $file    运单数据EXCEL文件
   * @return array
   */
  public static function buildCache($file) {
    $response = array('status' => 0, 'message' => '');
    $method   = self::getShippingMethod();
    $data     = array(
      'valid'  => TRUE, // 整体数据的有效性
      'weight' => 0, // 总重量
      'dross'  => 0, // 不符合条件的订单数量
      'upload' => array(), // 上传的运单数据
    );

    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类型文件';
      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';
      return $response;
    }

    $sheetObj = $loaderObj->getSheet(0); // 获取第一个工作表
    $maxCols  = PHPExcel_Cell::columnIndexFromString($sheetObj->getHighestColumn()); // 最大列数
    $maxRows  = $sheetObj->getHighestRow(); // 最大行数
    $cacheDir = self::getCacheDir();
    $transfer = array(); // 缓存转单号，查验是否有重复的
    $internal = array(); // 缓存内部单号，查验是否有重复的
    $country  = array(); // 缓存国家，避免对同一个国家进行多余的数据库查询验证

    if ($maxRows < 2) { // 没有数据上传
      $response['message'] = '所上传EXCEL文件缺乏数据';

      return $response;
    }

    for ($i = 2; $i <= $maxRows; ++$i) { // 排除表头，从第2行开始读取
      $data['upload'][$i - 2] = array(
        'valid'    => TRUE, // 数据有效性
        'data'     => array(), // 上传的数据
        'code'     => '', // 与系统匹配的物流单号
        'customer' => '', // 客户代码
        'sm_code'  => '', // 运输代码
        'country'  => '', // 目的地国家ID
        'message'  => '', // 验证结果
      );

      for ($j = 0; $j < $maxCols; ++$j) { // 读取各个单元格的内容
        $data['upload'][$i - 2]['data'][self::getMapIndex($j)] = trim($sheetObj->getCell(PHPExcel_Cell::stringFromColumnIndex($j) . $i)->getValue());
      }

      $errorTip = array();

      if (!isset($method[$data['upload'][$i - 2]['data']['type']])) {
        $errorTip[] = '快递类型不存在';
      }
      else {
        $data['upload'][$i - 2]['sm_code'] = $method[$data['upload'][$i - 2]['data']['type']];
      }

      if ('' === $data['upload'][$i - 2]['data']['tracking_number']) {
        $errorTip[] = '转单号不能为空';
      }
      else {
        if (isset($transfer[$data['upload'][$i - 2]['data']['tracking_number']])) {
          $errorTip[] = '与第' . $transfer[$data['upload'][$i - 2]['data']['tracking_number']] . '行转单号重复';
        }
        else {
          $transfer[$data['upload'][$i - 2]['data']['tracking_number']] = $i;
        }
      }

      if ('' === $data['upload'][$i - 2]['data']['reference_no']) {
        $errorTip[] = '内部单号不能为空';
      }
      else {
        if (isset($internal[$data['upload'][$i - 2]['data']['reference_no']])) {
          $errorTip[] = '与序号【' . $internal[$data['upload'][$i - 2]['data']['reference_no']] . '】内部单号重复';
        }
        else {
          $internal[$data['upload'][$i - 2]['data']['reference_no']] = ($i - 1);
        }
      }

      if ('' === $data['upload'][$i - 2]['data']['country']) {
        $errorTip[] = '目的地不能为空';
      }

      if (!preg_match('/^[1-9]\d*$/', $data['upload'][$i - 2]['data']['piece'])) {
        $errorTip[] = '件数只能为正整数';
      }

      if ('' === $data['upload'][$i - 2]['data']['weight']) {
        $errorTip[] = '重量不能为空';
      }
      elseif (!preg_match('/^[0-9]+(?:\.[0-9]+)?$/', $data['upload'][$i - 2]['data']['weight'])) {
        $errorTip[] = '重量只能为数字';
      }
      elseif (floatval($data['upload'][$i - 2]['data']['weight']) < 0.0000001) { // 重量必须大于0，这里的0.0000001只是精度限制
        $errorTip[] = '重量必须大于0';
      }
      else {
        $data['upload'][$i - 2]['data']['weight'] = number_format($data['upload'][$i - 2]['data']['weight'], 4);
      }
      if(empty($data['upload'][$i-2]['data']['receiving_date'])){
          $errorTip[] = '费用发生时间不能为空';

      }elseif(!preg_match('/^\d{4}[-\/]{1}\d{2}[-\/]{1}\d{2}\s{1,}\d{2}:{1}\d{2}:{1}\d{2}$/',$data['upload'][$i-2]['data']['receiving_date'])){
              $cell =$sheetObj->getCellByColumnAndRow('7',$i);  
             $value=$cell->getValue();  
            if($cell->getDataType()==PHPExcel_Cell_DataType::TYPE_NUMERIC){  
                       $cellstyleformat=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat();  
                       $formatcode=$cellstyleformat->getFormatCode();  
                        if (preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i', $formatcode)) {  
                              $value=gmdate("Y-m-d H:i:s", PHPExcel_Shared_Date::ExcelToPHP($value));  
                               $data['upload'][$i-2]['data']['receiving_date']=$value;
                        }else{  
                              $errorTip[] = '费用发生时间格式不正确';
                        }  
            }else{
                $errorTip[] = '费用发生时间格式不正确';
            }  
      }else{
          $data['upload'][$i-2]['data']['receiving_date']=  date('Y-m-d H;i:s',strtotime($data['upload'][$i-2]['data']['receiving_date']));
      }
      if (!empty($errorTip)) {
        $data['upload'][$i - 2]['valid']   = FALSE;
        $data['upload'][$i - 2]['message'] = join('；', $errorTip);
        $data['dross']                    += 1;
        continue ; // 继续下一组数据验证
      }

      // 验证目的地（国家）有效性
      if (!isset($country[$data['upload'][$i - 2]['data']['country']])) {
        $query = Service_Country::getByField($data['upload'][$i - 2]['data']['country'], 'country_name');
  
        if (empty($query)) { // 无效目的地
          $errorTip[] = '系统无法匹配目的地【' . $data['upload'][$i - 2]['data']['country'] . '】';
        }

        $country[$data['upload'][$i - 2]['data']['country']] = $query ? (int) $query['country_id'] : 0;
      }

      // 保存国家ID，后续有用
      $data['upload'][$i - 2]['country'] = $country[$data['upload'][$i - 2]['data']['country']];

      // 验证内部单号有效性
      $query = Service_LogisticsOrder::getByCondition(array(
        'ref_tracking_number'   => $data['upload'][$i - 2]['data']['reference_no'],
        'except_deleted_status' => TRUE,
      ));
      if (empty($query)) {
        $errorTip[] = '没有与内部单号匹配的运单';
      }
      elseif (count($query) > 1) {
        $errorTip[] = '内部单号存在多个匹配的运单';
      }
      elseif (2 !== (int) $query[0]['lo_status']&&$query[0]['sm_code']!='HKDHL') { // 运单不是已提交状态
         
             $errorTip[] = '内部单号匹配的运单不是【已提交】状态';
        
            
         
      }elseif(9 !== (int) $query[0]['lo_status']&&$query[0]['sm_code']=='HKDHL'){
           $errorTip[] = '内部单号匹配的运单不是【已录单】状态';
      }
      else {
        $data['upload'][$i - 2]['code']     = $query[0]['logistics_code'];
        $data['upload'][$i - 2]['customer'] = $query[0]['customer_code'];

        // 验证运输方式是否一致
        if ($data['upload'][$i - 2]['sm_code'] !== $query[0]['sm_code']) {
          $errorTip[] = '快递类型与运单运输方式不一致';
        }

        // 验证国家是否与目的地相同
        $query = Service_LogisticsOrderAddress::getByField($data['upload'][$i - 2]['code'], 'logistics_code');

        if ($country[$data['upload'][$i - 2]['data']['country']] !== (int) $query['loa_country']) {
          $errorTip[] = '目的地与运单收件人地址不符';
        }
      }

      // 内部单号跟转单号不一致时验证转单号的可用性
      if ($data['upload'][$i - 2]['data']['reference_no'] !== $data['upload'][$i - 2]['data']['tracking_number']) {
        $query = Service_LogisticsOrder::getByCondition(array(
          'ref_tracking_number'   => $data['upload'][$i - 2]['data']['tracking_number'],
          'except_deleted_status' => TRUE,
        ));

        if (!empty($query)) { // 转单号/跟踪号已经存在
          $errorTip[] = '转单号码不可用';
        }
      }

      if (!empty($errorTip)) {
        $data['upload'][$i - 2]['valid']   = FALSE;
        $data['upload'][$i - 2]['message'] = join('；', $errorTip);
        $data['dross']                    += 1;
        continue ; // 继续下一组数据验证
      }

      $data['upload'][$i - 2]['valid']   = TRUE;
      $data['upload'][$i - 2]['message'] = '验证通过';
      $data['weight']                   += $data['upload'][$i - 2]['data']['weight'];
    }
    if ($data['dross'] > 0) { // 存在验证不通过的记录，整批验证不通过
      $data['valid'] = FALSE;
    }
    $tmp   = md5('LOGISTICS-PR-' . 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);
    }

    unset($data); // 释放数组
    unlink($file); // 删除文件

    return $response;
  }

  /**
   * 区外仓运单收货、装袋
   * 
   * @param string $cache    缓存文件名
   * @return mixed
   */
  public static function prProcess($cache) {
    if (!self::isCache($cache)) {
      return '无效的缓存文件名';
    }

    $errorTip      = '';
    $data          = include self::getCacheDir() . trim($cache);
    $customerGroup = array(); // 按客户分组，以便集中收货
    $channelGroup  = array(); // 按渠道分组，以便集中装袋
    $bagNumber     = array(); // 包袋号
    $db            = Common_Common::getAdapter();

    foreach ($data['upload'] as $item) {
      $customerGroup[$item['customer']][] = $item;
      $channelGroup[$item['sm_code']][]   = $item;
    }

    unset($data); // 释放数组
    $db->beginTransaction(); // 开启事务

    try {
      self::receive($customerGroup); // 按客户收货
      // throw new Exception('区外仓收货完成');
      $bagNumber = self::bag($channelGroup); // 按渠道装袋
      // throw new Exception('区外仓装袋完成');
      $db->commit(); // 事务提交，收货、装袋完成
    }
    catch (Exception $e) {
      $db->rollBack(); // 发生异常回滚
      $errorTip = $e->getMessage();

      if ('' === trim($errorTip)) { // 防止空白异常信息的情况
        $errorTip = '未知错误异常';
      }
    }

    unset($customerGroup);
    unset($channelGroup);
    self::removeCache($cache);

    return ('' === $errorTip) ? $bagNumber : $errorTip;
  }

  /**
   * 根据用户逐个收货
   * 
   * @param array $customerGroup    依据客户分组的数据
   */
  private static function receive(&$customerGroup) {
    $user   = new Zend_Session_Namespace('userAuthorization');
    $userId = isset($user->userId) ? (int) $user->userId : 0;
    foreach ($customerGroup as $customerCode => $data) { // 按客户收货
      self::validateCustomer($customerCode); // 先验证客户
      $channelGroup = array(); // 按渠道分组

      foreach ($data as $item) { // 统计件数、重量
        //$channelGroup[$item['sm_code']][] = $item;

        if (isset($channelGroup[$item['sm_code']]['piece'])) {
          $channelGroup[$item['sm_code']]['piece']  += $item['data']['piece'];
          $channelGroup[$item['sm_code']]['weight'] += $item['data']['weight'];
        }
        else {
          $channelGroup[$item['sm_code']]['piece']  = $item['data']['piece'];
          $channelGroup[$item['sm_code']]['weight'] = $item['data']['weight'];
        }
      }
      // 创建收货总单 - START
      $rbCode         = '';
      $operationTime  = date('Y-m-d H:i:s');
      $receivingBatch = Service_ReceivingBatch::getByCondition(array(
        'customer_code' => $customerCode,
        'status'        => '0',
      ));

      if (empty($receivingBatch)) { // 没有草稿状态的收货总单则创建
        $rbCode = Common_GetNumbers::getCode('receingBatch', $customer_code, 'REB');

        if (Service_ReceivingBatch::add(array(
          'rb_code'            => $rbCode,
          'customer_code'      => $customerCode,
          'warehouse_id'       => 1,
          'add_time'           => $operationTime,
          'submit_time'        => $operationTime,
          'last_modified_time' => $operationTime,
          'oper_userid'        => $userId,
        ))) { // 创建收货总单，写日志
          Service_ReceivingBatchLog::add(array(
            'rb_code'     => $rbCode,
            'from_status' => 0,
            'to_status'   => 0,
            'action'      => '新增到货总单',
            'content'     => '新增到货总单',
            'operator'    => $userId,
            'add_time'    => $operationTime,
          ));
        }
        else {
          throw new Exception('创建收货总单时，数据库异常');
        }
      }
      else {
        $rbCode = $receivingBatch[0]['rb_code'];
      }
      // 创建收货总单 - END

      // 保存运单详情 - START
      foreach ($channelGroup as $channel => $item) {
        Service_ReceivingBatchDetail::add(array(
          'rb_code'         => $rbCode,
          'rbdetail_status' => 1,
          'sm_code'         => $channel,
          'BagQty'          => 1, // 暂时为1
          'PackageQty'      => $item['piece'],
          'TotalWeight'     => $item['weight'],
        ));
      }

      unset($channelGroup); // 释放
      // 保存运单详情 - END

      // 保存运单 - START
      foreach ($data as $item) {
        $logistics = Service_LogisticsOrder::getByField($item['code'], 'logistics_code');

        if (2 !== (int) $logistics['lo_status']&&$logistics['sm_code']!='HKDHL') {
          throw new Exception('运单【' . $item['code'] . '】状态不是【已提交】');
        }
         if (9 !== (int) $logistics['lo_status']&&$logistics['sm_code']=='HKDHL') {
          throw new Exception('运单【' . $item['code'] . '】状态不是【已录单】');
        }
        // 收货总单添加运单
        Service_ReceivingBatchOrder::add(array(
          'logistics_code' => $item['code'],
          'rb_code'        => $rbCode,
          'weight'         => $item['data']['weight'],
          'user_id'        => $userId,
          'sm_code'        => $item['sm_code'],
          'add_time'       => $item['data']['receiving_date'],
        ));
        
        // 更新运单信息
        Service_LogisticsOrder::update(array(
          'lo_status'           => 3,
          'lo_update_time'      => $operationTime,
          'ref_tracking_number' => $item['data']['tracking_number'],
        ), (int) $logistics['lo_id']);

        // 运单日志
        Service_LogisticsOrderLog::add(array(
          'logistics_code'    => $item['code'],
          'lol_comment'       => '收货扫描运单',
          'lol_create_time'   => $operationTime,
          'lol_operator'      => $userId,
          'lol_ip'            => Common_Common::getIP(),
          'order_status_from' => 2,
          'order_status_to'   => 3,
        ));

        // 运单解冻、扣费 - START
        $balanceProcess = new Service_CustomerBalanceProcess();
        $processResult  = $balanceProcess->logisticsUnFreezeFee($item['code'], $logistics['customer_id']);

        if (TRUE !== $processResult) { // 解冻失败
          throw new Exception('运单【' . $item['code'] . '】解冻异常：' . $processResult);
        }

        $shipOrderProcess = new Service_ShipOrderProcess();
        $processResult    = $shipOrderProcess->shipLogisticsFee($item['code'], $logistics['customer_id'], $item['data']['weight'], $item['country'],0,array('receiving_date'=>$item['data']['receiving_date']));

        if (TRUE !== $processResult) {
          throw new Exception('运单【' . $item['code'] . '】扣款异常：' . $processResult);
        }
        // 运单解冻扣费 - END
      }
      // 保存运单 - END

      // 收货总单完成 - START
      Service_ReceivingBatchDetail::update(array('rbdetail_status' => 2), $rbCode, 'rb_code');
      Service_ReceivingBatch::update(array(
        'status'             => 1,
        'last_modified_time' => $operationTime,
      ), $rbCode, 'rb_code');
      Service_ReceivingBatchLog::add(array(
        'rb_code'     => $rbCode,
        'from_status' => 0,
        'to_status'   => 1,
        'action'      => '完成到货总单',
        'content'     => '完成到货总单',
        'operator'    => $userId,
        'add_time'    => $operationTime,
      ));

      foreach ($data as $item) {
        // 更新运单信息
        Service_LogisticsOrder::update(array(
          'lo_status'      => 4,
          'lo_update_time' => $operationTime,
        ), $item['code'], 'logistics_code');

        // 运单日志
        Service_LogisticsOrderLog::add(array(
          'logistics_code'    => $item['code'],
          'lol_comment'       => '完成到货总单',
          'lol_create_time'   => $operationTime,
          'lol_operator'      => $userId,
          'lol_ip'            => Common_Common::getIP(),
          'order_status_from' => 3,
          'order_status_to'   => 4,
        ));
      }
      // 收货总单完成 - END
    }
  }

  /**
   * 按渠道装袋
   * 
   * @param array $channelGroup    依据渠道分组的数据
   */
  private static function bag(&$channelGroup) {
    $bagNumber = array();
    $user      = new Zend_Session_Namespace('userAuthorization');
    $userId    = isset($user->userId) ? (int) $user->userId : 0;

    foreach ($channelGroup as $channel => $data) { // 按渠道装袋
      $operationTime = date('Y-m-d H:i:s');
      $packNo        = $channel . date('ymdHis') . sprintf('%04s', array_pop(explode('.', trim(microtime(TRUE))))) . mt_rand(10, 99);
      $packWeight    = 0;

      // 创建袋子 - START
      if (Service_Pack::add(array(
        'pack_code'    => $packNo,
        'warehouse_id' => 1,
        'status'       => 0,
        'weight'       => 0,
        'add_time'     => $operationTime,
        'sm_code'      => $channel,
      ))) {
        // 添加日志
        Service_PackLog::add(array(
          'pack_code'   => $packNo,
          'from_status' => 0,
          'to_status'   => 0,
          'content'     => '扫描运单，创建袋子',
          'operator'    => $userId,
          'add_time'    => $operationTime,
        ));

        $bagNumber[] = $packNo;
      }
      else {
        throw new Exception('运单装袋创建袋子时发生异常');
      }
      // 创建袋子 - END

      // 运单装袋 - START
      foreach ($data as $item) {
        $packWeight += $item['data']['weight'];

        // 往袋子添加订单
        Service_PackOrder::add(array(
          'pack_code'   => $packNo,
          'orders_code' => $item['code'],
          'operator'    => $userId,
          'add_time'    => $operationTime,
        ));

        // 袋子日志
        Service_PackLog::add(array(
          'pack_code'   => $packNo,
          'from_status' => 0,
          'to_status'   => 0,
          'content'     => '订单装袋，扫描运单，服务商号：' . $item['data']['tracking_number'],
          'operator'    => $userId,
          'add_time'    => $operationTime,
        ));

        // 更新运单信息
        Service_LogisticsOrder::update(array(
          'lo_status'      => 6,
          'lo_update_time' => $operationTime,
        ), $item['code'], 'logistics_code');

        // 运单日志
        Service_LogisticsOrderLog::add(array(
          'logistics_code'    => $item['code'],
          'lol_comment'       => '运单扫描装袋',
          'lol_create_time'   => $operationTime,
          'lol_operator'      => $userId,
          'lol_ip'            => Common_Common::getIP(),
          'order_status_from' => 4,
          'order_status_to'   => 5,
        ));
        Service_LogisticsOrderLog::add(array(
          'logistics_code'    => $item['code'],
          'lol_comment'       => '运单装袋完成',
          'lol_create_time'   => $operationTime,
          'lol_operator'      => $userId,
          'lol_ip'            => Common_Common::getIP(),
          'order_status_from' => 5,
          'order_status_to'   => 6,
        ));
      }
      // 运单装袋 - END

      // 完成装袋 - START
      Service_Pack::update(array(
        'status'      => 1,
        'weight'      => $packWeight,
        'update_time' => $operationTime,
      ), $packNo, 'pack_code');
      Service_PackLog::add(array(
        'pack_code'   => $packNo,
        'from_status' => 0,
        'to_status'   => 1,
        'content'     => '运单扫描完毕，完成装袋',
        'operator'    => $userId,
        'add_time'    => $operationTime,
      ));
      // 完成装袋 - END
    }

    if (empty($bagNumber)) {
      throw new Exception('运单装袋时发生异常');
    }

    return $bagNumber;
  }

  /**
   * 验证客户有效性
   */
  private static function validateCustomer($customerCode) {
    $customerCode = trim($customerCode);

    if ('' === $customerCode) {
      throw new Exception('客户代码不能为空');
    }

    $customer = Service_Customer::getByField($customerCode, 'customer_code');

    if (empty($customer)) {
      throw new Exception('客户代码【' . $customerCode . '】不存在');
    }
    elseif (2 !== (int) $customer['customer_status']) {
      throw new Exception('客户代码【' . $customerCode . '】不可用');
    }
  }

  /**
   * 根据索引映射为可读性的名称
   * 
   * @param integer|string $index    索引值
   * @return mixed                   若存在返回对应的映射，否则返回原来的内容
   */
  private static function getMapIndex($index) {
    switch ($index) {
      case 0:
      case 'A':
      case 'a':
        return 'date';

      case 1:
      case 'B':
      case 'b':
        return 'type';

      case 2:
      case 'C':
      case 'c':
        return 'tracking_number';

      case 3:
      case 'D':
      case 'd':
        return 'reference_no';

      case 4:
      case 'E':
      case 'e':
        return 'country';

      case 5:
      case 'F':
      case 'f':
        return 'piece';

      case 6:
      case 'G':
      case 'g':
        return 'weight';
      case 7:
      case 'H':
      case 'h':
        return 'receiving_date';
      case 8:
      case 'I':
      case 'i':
        return 'discount';

      case 9:
      case 'J':
      case 'j':
        return 'fee';

      case 10:
      case 'K':
      case 'k':
        return 'amount';

      case 11:
      case 'L':
      case 'l':
        return 'remark';

      case 12:
      case 'M':
      case 'm':
        return 'area';

      default:
        return $index;
    }
  }
}
