<?php
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST,OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    echo json_encode(['code' => 0, 'msg' => 'ok']);
    exit;
}
session_start();
$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    echo json_encode(['code' => 401, 'msg' => '登录失效']);
    exit;
}
$loginUid = $_SESSION['user_id'];

// 工单业务库 monitor
$dbWorkHost = 'localhost';
$dbWorkUser = 'root';
$dbWorkPwd = 'hp93000';
$dbWorkName = 'monitor';
$connWork = mysqli_connect($dbWorkHost, $dbWorkUser, $dbWorkPwd, $dbWorkName);
if (!$connWork) {
    echo json_encode(['code' => 500, 'msg' => '工单数据库连接失败：' . mysqli_connect_error()]);
    exit;
}
mysqli_set_charset($connWork, 'utf8mb4');

// 配置库 alert_mail_stat
$dbConfHost = "10.150.117.190";
$dbConfUser = "root";
$dbConfPwd = "hp93000";
$dbConfName = "alert_mail_stat";
$connConf = mysqli_connect($dbConfHost, $dbConfUser, $dbConfPwd, $dbConfName);
mysqli_set_charset($connConf, "utf8mb4");

// 获取当前用户角色权限
$isAdmin = 0;
$permList = "";
$roleSql = "SELECT r.is_admin, r.perm_list FROM sys_user u LEFT JOIN sys_role r ON u.role_id=r.id WHERE u.uid = ?";
$stmtRole = mysqli_prepare($connWork, $roleSql);
mysqli_stmt_bind_param($stmtRole, 's', $loginUid);
mysqli_stmt_execute($stmtRole);
$roleRow = mysqli_fetch_assoc(mysqli_stmt_get_result($stmtRole));
if ($roleRow) {
    $isAdmin = intval($roleRow['is_admin']);
    $permList = $roleRow['perm_list'];
}

$action = $_REQUEST['action'] ?? '';
$post = json_decode(file_get_contents("php://input"), true) ?: [];

// 1、获取当前活跃告警（解决前端下拉空白）
if ($action === "get_firing_alert") {
    $alertSql = "SELECT alert_id,alert_name,instance FROM alert_firing ORDER BY receive_time DESC LIMIT 100";
    $res = mysqli_query($connConf, $alertSql);
    $list = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $list[] = $row;
    }
    echo json_encode(['code' => 0, 'list' => $list]);
    exit;
}

// 2、新建工单（新增通知用户、通知渠道、关联告警）
if ($action === "create") {
    $title = trim($post['title'] ?? '');
    $content = trim($post['content'] ?? '');
    $assign = trim($post['assign_uid'] ?? '');
    $relateAlertId = trim($post['relate_alert_id'] ?? '');
    $notifyUser = trim($post['notify_user'] ?? '');
    $notifyChannel = trim($post['notify_channel'] ?? '');
    $status = 1;
    if (!$title || !$content) {
        echo json_encode(['code' => 400, 'msg' => '标题和内容不能为空']);
        exit;
    }
    $sql = "INSERT INTO work_order(title,content,create_uid,assign_uid,relate_alert_id,notify_user,notify_channel,status,create_time,update_time) VALUES (?,?,?,?,?,?,?,?,NOW(),NOW())";
    $stmt = mysqli_prepare($connWork, $sql);
    mysqli_stmt_bind_param($stmt, 'sssssssi', $title, $content, $loginUid, $assign, $relateAlertId, $notifyUser, $notifyChannel, $status);
    $ok = mysqli_stmt_execute($stmt);
    if (!$ok) {
        echo json_encode(['code' => 500, 'msg' => '创建失败：' . mysqli_error($connWork)]);
        exit;
    }
    $orderId = mysqli_insert_id($connWork);
    // 发送通知
    sendWorkOrderNotify($connConf, $connWork, $orderId, $notifyUser, $notifyChannel);
    echo json_encode(['code' => 0, 'msg' => '工单提交成功，通知已下发']);
    exit;
}

// 3、编辑工单（更新通知、不修改关联告警）
if ($action === "edit") {
    $id = intval($post['id'] ?? 0);
    $title = trim($post['title'] ?? '');
    $content = trim($post['content'] ?? '');
    $assign = trim($post['assign_uid'] ?? '');
    $notifyUser = trim($post['notify_user'] ?? '');
    $notifyChannel = trim($post['notify_channel'] ?? '');
    if ($id <= 0 || empty($title) || empty($content)) {
        echo json_encode(['code' => 400, 'msg' => '参数不能为空']);
        exit;
    }
    // 权限校验
    if ($isAdmin !== 1) {
        $chkSql = "SELECT id FROM work_order WHERE id=? AND (create_uid=? OR assign_uid=?)";
        $stmtChk = mysqli_prepare($connWork, $chkSql);
        mysqli_stmt_bind_param($stmtChk, 'iss', $id, $loginUid, $loginUid);
        mysqli_stmt_execute($stmtChk);
        $chkRes = mysqli_stmt_get_result($stmtChk);
        if (mysqli_num_rows($chkRes) === 0) {
            echo json_encode(['code' => 403, 'msg' => '无权限编辑该工单']);
            exit;
        }
    }
    $sql = "UPDATE work_order SET title=?,content=?,assign_uid=?,notify_user=?,notify_channel=?,update_time=NOW() WHERE id=?";
    $stmt = mysqli_prepare($connWork, $sql);
    mysqli_stmt_bind_param($stmt, 'sssssi', $title, $content, $assign, $notifyUser, $notifyChannel, $id);
    mysqli_stmt_execute($stmt);
    sendWorkOrderNotify($connConf, $connWork, $id, $notifyUser, $notifyChannel);
    echo json_encode(['code' => 0, 'msg' => '工单保存成功，通知已更新下发']);
    exit;
}

