<?php
$act = $_GET['act'] ?? '';
if($act == "export_csv"){
    // 先不输出JSON头，单独处理下载
    $host = "10.150.117.190";
    $user = "root";
    $pass = "hp93000";
    $dbname = "alert_mail_stat";
    $conn = mysqli_connect($host,$user,$pass,$dbname);
    if(!$conn){
        header("Content-Type:text/html;charset=utf-8");
        echo "数据库连接失败：".mysqli_connect_error();
        exit;
    }
    mysqli_set_charset($conn,"utf8mb4");
    $today = date("Y-m-d");
    // 查询今日告警，去掉ends_at恢复时间字段
    $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");
    // UTF8 BOM，Windows Excel不乱码
    echo "\xEF\xBB\xBF";
    // CSV表头
    $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']
        ];
        // 字段逗号转义，防止内容逗号破坏CSV格式
        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");
$host = "10.150.117.190";
$user = "root";
$pass = "hp93000";
$dbname = "alert_mail_stat";

$conn = mysqli_connect($host,$user,$pass,$dbname);
if(!$conn){
    echo json_encode(["code"=>500,"msg"=>"数据库连接失败：".mysqli_connect_error()]);
    exit;
}
mysqli_set_charset($conn,"utf8mb4");
$today = date("Y-m-d");

// 当日总统计
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'";
    $res = mysqli_fetch_assoc(mysqli_query($conn,$sql));
    echo json_encode($res,JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

// 告警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";
    $data = [];
    $q = mysqli_query($conn,$sql);
    while($r = mysqli_fetch_assoc($q)) $data[] = $r;
    echo json_encode($data,JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

// 明细列表
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";
    $data = [];
    $q = mysqli_query($conn,$sql);
    while($r = mysqli_fetch_assoc($q)) $data[] = $r;
    echo json_encode($data,JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

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