<?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. 全局跨天未恢复告警（解决6.30残留故障不显示）
if ($act === "active_firing") {
    // 查询全部触发告警
    $fireSql = "SELECT DISTINCT alert_name,instance,severity,starts_at,receive_time FROM alert_log WHERE alert_type=1";
    $fireRes = mysqli_query($conn, $fireSql);
    $fireMap = [];
    while ($row = mysqli_fetch_assoc($fireRes)) {
        $key = $row['alert_name'] . "|" . $row['instance'];
        $fireMap[$key] = $row;
    }
    if (empty($fireMap)) {
        echo json_encode([], JSON_UNESCAPED_UNICODE);
        mysqli_close($conn);
        exit;
    }
    // 查询全部恢复告警唯一标识
    $resolveSql = "SELECT DISTINCT CONCAT(alert_name,'|',instance) as k FROM alert_log WHERE alert_type=2";
    $resolveRes = mysqli_query($conn, $resolveSql);
    $resolveKeys = [];
    while ($r = mysqli_fetch_assoc($resolveRes)) {
        $resolveKeys[] = $r['k'];
    }
    // 过滤：存在触发、无对应恢复 = 当前活跃故障
    $activeList = [];
    foreach ($fireMap as $key => $row) {
        if (!in_array($key, $resolveKeys)) {
            $row['alert_type'] = 1;
            $activeList[] = $row;
        }
    }
    echo json_encode($activeList, JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

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