<?php
require_once ('config.php');
$flagFile = APPLICATION_PATH . '/../data/log/autoRumal.lock';
if (@file_exists($flagFile)) {
    echo 'Another process is running.'."\r\n";
    echo $flagFile."\r\n";
    exit();
}
$link = fopen($flagFile, 'wb');
fclose($link);
function mkdirs($dir) {
    $dirArray = explode('/', $dir);
    $path = array_shift($dirArray);
    while (file_exists($path)) {
        $path.='/' . array_shift($dirArray);
    }
    foreach ($dirArray as $mk) {
        $path.='/' . $mk;
        mkdir($path, 0777, true);
    }
}
define('RUNTIME', '[' . date('Y-m-d H:i:s') . '] ');
echo RUNTIME . "Starting.\r\n\r\n";
    $savePdfPath = array(
    'Rumall-RU-EP' => APPLICATION_PATH . '/../data/pdf/RUMAll-RU-EP/',
    'Rumall-RU-G' => APPLICATION_PATH . '/../data/pdf/RUMAll-RU-G/',
);
    foreach ($savePdfPath as $path) {
    if (!file_exists($path)) {
        mkdirs($path);
    }
}
$condition = array(
    'sm_code_Arr'                 => array('Rumall-RU-EP','Rumall-RU-G'),
    'order_status'=>'4',
    'ref_tracking_number'=>'',
    //'order_mode_type' => '0', // 备货模式
);
$total = Service_Orders::getByCondition($condition,"count(*)");
$pageSize = 20;
$totalPage = ceil($total/$pageSize);
$rumalService=new Service_RumalApiProcess();
for($page=1;$page<=$totalPage;$page++){
    $orderList = Service_Orders::getByCondition($condition,'*',$pageSize,$page,'order_id desc');
    foreach($orderList as $k=>$v){
        // 数据过滤
        if (!in_array(trim($v['sm_code']),array('Rumall-RU-EP','Rumall-RU-G'))
            || 4 !== (int) $v['order_status']
            || '' !== trim($v['ref_tracking_number'])) {
          continue ;
        }
        $orderXml = Service_SfexpressService::getOrderContent($v['order_code']);
        $rumalService->makeOrderXml($v);
       $result= $rumalService->confirmSenderInfo($rumalService->sendXml);

       $result=$rumalService->xmlToArray($result);
            if(is_array($result)&&$result['Head']=="OK"){
                $updateOrder = array(
                    'agent_mailno'=>$result['Mailno'],
                    'ref_tracking_number'       =>empty($result['AgentMailno'])||$result['AgentMailno']=='null'?$result['Mailno']:$result['AgentMailno'],
                );
                $orderLog = array(
                    'order_id'=>$v['order_id'],
                    'order_code'=>$v['order_code'],
                    'ol_type'=>'1',
                    'order_status_from'=>$v['order_status'],
                    'order_status_to'=>$v['order_status'],
                    'ol_add_time'=>date("Y-m-d H:i:s"),
                    'user_id'=>0,
                    'ol_comments'=>'Rumal订单发件信息和申报价值的确认'
                );
                Service_OrderLog::add($orderLog);
                Service_Orders::update($updateOrder,$v['order_id'],"order_id");

               $p=$rumalService->genaratLabel($v['reference_no']);
               if(strpos($p,'%PDF-1.4')!==FALSE){
                    file_put_contents($savePdfPath[$v['sm_code']].'/'.$v['order_code'].'.pdf', $p);
                    Service_OrdersLabel::add(array('order_code'=>$v['order_code'],'ol_content'=>  base64_encode($p),'ol_time'=>date('Y-m-d H;i:s')));
               }else{
                   echo "订单获取面单失败";
               }
                echo "订单".$v['order_code']."获取单号".$result['Mailno']."成功\r\n";
            }else{
                $errorText="订单".$v['order_code']."提交出错:".var_export($result,true)."\r\n";
                
                $errorLog=array(
                 'order_code'=>$v['order_code'],
                 'sm_code'=>$v['sm_code'],
                 'content'=>$errorText,
                );
             Service_TrackingErrorLog::add($errorLog);
             echo $errorText;
            }
    }
}
echo "[" . date('Y-m-d H:i:s') . "] End run\r\n";
@unlink($flagFile);