<?php
/**
 * ASN集货SZY-EUB运输方式订单向EUB创建订单并取回LABEL
 */
require_once 'config.php';

$flag = APPLICATION_PATH . '/../data/log/autoAsnEub.lock';

if (@file_exists($flag)) {
  echo "Another process is running.\r\n";
  echo "{$flag}\r\n";
  exit();
}

$handler = fopen($flag, 'wb');
fclose($handler);

echo '[', date('Y-m-d H:i:s'), '] Starting.', "\r\n";

// 从订单反推ASN，更具目的性，提高性能
$condition = array(
  'sm_code_Arr'                 => array('SZY-EUB','SZH-EUB','WG-EUB'), // 运输方式
  'order_status'            => 4, // 订单状态：已提交
  'order_mode_type'         => 1, // 集货模式
  'EUB_ref_tracking_number' => '', // 服务商单号
);
$total   = Service_Orders::getByCondition($condition, 'count(*)');
$size    = 20;
$maxPage = ceil($total / $size);

for ($i = 0; $i < $maxPage; ++$i) {
  $orderList = Service_Orders::getByCondition($condition, '*', $size, $i + 1, 'order_id DESC');

  foreach ($orderList as $order) {
    // 数据过滤
    if (!in_array(trim($order['sm_code']),array('SZY-EUB','SZH-EUB','WG-EUB'))
        || 1 !== (int) $order['order_mode_type']
        || 4 !== (int) $order['order_status']
        || '' !== trim($order['ref_tracking_number'])) {
      continue ;
    }

    $receivingDetail = Service_ReceivingOrderDetail::getByCondition(array(
      'order_code' => $order['order_code'],
    ));

    // 没有提取到数据或不是在途、收货中状态，继续下一轮
    if (empty($receivingDetail) || !in_array((int) $receivingDetail[0]['rd_status'], array(0, 1), TRUE)) {
      continue ;
    }

    $receiving = Service_Receiving::getByField((int) $receivingDetail[0]['receiving_id'], 'receiving_id');

    // 提取不到数据或不是集货ASN或状态不在待审核、已审核、在途、收货中状态之中，继续下一轮
    if (empty($receiving) || 1 !== (int) $receiving['receive_model_type'] || !in_array((int) $receiving['receiving_status'], array(3, 4, 5, 6), TRUE)) {
      continue ;
    }

    $orderXml = Service_EpacketWebService::getOrderContent($order['order_code']);
    $eub      = new Service_EpacketWebService();
    $response = $eub->validate($orderXml);

    if ('success' === strtolower(trim($response['status']))) {
      // 创建SZY-EUB订单
      $response = $eub->createEpacketOrder($orderXml);

      if (isset($response['mailnum']) && '' !== $response['mailnum']) {
        $orderLog = array(
          'order_id'          => $order['order_id'],
          'order_code'        => $order['order_code'],
          'ol_type'           => 1,
          'order_status_from' => $order['order_status'],
          'order_status_to'   => $order['order_status'],
          'ol_add_time'       => date("Y-m-d H:i:s"),
          'user_id'           => 0,
          'ol_comments'       => 'EUB自动取单号以及标签->autoAsnEub.php',
        );
        Service_OrderLog::add($orderLog);
        Service_Orders::update(array(
          'ref_tracking_number' => $response['mailnum'],
        ), $order['order_id'], 'order_id');

        /*$labelResponse = $eub->getOneLableByMailnum($response['mailnum']);
        $zipFileStream = @file_get_contents($labelResponse['url'], FALSE, NULL);
        $zipFileName   = APPLICATION_PATH . '/../data/pdf/EUB/' . $order['order_code'] . '.zip';
        $zip           = new ZipArchive();
        @file_put_contents($zipFileName, $zipFileStream);

        if (TRUE === $zip->open($zipFileName)) {
          $zip->extractTo(APPLICATION_PATH . '/../data/pdf/EUB/');
          $pdfFileName = $zip->getNameIndex(0);
          @rename(APPLICATION_PATH . '/../data/pdf/EUB/' . $pdfFileName, APPLICATION_PATH . '/../data/pdf/EUB/' . $order['order_code'] . '.pdf');
          $zip->close();
        }

        @unlink($zipFileName);*/
        $epaService->getPdfByOrderCode($v['order_code']);
        echo '订单', $order['order_code'], '获取单号', $response['mailnum'], '成功', "\r\n";
      }
      else {
        echo '订单', $order['order_code'], '提交出错:', $response['description'], "\r\n";
      }
    }
    else {
      echo '订单', $order['order_code'], '提交出错:', $response['description'], "\r\n";
    }
  }
}

echo '[', date('Y-m-d H:i:s'), '] End run', "\r\n";
@unlink($flag);