// 4、修改工单状态
if ($action === "update_status") {
    $id = intval($post['id'] ?? 0);
    $status = intval($post['status'] ?? 1);
    if ($id <= 0) {
        echo json_encode(['code' => 400, 'msg' => '工单ID错误']);
        exit;
    }
    if ($isAdmin !== 1) {
        $chkSql = "SELECT id FROM work_order WHERE id=? AND (create_uid=? OR assign_uid=?)";
        $stmtChk = mysqli_prepare($connWork, $chkSql);
        mysqli_stmt_bind_param($stmtChk, 'iss', $id, $loginUid, $loginUid);
        mysqli_stmt_execute($stmtChk);
        $chkRes = mysqli_stmt_get_result($stmtChk);
        if (mysqli_num_rows($chkRes) === 0) {
            echo json_encode(['code' => 403, 'msg' => '无权限操作该工单']);
            exit;
        }
    }
    $sql = "UPDATE work_order SET status=?,update_time=NOW() WHERE id=?";
    $stmt = mysqli_prepare($connWork, $sql);
    mysqli_stmt_bind_param($stmt, 'ii', $status, $id);
    mysqli_stmt_execute($stmt);
    echo json_encode(['code' => 0, 'msg' => '状态更新成功']);
    exit;
}

// 5、管理员分发工单
if ($action === "assign_order") {
    if ($isAdmin !== 1) {
        echo json_encode(['code' => 403, 'msg' => '仅管理员可分发工单']);
        exit;
    }
    $id = intval($post['id'] ?? 0);
    $assignUid = trim($post['assign_uid'] ?? '');
    $sql = "UPDATE work_order SET assign_uid=?,update_time=NOW() WHERE id=?";
    $stmt = mysqli_prepare($connWork, $sql);
    mysqli_stmt_bind_param($stmt, 'si', $assignUid, $id);
    mysqli_stmt_execute($stmt);
    echo json_encode(['code' => 0, 'msg' => '工单分发成功']);
    exit;
}

// 通知发送统一函数
function sendWorkOrderNotify($connConf, $connWork, $orderId, $notifyUserStr, $channelStr)
{
    if (empty($notifyUserStr) || empty($channelStr)) return;
    $userArr = explode(",", $notifyUserStr);
    $channelArr = explode(",", $channelStr);

    // 获取SMTP配置
    $smtpRow = mysqli_fetch_assoc(mysqli_query($connConf, "SELECT * FROM sys_smtp_config WHERE id=1"));
    $smtpConfig = $smtpRow ?? [];

    // 获取工单详情
    $orderRow = mysqli_fetch_assoc(mysqli_query($connWork, "SELECT * FROM work_order WHERE id=$orderId"));
    $title = $orderRow['title'];
    $content = $orderRow['content'];

    // 遍历渠道发送
    foreach ($channelArr as $ch) {
        switch ($ch) {
            case "mail":
                sendMailNotify($smtpConfig, $userArr, $title, $content);
                break;
            case "dingtalk":
                // 此处填入钉钉机器人发送逻辑，按需补充
                break;
            case "wecom":
                // 此处填入企业微信机器人发送逻辑，按需补充
                break;
        }
    }
}

// 邮件发送函数
function sendMailNotify($smtp, $uidList, $title, $content)
{
    if (empty($smtp['smtp_host']) || empty($smtp['smtp_user']) || empty($smtp['smtp_pass'])) return;
    // 查询用户邮箱
    $emailList = [];
    foreach ($uidList as $uid) {
        $uid = trim($uid);
        if (empty($uid)) continue;
        $res = mysqli_query($GLOBALS['connWork'], "SELECT email FROM sys_user WHERE uid='$uid'");
        $u = mysqli_fetch_assoc($res);
        if (!empty($u['email'])) $emailList[] = $u['email'];
    }
    if (empty($emailList)) return;
    $to = implode(",", $emailList);
    $subject = "【工单通知】" . $title;
    $body = "<h3>工单内容</h3><pre>".$content."</pre>";
    // PHPMailer 发送逻辑，环境需安装phpmailer
    /*
    require_once 'PHPMailer.php';
    require_once 'SMTP.php';
    $mail = new PHPMailer\PHPMailer\PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = $smtp['smtp_host'];
        $mail->SMTPAuth = true;
        $mail->Username = $smtp['smtp_user'];
        $mail->Password = $smtp['smtp_pass'];
        $mail->SMTPSecure = $smtp['smtp_ssl'] ? PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS : '';
        $mail->Port = $smtp['smtp_port'];
        $mail->setFrom($smtp['send_from'], $smtp['send_from']);
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->send();
    } catch (Exception $e) {}
    */
}

// 无匹配动作
echo json_encode(['code' => 400, 'msg' => '无效请求动作']);
mysqli_close($connWork);
mysqli_close($connConf);
exit;
?>
