<?php
/**
 * 出货数据统计 计划任务 写入数据库
 */
set_time_limit(7200);
error_reporting(E_ALL);
require_once('config.php');
$flagFile = APPLICATION_PATH . '/../data/log/shippingCount.lock';
if (@file_exists($flagFile)) {
    /*if (time() - filemtime($flagFile) > 3600) {
        unlink($flagFile);
    } else {
        echo 'Another process is running.' . "\r\n";
        echo $flagFile . "\r\n";
        exit();
    }*/
    echo 'Another process is running.' . "\r\n";
    echo $flagFile . "\r\n";
    exit();
}
$link = fopen($flagFile, 'wb');
fclose($link);

global $shippingCountDate;
global $runtime;
$runtime = date('Y-m-d H:i:s');
// 初始时间
$startDate = '2000-01';

echo '[' . $runtime . '] ' . "Starting.\r\n\r\n";
// 获取shipping_count表的最大日期
$dateMax = Service_ShippingCount::getByField(1, 1, 'max(date) as date');
if (empty($dateMax['date'])) {
    // 空则取订单完成装袋日期最小的值
    $orderDateMin = Service_OrderOperationTime::getByField(1, 1, 'min(finishbag_time) as finishbag_time');
    if ($orderDateMin['finishbag_time'] == '0000-00-00 00:00:00') {
        $shippingCountDate = '0000-00';
    } else {
        $shippingCountDate = date('Y-m', strtotime($orderDateMin['finishbag_time']));
    }
} else {
    // 存在则日期月份进一
    if ($dateMax['date'] == '0000-00') {
        $shippingCountDate = $startDate;
    } else {
        $shippingCountDate = date('Y-m', strtotime($dateMax['date'] . " + 1 month"));
    }
}
$dateNow = date('Y-m');
try {
    while ($shippingCountDate < $dateNow) {
        $result = Service_OrderProduct::getShippingCount($shippingCountDate);
        if (isset($result) && !empty($result)) {
            $result = array_map('arrayFormat', $result);
            array_map('Service_ShippingCount::insert', $result);
            echo 'date: ' . $shippingCountDate . " insert success, total: " . count($result) ." rows;\r\n";
        } else {
            echo $shippingCountDate . " have no data;\r\n";
        }
        if ($shippingCountDate == '0000-00') {
            $shippingCountDate = $startDate;
        } else {
            $shippingCountDate = date('Y-m', strtotime("$shippingCountDate + 1 month"));
        }
    }
} catch (Exception $e) {
    echo $e->getMessage() . "\r\n";
}
echo '[' . date('Y-m-d H:i:s') . '] ' . "End.\r\n\r\n";
unlink($flagFile);

function arrayFormat($data) {
    global $shippingCountDate;
    global $runtime;
    $result = array();
    $result['customer_code'] = $data['customer_code'];
    $result['date'] = $shippingCountDate;
    $result['product_id'] = $data['product_id'];
    $result['quantity'] = $data['op_quantity_total'];
    $result['product_value'] = $data['op_declared_value_total'];
    $result['add_time'] = $runtime;
    return $result;
}