<?php
session_start();
// 未登录直接拒绝所有接口访问
if(empty($_SESSION['user_id'])){
    header("Content-Type:application/json;charset=utf-8");
    echo json_encode(["code"=>401,"msg"=>"未登录，请前往登录页面"]);
    exit;
}
// 统一数据库配置
$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. 全局跨天未恢复告警【修复版：只看每条告警最新状态，兼容低版本MariaDB】
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 ($maxRow = mysqli_fetch_assoc($maxRes)) {
        // 转义防止SQL注入
        $an = $conn->real_escape_string($maxRow['alert_name']);
        $ins = $conn->real_escape_string($maxRow['instance']);
        $mrt = $conn->real_escape_string($maxRow['max_rt']);
        // 根据告警名、实例、最新时间取出最后一条记录
        $rowSql = "SELECT alert_name,instance,severity,starts_at,receive_time,alert_type
                   FROM alert_log
                   WHERE alert_name='$an' AND instance='$ins' AND receive_time='$mrt'";
        $rowRes = mysqli_query($conn, $rowSql);
        $data = mysqli_fetch_assoc($rowRes);
        // 仅最后一条状态为触发，才判定为当前活跃未恢复告警
        if ($data && (int)$data['alert_type'] === 1) {
            $activeList[] = $data;
        }
    }
    echo json_encode($activeList, JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

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