<?php
// 统一数据库配置
$dbHost = "10.150.117.190";
$dbUser = "root";
$dbPass = "hp93000";
$dbName = "alert_mail_stat";

// 统一数据库连接函数
function getDbConn() {
    global $dbHost, $dbUser, $dbPass, $dbName;
    $conn = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
    mysqli_set_charset($conn, "utf8mb4");
    return $conn;
}

$act = $_GET['act'] ?? '';

// CSV导出接口（独立流式下载，不输出JSON头）
if ($act === "export_csv") {
    $conn = getDbConn();
    if (!$conn) {
        header("Content-Type:text/html;charset=utf-8");
        echo "数据库连接失败：" . mysqli_connect_error();
        exit;
    }
    $today = date("Y-m-d");
    $sql = "SELECT alert_type,alert_name,instance,severity,starts_at,receive_time
            FROM alert_log WHERE DATE(receive_time) = '$today' ORDER BY receive_time DESC";
    $res = mysqli_query($conn, $sql);

    ob_clean();
    header("Content-Type: text/csv; charset=utf-8");
    header("Content-Disposition: attachment; filename=告警报表_" . $today . ".csv");
    echo "\xEF\xBB\xBF";
    $header = ["告警状态", "告警名称", "实例", "级别", "故障开始时间", "接收时间"];
    echo implode(",", $header) . "\r\n";

    while ($row = mysqli_fetch_assoc($res)) {
        $status = $row['alert_type'] == 1 ? "触发" : "恢复";
        $line = [
            $status,
            $row['alert_name'],
            $row['instance'],
            $row['severity'],
            $row['starts_at'],
            $row['receive_time']
        ];
        foreach ($line as &$v) {
            $v = '"' . str_replace('"', '""', $v) . '"';
        }
        echo implode(",", $line) . "\r\n";
    }
    mysqli_close($conn);
    exit;
}

// 所有JSON接口统一返回头
header("Content-Type:application/json;charset=utf-8");
$conn = getDbConn();
if (!$conn) {
    echo json_encode(["code" => 500, "msg" => "数据库连接失败：" . mysqli_connect_error()], JSON_UNESCAPED_UNICODE);
    exit;
}
$today = date("Y-m-d");

// 1.今日统计卡片
if ($act === "day_total") {
    $sql = "SELECT
        SUM(IF(alert_type=1,1,0)) as fire_count,
        SUM(IF(alert_type=2,1,0)) as resolve_count,
        COUNT(DISTINCT instance) as instance_num
        FROM alert_log WHERE DATE(receive_time) = '$today'";
    $data = mysqli_fetch_assoc(mysqli_query($conn, $sql));
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

// 2.今日告警TOP10图表
if ($act === "top_alert") {
    $sql = "SELECT alert_name,COUNT(*) cnt FROM alert_log WHERE DATE(receive_time)='$today' GROUP BY alert_name ORDER BY cnt DESC LIMIT 10";
    $list = [];
    $q = mysqli_query($conn, $sql);
    while ($r = mysqli_fetch_assoc($q)) $list[] = $r;
    echo json_encode($list, JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

// 3.今日全量告警明细
if ($act === "log_list") {
    $sql = "SELECT alert_type,alert_name,instance,severity,starts_at,ends_at,receive_time
    FROM alert_log WHERE DATE(receive_time)='$today' ORDER BY receive_time DESC";
    $list = [];
    $q = mysqli_query($conn, $sql);
    while ($r = mysqli_fetch_assoc($q)) $list[] = $r;
    echo json_encode($list, JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

// 4.全局跨天未恢复告警（修复版，取每组最新一条判断状态）
if ($act === "active_firing") {
    $maxSql = "SELECT alert_name,instance,MAX(receive_time) max_rt FROM alert_log GROUP BY alert_name,instance";
    $maxRes = mysqli_query($conn, $maxSql);
    $activeList = [];
    while ($row = mysqli_fetch_assoc($maxRes)) {
        $an = mysqli_real_escape_string($conn, $row['alert_name']);
        $ins = mysqli_real_escape_string($conn, $row['instance']);
        $rt = mysqli_real_escape_string($conn, $row['max_rt']);
        $sql = "SELECT alert_name,instance,severity,starts_at,receive_time,alert_type
                FROM alert_log WHERE alert_name='$an' AND instance='$ins' AND receive_time='$rt' LIMIT 1";
        $one = mysqli_fetch_assoc(mysqli_query($conn, $sql));
        if ($one && (int)$one['alert_type'] === 1) {
            $activeList[] = $one;
        }
    }
    echo json_encode($activeList, JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

// 非法act
echo json_encode(["code" => 400, "msg" => "无效请求参数act"], JSON_UNESCAPED_UNICODE);
mysqli_close($conn);
?>
