<?php
session_start();
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");

// 兼容低PHP版本 str_contains
if (!function_exists('str_contains')) {
    function str_contains($haystack, $needle) {
        return $needle === '' || strpos($haystack, $needle) !== false;
    }
}

$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    session_destroy();
    header("Location: login.php");
    exit;
}
$_SESSION['login_time'] = time();
$userName = htmlspecialchars($_SESSION['username']);
$userRoleId = $_SESSION['role_id'];

// 全局配置库连接
$dbConfigHost = "10.150.117.190";
$dbConfigUser = "root";
$dbConfigPwd = "hp93000";
$dbConfigName = "alert_mail_stat";
$connConfig = mysqli_connect($dbConfigHost, $dbConfigUser, $dbConfigPwd, $dbConfigName);
if(!$connConfig){
    die("配置库连接失败");
}
mysqli_set_charset($connConfig, "utf8mb4");
$configSql = "SELECT k,v FROM sys_config";
$configRes = mysqli_query($connConfig, $configSql);
$sysConfig = [];
while ($row = mysqli_fetch_assoc($configRes)) {
    $sysConfig[$row['k']] = $row['v'];
}

// 修复SMTP查询警告
$smtpRow = [];
$sqlSmtp = "SELECT * FROM sys_smtp_config WHERE id=1";
if (!empty(trim($sqlSmtp))) {
    $smtpQuery = mysqli_query($connConfig, $sqlSmtp);
    if ($smtpQuery !== false && $smtpQuery instanceof mysqli_result) {
        $smtpRow = mysqli_fetch_assoc($smtpQuery) ?: [];
    }
}
$smtpConfig = $smtpRow ?? [];

$pageTitle = htmlspecialchars($sysConfig['page_title'] ?? "告警监控系统");
$currentLang = $sysConfig['lang'] ?? "zh";
$sidebarRawLinks = $sysConfig['sidebar_links'] ?? "";
mysqli_close($connConfig);

// 多语言词典
$langMap = [
    'zh' => [
        'html_lang' => 'zh-CN',
        'page_subtitle' => '爱德万测试 · 运维告警监控平台',
        'monitor_panel' => '监控面板',
        'alert_overview' => '告警总览',
        'disk_capacity' => '磁盘容量',
        'alert_list_page' => '历史告警',
        'quick_link' => '快捷外链',
        'system_manage' => '系统管理',
        'system_config' => '系统参数',
        'smtp_config' => '邮箱SMTP配置',
        'current_user' => '当前用户：',
        'sys_time' => '系统时间：',
        'refresh_all' => '刷新页面',
        'export_csv' => '导出CSV',
        'logout' => '退出登录',
        'lang_text' => '语言：',
        'work_order_mgr' => '工单系统',
        'work_create' => '新建工单',
        'work_edit' => '编辑工单',
        'work_assign' => '分发工单',
        'work_status' => '工单状态',
        'work_creator' => '创建人',
        'work_handler' => '处理人',
        'work_content' => '工单内容/备注',
        'work_title' => '工单标题',
        'create_time' => '创建时间',
        'update_time' => '更新时间',
        'all_work_order' => '全部工单列表',
        'no_work_data' => '暂无工单数据',
        'save' => '保存',
        'cancel' => '取消',
        'title_placeholder' => '填写故障/需求标题',
        'content_placeholder' => '详细描述故障现象、操作步骤、处理方案',
        'select_handler' => '选择处理人（留空暂不分配）',
        'status_1' => '待处理',
        'status_2' => '处理中',
        'status_3' => '已完成',
        'status_4' => '已关闭',
        'no_alert_option' => '不关联任何告警',
        'relate_alert' => '关联告警（可选）',
        'relate_alert_id' => '关联告警ID',
        'notify_title' => '通知配置',
        'notify_user' => '通知接收人',
        'notify_channel' => '通知渠道',
        'channel_mail' => '邮箱',
        'channel_ding' => '钉钉',
        'channel_wecom' => '企业微信',
        'smtp_host' => 'SMTP服务器',
        'smtp_port' => '端口',
        'smtp_ssl' => '开启SSL/TLS',
        'smtp_account' => '发件账号',
        'smtp_pwd' => '授权密码',
        'smtp_from' => '发件邮箱',
        'save_smtp' => '保存SMTP配置',
        'alert_loading' => '加载活跃告警...',
        'no_alert_data' => '当前无正在触发的告警',
        'user_loading' => '加载用户列表',
        'no_user_data' => '无可用用户',
        'perm_deny' => '权限不足，禁止访问',
    ],
    'en' => [
        'html_lang' => 'en',
        'page_subtitle' => 'Advantest · O&M Alert Monitor Platform',
        'monitor_panel' => 'Monitor Panel',
        'alert_overview' => 'Alert Overview',
        'disk_capacity' => 'Disk Capacity',
        'alert_list_page' => 'History Alert',
        'quick_link' => 'Quick Links',
        'system_manage' => 'System Manage',
        'system_config' => 'System Config',
        'smtp_config' => 'SMTP Mail Config',
        'current_user' => 'User: ',
        'sys_time' => 'System Time: ',
        'refresh_all' => 'Refresh',
        'export_csv' => 'Export CSV',
        'logout' => 'Logout',
        'lang_text' => 'Lang: ',
        'work_order_mgr' => 'Work Order System',
        'work_create' => 'Create Order',
        'work_edit' => 'Edit Order',
        'work_assign' => 'Assign Order',
        'work_status' => 'Status',
        'work_creator' => 'Creator',
        'work_handler' => 'Handler',
        'work_content' => 'Content / Remark',
        'work_title' => 'Order Title',
        'create_time' => 'Create Time',
        'update_time' => 'Update Time',
        'all_work_order' => 'All Work Orders',
        'no_work_data' => 'No work orders',
        'save' => 'Save',
        'cancel' => 'Cancel',
        'title_placeholder' => 'Fill fault or demand title',
        'content_placeholder' => 'Describe fault, steps and handling plan',
        'select_handler' => 'Select handler (empty for unassigned)',
        'status_1' => 'Pending',
        'status_2' => 'Processing',
        'status_3' => 'Finished',
        'status_4' => 'Closed',
        'no_alert_option' => 'No related alert',
        'relate_alert' => 'Relate Alert (Optional)',
        'relate_alert_id' => 'Relate Alert ID',
        'notify_title' => 'Notification Config',
        'notify_user' => 'Notify Users',
        'notify_channel' => 'Notify Channel',
        'channel_mail' => 'Email',
        'channel_ding' => 'DingTalk',
        'channel_wecom' => 'WeCom',
        'smtp_host' => 'SMTP Host',
        'smtp_port' => 'Port',
        'smtp_ssl' => 'Enable SSL/TLS',
        'smtp_account' => 'SMTP Account',
        'smtp_pwd' => 'Auth Password',
        'smtp_from' => 'Sender Email',
        'save_smtp' => 'Save SMTP Config',
        'alert_loading' => 'Loading active alerts...',
        'no_alert_data' => 'No active firing alerts',
        'user_loading' => 'Loading user list...',
        'no_user_data' => 'No available users',
        'perm_deny' => 'Permission denied',
    ]
];
$t = $langMap[$currentLang];

// 解析外链菜单
$sidebarLinkList = [];
if (!empty($sidebarRawLinks)) {
    $lines = explode("\n", $sidebarRawLinks);
    foreach ($lines as $line) {
        $line = trim($line);
        if (empty($line)) continue;
        $item = explode("|", $line, 2);
        if (count($item) === 2) {
            $sidebarLinkList[] = ["name" => trim($item[0]), "url" => trim($item[1])];
        }
    }
}

// 工单业务库 monitor
$dbWorkHost = "10.150.117.190";
$dbWorkUser = "root";
$dbWorkPwd = "hp93000";
$dbWorkName = "monitor";
$connWork = mysqli_connect($dbWorkHost, $dbWorkUser, $dbWorkPwd, $dbWorkName);
if (!$connWork) {
    die("工单数据库 monitor 连接失败");
}
mysqli_set_charset($connWork, "utf8mb4");
$loginUid = $_SESSION['user_id'];

// 获取用户角色权限
$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);
if($stmtRole){
    mysqli_stmt_bind_param($stmtRole, 's', $loginUid);
    mysqli_stmt_execute($stmtRole);
    $roleRes = mysqli_stmt_get_result($stmtRole);
    if ($roleRes instanceof mysqli_result) {
        $roleRow = mysqli_fetch_assoc($roleRes);
        if ($roleRow) {
            $isAdmin = intval($roleRow['is_admin']);
            $permList = $roleRow['perm_list'];
        }
    }
}

// 权限校验临时注释，如需开启取消注释
//$hasWorkPerm = str_contains($permList, "work_order");
//if (!$hasWorkPerm) {
//    echo "<script>alert('".$t['perm_deny']."');location.href='dashboard.php';</script>";
//    exit;
//}

// 加载全部系统用户下拉
$userOptions = "";
$userAll = mysqli_query($connWork, "SELECT uid, real_name, username FROM sys_user WHERE enable = 1 ORDER BY real_name ASC");
if ($userAll instanceof mysqli_result) {
    while ($u = mysqli_fetch_assoc($userAll)) {
        $userOptions .= '<option value="' . $u['uid'] . '">' . $u['real_name'] . '(' . $u['username'] . ')</option>';
    }
}

// 分页参数
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$pageSize = intval($sysConfig['page_size'] ?? 20);
if ($pageSize < 1) $pageSize = 20;
$offset = ($page - 1) * $pageSize;

// 数据权限过滤
if ($isAdmin === 1) {
    $whereSql = " 1=1 ";
} else {
    $whereSql = " (create_uid = ? OR assign_uid = ?) ";
}

// 统计工单总数
$cntSql = "SELECT COUNT(*) total FROM work_order WHERE " . $whereSql;
$stmtCnt = mysqli_prepare($connWork, $cntSql);
$total = 0;
if($stmtCnt){
    if ($isAdmin !== 1) {
        mysqli_stmt_bind_param($stmtCnt, 'ss', $loginUid, $loginUid);
    }
    mysqli_stmt_execute($stmtCnt);
    $cntRes = mysqli_stmt_get_result($stmtCnt);
    if ($cntRes instanceof mysqli_result) {
        $cntRow = mysqli_fetch_assoc($cntRes);
        $total = intval($cntRow['total'] ?? 0);
    }
}
$totalPage = $pageSize <= 0 ? 1 : ceil($total / $pageSize);

// 查询工单列表
$listSql = "SELECT wo.*, uc.real_name create_name, ua.real_name assign_name
FROM work_order wo
LEFT JOIN sys_user uc ON wo.create_uid = uc.uid
LEFT JOIN sys_user ua ON wo.assign_uid = ua.uid
WHERE " . $whereSql . " ORDER BY create_time DESC LIMIT ?, ?";
$stmtList = mysqli_prepare($connWork, $listSql);
$orderList = [];
if($stmtList){
    if ($isAdmin === 1) {
        mysqli_stmt_bind_param($stmtList, 'ii', $offset, $pageSize);
    } else {
        mysqli_stmt_bind_param($stmtList, 'ssii', $loginUid, $loginUid, $offset, $pageSize);
    }
    mysqli_stmt_execute($stmtList);
    $listResult = mysqli_stmt_get_result($stmtList);
    if ($listResult instanceof mysqli_result) {
        while ($row = mysqli_fetch_assoc($listResult)) {
            $orderList[] = $row;
        }
    }
}
mysqli_close($connWork);
?>
<!DOCTYPE html>
<html lang="<?php echo $t['html_lang']; ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $pageTitle; ?> - Advantest <?php echo $t['work_order_mgr']; ?></title>
<link rel="stylesheet" href="/static/css/font-awesome.min.css">
<script src="/static/js/echarts.min.js"></script>
<script src="/static/js/jquery.min.js"></script>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#f9fafc;font-family:"Inter","PingFang SC","Microsoft YaHei";color:#1d2939;line-height:1.6;display:flex;flex-direction:column;height:100vh;overflow:hidden;}
.wrap-main{display:flex;flex:1;overflow:hidden;}
.sidebar{width:240px;background:#152c5b;color:#e2e8f0;flex-shrink:0;overflow-y:auto;}
.sidebar-brand{padding:26px 24px;border-bottom:1px solid rgba(255,255,255,0.1);}
.sidebar-brand-en{font-size:20px;font-weight:700;letter-spacing:1px;color:#fff;}
.sidebar-brand-cn{font-size:13px;color:#a5b4fc;margin-top:4px;}
.sidebar-menu{padding:16px 0;}
.menu-title{padding:10px 24px;font-size:12px;color:#94a3b8;letter-spacing:1px;}
.menu-item{display:flex;align-items:center;gap:12px;padding:14px 24px;cursor:pointer;font-size:14px;transition:0.2s;color:#cbd5e1;}
.menu-item i{font-size:16px;width:20px;text-align:center;}
.menu-item.active{background:rgba(255,255,255,0.12);color:#fff;border-left:4px solid #3b82f6;}
.menu-item:hover:not(.active){background:rgba(255,255,255,0.06);color:#fff;}
.main-content{flex:1;overflow-y:auto;display:flex;flex-direction:column;}
.header{background:#ffffff;border-bottom:1px solid #eef2fb;color:#152c5b;padding:20px 40px;display:flex;justify-content:space-between;align-items:center;box-shadow:0 2px 12px rgba(21,44,91,0.05);flex-shrink:0;}
.header-left{display:flex;align-items:center;gap:14px;}
.header-brand-en{font-size:24px;font-weight:700;letter-spacing:2px;color:#152c5b;}
.header-brand-cn{font-size:15px;color:#64748b;}
.header-right{display:flex;align-items:center;gap:18px;font-size:14px;flex-wrap:wrap;}
.user-info,.time-info,.lang-box{color:#475569;display:flex;align-items:center;gap:6px;}
.lang-box select{padding:4px 8px;border:1px solid #cbd5e1;border-radius:6px;}
.btn-base{border:none;padding:9px 20px;border-radius:8px;cursor:pointer;font-size:14px;display:flex;align-items:center;gap:6px;transition:all 0.2s ease;height:38px;}
.btn-sm{padding:6px 10px;height:32px;font-size:13px;}
.btn-outline{background:#ffffff;color:#152c5b;border:1px solid #cbd5e1;}
.btn-outline:hover{background:#f7f8fc;border-color:#152c5b;}
.btn-primary{background:#152c5b;color:#fff;}
.btn-primary:hover{background:#0f2347;}
.btn-success{background:#10b981;color:#fff;}
.btn-success:hover{background:#059669;}
.mask{position:fixed;left:0;top:0;width:100%;height:100%;background:rgba(255,255,255,0.85);display:none;z-index:1;align-items:center;justify-content:center;}
.mask-box{background:#fff;padding:30px 40px;border-radius:14px;font-size:15px;display:flex;gap:14px;align-items:center;box-shadow:0 8px 30px rgba(21,44,91,0.12);border:1px solid #eef2fb;}
.loading-spin{display:inline-block;width:20px;height:20px;border:2px solid #e2e8f0;border-top-color:#152c5b;border-radius:50%;animation:spin 0.8s linear infinite;}
@keyframes spin{to{transform:rotate(360deg)}}
.container{padding:36px 40px;max-width:100%;flex:1;}
.panel-card{background:#fff;border-radius:16px;padding:32px;box-shadow:0 3px 18px rgba(21,44,91,0.06);border:1px solid #eef2fb;margin-bottom:36px;}
.panel-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:26px;padding-bottom:16px;border-bottom:1px solid #eef2fb;}
.panel-title{display:flex;align-items:center;gap:12px;font-size:19px;font-weight:600;color:#152c5b;}
.panel-title i{color:#3b82f6;font-size:21px}
.table-wrap{overflow-x:auto}
table{width:100%;border-collapse:collapse;font-size:14px}
th{background:#f9fafc;color:#475569;font-weight:600;padding:16px 18px;text-align:left;border-bottom:2px solid #e2e8f0;white-space:nowrap;}
th i{margin-right:6px;font-size:13px;color:#94a3b8}
td{padding:18px;border-bottom:1px solid #f1f5f9;color:#334155;vertical-align:middle;}
tbody tr{transition:background 0.2s}
tbody tr:hover{background:#f7f8fc}
tbody tr:nth-child(even){background:#fbfcfe}
.empty-tip{text-align:center;padding:80px 20px;color:#94a3b8;font-size:15px;}
.empty-tip i{font-size:56px;margin-bottom:18px;opacity:0.35;}
.modal-mask{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.4);display:none;align-items:center;justify-content:center;z-index:999;pointer-events:none;}
.modal-box{width:720px;background:#fff;border-radius:16px;padding:32px;box-shadow:0 8px 30px rgba(21,44,91,0.12);max-height:90vh;overflow-y:auto;pointer-events:auto;}
.modal-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:26px;padding-bottom:16px;border-bottom:1px solid #eef2fb;}
.modal-close{cursor:pointer;font-size:22px;color:#94a3b8;}
.form-row{margin-bottom:20px;}
.form-row label{display:block;margin-bottom:8px;color:#475569;font-weight:500;}
.form-row input,.form-row select,.form-row textarea{width:100%;padding:10px 14px;border:1px solid #cbd5e1;border-radius:8px;font-size:14px;height:40px;}
.form-row textarea{height:140px;resize:none;}
.btn-group{display:flex;gap:14px;margin-top:10px;}
.select-sm{padding:6px 8px;border:1px solid #cbd5e1;border-radius:6px;font-size:13px;height:32px;}
.status-tag{display:inline-flex;align-items:center;gap:5px;padding:6px 14px;border-radius:24px;font-size:13px;font-weight:500;}
.tag-pending{background:#ffedd5;color:#ea580c}
.tag-processing{background:#dbeafe;color:#2563eb}
.tag-finished{background:#dcfce7;color:#16a34a}
.tag-closed{background:#f1f5f9;color:#64748b}
.pagination{display:flex;justify-content:space-between;align-items:center;margin-top:20px;flex-wrap:wrap;gap:16px;}
.page-btn{padding:8px 16px;border:1px solid #cbd5e1;background:#fff;border-radius:8px;cursor:pointer;font-size:14px;min-width:40px;text-align:center;transition:0.2s;}
.page-btn:hover{background:#f7f8fc;border-color:#152c5b;}
.page-btn.active{background:#152c5b;color:#fff;border-color:#152c5b;}
.page-btn:disabled{opacity:0.5;cursor:not-allowed;}
.checkbox-wrap{display:flex;gap:16px;flex-wrap:wrap;padding:8px 0;}
.checkbox-item{display:flex;align-items:center;gap:6px;padding:8px 12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafafa;min-width:130px;}
.checkbox-item input{width:auto;height:auto;}
.input-readonly{background:#f7f8fc;color:#64748b;}
.divider-top{margin:24px 0 8px;padding-top:16px;border-top:1px solid #eef2fb;}
@media (max-width:768px){
    .wrap-main{flex-direction:column;}
    .sidebar{width:100%;height:auto}
    .header{padding:16px 24px;flex-direction:column;gap:16px;align-items:flex-start}
    .header-right{flex-wrap:wrap}
    .container{padding:24px}
    .panel-card{padding:24px}
    .pagination{flex-direction:column;align-items:flex-start;}
}
</style>
</head>
<body>
<div class="mask" id="loadingMask">
    <div class="mask-box"><span class="loading-spin"></span><span></span></div>
</div>
<div class="wrap-main">
    <div class="sidebar">
        <div class="sidebar-brand">
            <div class="sidebar-brand-en">Advantest</div>
            <div class="sidebar-brand-cn"><?php echo $t['page_subtitle']; ?></div>
        </div>
        <div class="sidebar-menu">
            <div class="menu-title"><?php echo $t['monitor_panel']; ?></div>
            <div class="menu-item" onclick="location.href='dashboard.php'">
                <i class="fa fa-line-chart"></i><span><?php echo $t['alert_overview']; ?></span>
            </div>
            <div class="menu-item" onclick="location.href='dashboard.php#disk'">
                <i class="fa fa-hdd-o"></i><span><?php echo $t['disk_capacity']; ?></span>
            </div>
            <div class="menu-item" onclick="window.open('alert_list.php','_blank')">
                <i class="fa fa-list"></i><span><?php echo $t['alert_list_page']; ?></span>
            </div>
            <div class="menu-item active">
                <i class="fa fa-ticket"></i><span><?php echo $t['work_order_mgr']; ?></span>
            </div>
            <?php if (!empty($sidebarLinkList)): ?>
            <div class="menu-title"><?php echo $t['quick_link']; ?></div>
            <?php foreach ($sidebarLinkList as $link): ?>
            <div class="menu-item" onclick="window.open('<?php echo htmlspecialchars($link['url']); ?>','_blank')">
                <i class="fa fa-external-link"></i><span><?php echo htmlspecialchars($link['name']); ?></span>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
            <div class="menu-title"><?php echo $t['system_manage']; ?></div>
            <div class="menu-item" onclick="location.href='admin.php'">
                <i class="fa fa-cog"></i><span><?php echo $t['system_config']; ?></span>
            </div>
            <div class="menu-item" onclick="location.href='smtp_config.php'">
                <i class="fa fa-envelope-o"></i><span><?php echo $t['smtp_config']; ?></span>
            </div>
        </div>
    </div>
    <div class="main-content">
        <div class="header">
            <div class="header-left">
                <div>
                    <div class="header-brand-en">Advantest</div>
                    <div class="header-brand-cn"><?php echo $t['page_subtitle']; ?></div>
                </div>
            </div>
            <div class="header-right">
                <span class="user-info"><i class="fa fa-user-circle"></i><?php echo $t['current_user']; ?><?php echo $userName; ?></span>
                <span class="time-info"><i class="fa fa-clock-o"></i><span id="nowTime">--</span></span>
                <div class="lang-box">
                    <span><?php echo $t['lang_text']; ?></span>
                    <select id="langSwitch">
                        <option value="zh" <?php echo $currentLang==='zh'?'selected':''; ?>>中文</option>
                        <option value="en" <?php echo $currentLang==='en'?'selected':''; ?>>EN</option>
                    </select>
                </div>
                <button class="btn-base btn-outline" onclick="location.reload()"><i class="fa fa-refresh"></i><?php echo $t['refresh_all']; ?></button>
                <button class="btn-base btn-primary" onclick="location.href='logout.php'"><i class="fa fa-sign-out"></i><?php echo $t['logout']; ?></button>
            </div>
        </div>
        <div class="container">
            <div class="panel-card">
                <div class="panel-head">
                    <div class="panel-title"><i class="fa fa-ticket"></i><?php echo $t['all_work_order']; ?></div>
                    <button class="btn-base btn-success" id="openCreateModal"><i class="fa fa-plus"></i><?php echo $t['work_create']; ?></button>
                </div>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th><i class="fa fa-link"></i><?php echo $t['relate_alert_id']; ?></th>
                                <th><i class="fa fa-file-text-o"></i><?php echo $t['work_title']; ?></th>
                                <th><i class="fa fa-user"></i><?php echo $t['work_creator']; ?></th>
                                <th><i class="fa fa-user-o"></i><?php echo $t['work_handler']; ?></th>
                                <th><i class="fa fa-tag"></i><?php echo $t['work_status']; ?></th>
                                <th><i class="fa fa-calendar-o"></i><?php echo $t['create_time']; ?></th>
                                <th><i class="fa fa-clock-o"></i><?php echo $t['update_time']; ?></th>
                                <th>OP</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($orderList) === 0): ?>
                            <tr>
                                <td colspan="9">
                                    <div class="empty-tip">
                                        <i class="fa fa-ticket"></i>
                                        <div><?php echo $t['no_work_data']; ?></div>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($orderList as $item): ?>
                            <?php
                            $statusText = ''; $statusClass = '';
                            switch ($item['status']) {
                                case 1:$statusText=$t['status_1'];$statusClass='tag-pending';break;
                                case 2:$statusText=$t['status_2'];$statusClass='tag-processing';break;
                                case 3:$statusText=$t['status_3'];$statusClass='tag-finished';break;
                                case 4:$statusText=$t['status_4'];$statusClass='tag-closed';break;
                            }
                            ?>
                            <tr data-id="<?php echo $item['id']; ?>"
                                data-title="<?php echo htmlspecialchars($item['title']); ?>"
                                data-content="<?php echo htmlspecialchars($item['content']); ?>"
                                data-assign="<?php echo $item['assign_uid']; ?>"
                                data-status="<?php echo $item['status']; ?>"
                                data-relate="<?php echo htmlspecialchars($item['relate_alert_id'] ?? ''); ?>"
                                data-notifyuser="<?php echo htmlspecialchars($item['notify_user'] ?? ''); ?>"
                                data-notifychannel="<?php echo htmlspecialchars($item['notify_channel'] ?? ''); ?>">
                                <td><?php echo $item['id']; ?></td>
                                <td><?php echo htmlspecialchars($item['relate_alert_id'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($item['title']); ?></td>
                                <td><?php echo $item['create_name'] ?? '-'; ?></td>
                                <td><?php echo $item['assign_name'] ?? '-'; ?></td>
                                <td><span class="status-tag <?php echo $statusClass; ?>"><?php echo $statusText; ?></span></td>
                                <td><?php echo $item['create_time']; ?></td>
                                <td><?php echo $item['update_time'] ?? '-'; ?></td>
                                <td style="display:flex;gap:6px;align-items:center;">
                                    <?php if ($isAdmin === 1): ?>
                                    <select class="assign-user select-sm">
                                        <option value="">--</option>
                                        <?php echo $userOptions; ?>
                                    </select>
                                    <?php endif; ?>
                                    <select class="status-select select-sm">
                                        <option value="1" <?php echo $item['status']==1?'selected':''; ?>><?php echo $t['status_1']; ?></option>
                                        <option value="2" <?php echo $item['status']==2?'selected':''; ?>><?php echo $t['status_2']; ?></option>
                                        <option value="3" <?php echo $item['status']==3?'selected':''; ?>><?php echo $t['status_3']; ?></option>
                                        <option value="4" <?php echo $item['status']==4?'selected':''; ?>><?php echo $t['status_4']; ?></option>
                                    </select>
                                    <button class="btn-base btn-outline btn-sm edit-order"><i class="fa fa-edit"></i><?php echo $t['work_edit']; ?></button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <!-- 重构分页 -->
                <div class="pagination">
                    <div><?php echo $currentLang==='zh'?'共 ':'Total '; ?><?php echo $total; ?> <?php echo $currentLang==='zh'?'条':'records'; ?></div>
                    <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
                        <?php if ($page > 1): ?>
                        <button class="page-btn" onclick="location.href='work_order.php?page=1'"><?php echo $currentLang==='zh'?'首页':'First' ?></button>
                        <button class="page-btn" onclick="location.href='work_order.php?page=<?php echo $page-1; ?>'"><?php echo $currentLang==='zh'?'上一页':'Prev' ?></button>
                        <?php else: ?>
                        <button class="page-btn" disabled><?php echo $currentLang==='zh'?'首页':'First' ?></button>
                        <button class="page-btn" disabled><?php echo $currentLang==='zh'?'上一页':'Prev' ?></button>
                        <?php endif; ?>
                        <?php
                        $start = max(1, $page - 2);
                        $end = min($totalPage, $page + 2);
                        for ($i = $start; $i <= $end; $i++):
                        ?>
                        <button class="page-btn <?php echo $i == $page ? 'active' : ''; ?>" onclick="location.href='work_order.php?page=<?php echo $i; ?>'"><?php echo $i; ?></button>
                        <?php endfor; ?>
                        <?php if ($page < $totalPage): ?>
                        <button class="page-btn" onclick="location.href='work_order.php?page=<?php echo $page+1; ?>'"><?php echo $currentLang==='zh'?'下一页':'Next' ?></button>
                        <button class="page-btn" onclick="location.href='work_order.php?page=<?php echo $totalPage; ?>'"><?php echo $currentLang==='zh'?'末页':'Last' ?></button>
                        <?php else: ?>
                        <button class="page-btn" disabled><?php echo $currentLang==='zh'?'下一页':'Next' ?></button>
                        <button class="page-btn" disabled><?php echo $currentLang==='zh'?'末页':'Last' ?></button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- 新建工单弹窗 -->
<div class="modal-mask" id="createModal">
    <div class="modal-box">
        <div class="modal-head">
            <div class="panel-title"><i class="fa fa-plus"></i><?php echo $t['work_create']; ?></div>
            <span class="modal-close" id="closeCreateModal">×</span>
        </div>
        <div class="form-row">
            <label><?php echo $t['relate_alert']; ?></label>
            <select id="relateAlertSelect">
                <option value="">-- <?php echo $t['no_alert_option']; ?> --</option>
            </select>
            <div class="form-desc"><?php echo $currentLang==='zh'?'选择后自动填充工单标题与告警基础信息':'Auto fill title and alert info after select'; ?></div>
        </div>
        <div class="form-row">
            <label><?php echo $t['work_title']; ?></label>
            <input type="text" id="orderTitle" placeholder="<?php echo $t['title_placeholder']; ?>">
        </div>
        <div class="form-row">
            <label><?php echo $t['work_content']; ?></label>
            <textarea id="orderContent" placeholder="<?php echo $t['content_placeholder']; ?>"></textarea>
        </div>
        <div class="form-row">
            <label><?php echo $t['work_handler']; ?></label>
            <select id="orderAssign">
                <option value=""><?php echo $t['select_handler']; ?></option>
                <?php echo $userOptions; ?>
            </select>
        </div>
        <div class="divider-top"></div>
        <div class="panel-title" style="font-size:16px;margin-bottom:12px;"><i class="fa fa-bell"></i><?php echo $t['notify_title']; ?></div>
        <div class="form-row">
            <label><?php echo $t['notify_user']; ?></label>
            <select id="notifyUserSelect" multiple style="height:120px;">
                <?php echo $userOptions; ?>
            </select>
            <div class="form-desc"><?php echo $currentLang==='zh'?'按住Ctrl多选通知人员':'Hold Ctrl multi-select users'; ?></div>
        </div>
        <div class="form-row">
            <label><?php echo $t['notify_channel']; ?></label>
            <div class="checkbox-wrap">
                <div class="checkbox-item">
                    <input type="checkbox" id="chMail" value="mail">
                    <label for="chMail"><i class="fa fa-envelope-o"></i> <?php echo $t['channel_mail']; ?></label>
                </div>
                <div class="checkbox-item">
                    <input type="checkbox" id="chDing" value="dingtalk">
                    <label for="chDing"><i class="fa fa-comment"></i> <?php echo $t['channel_ding']; ?></label>
                </div>
                <div class="checkbox-item">
                    <input type="checkbox" id="chWecom" value="wecom">
                    <label for="chWecom"><i class="fa fa-wechat"></i> <?php echo $t['channel_wecom']; ?></label>
                </div>
            </div>
        </div>
        <div class="btn-group">
            <button class="btn-base btn-primary" id="submitOrder"><i class="fa fa-save"></i><?php echo $t['save']; ?></button>
            <button class="btn-base btn-outline" id="resetForm"><i class="fa fa-refresh"></i><?php echo $t['cancel']; ?></button>
        </div>
    </div>
</div>

<!-- 编辑工单弹窗 -->
<div class="modal-mask" id="editModal">
    <div class="modal-box">
        <div class="modal-head">
            <div class="panel-title"><i class="fa fa-edit"></i><?php echo $t['work_edit']; ?></div>
            <span class="modal-close" id="closeEditModal">×</span>
        </div>
        <input type="hidden" id="editOrderId">
        <input type="hidden" id="editRelateAlertId">
        <!-- 新增可选择告警下拉框 -->
        <div class="form-row">
            <label><?php echo $t['relate_alert']; ?></label>
            <select id="editRelateAlertSelect" style="width:100%;">
                <option value="">-- <?php echo $t['no_alert_option']; ?> --</option>
            </select>
            <div class="form-desc"><?php echo $currentLang==='zh'?'下拉可更换关联故障告警':'Re-select active alert' ?></div>
        </div>
        <!-- 保留只读展示框 -->
        <div class="form-row">
            <label>当前绑定告警ID（只读）</label>
            <input type="text" id="editRelateAlertShow" readonly class="input-readonly">
        </div>
        <div class="form-row">
            <label><?php echo $t['work_title']; ?></label>
            <input type="text" id="editTitle">
        </div>
        <div class="form-row">
            <label><?php echo $t['work_content']; ?></label>
            <textarea id="editContent"></textarea>
        </div>
        <div class="form-row">
            <label><?php echo $t['work_handler']; ?></label>
            <select id="editAssign">
                <option value="">--</option>
                <?php echo $userOptions; ?>
            </select>
        </div>
        <div class="divider-top"></div>
        <div class="panel-title" style="font-size:16px;margin-bottom:12px;"><i class="fa fa-bell"></i><?php echo $t['notify_title']; ?></div>
        <div class="form-row">
            <label><?php echo $t['notify_user']; ?></label>
            <select id="editNotifyUser" multiple style="height:120px;">
                <?php echo $userOptions; ?>
            </select>
        </div>
        <div class="form-row">
            <label><?php echo $t['notify_channel']; ?></label>
            <div class="checkbox-wrap">
                <div class="checkbox-item"><input type="checkbox" id="editChMail" value="mail"><label for="editChMail"><i class="fa fa-envelope-o"></i> <?php echo $t['channel_mail']; ?></label></div>
                <div class="checkbox-item"><input type="checkbox" id="editChDing" value="dingtalk"><label for="editChDing"><i class="fa fa-comment"></i> <?php echo $t['channel_ding']; ?></label></div>
                <div class="checkbox-item"><input type="checkbox" id="editChWecom" value="wecom"><label for="editChWecom"><i class="fa fa-wechat"></i> <?php echo $t['channel_wecom']; ?></label></div>
            </div>
        </div>
        <div class="btn-group">
            <button class="btn-base btn-primary" id="saveEdit"><i class="fa fa-save"></i><?php echo $t['save']; ?></button>
            <button class="btn-base btn-outline" id="cancelEdit"><?php echo $t['cancel']; ?></button>
        </div>
    </div>
</div>

<script>
const apiAlert = "./api/index.php";
const apiOrder = "./api/work_order_api.php";
const loginUid = "<?php echo $loginUid; ?>";
const lang = "<?php echo $currentLang; ?>";
let firingAlertList = [];

// 顶部时间
function updateClock() {
    const now = new Date();
    const Y = now.getFullYear();
    const M = String(now.getMonth()+1).padStart(2,"0");
    const D = String(now.getDate()).padStart(2,"0");
    const h = String(now.getHours()).padStart(2,"0");
    const m = String(now.getMinutes()).padStart(2,"0");
    const s = String(now.getSeconds()).padStart(2,"0");
    $("#nowTime").text(`${Y}-${M}-${D} ${h}:${m}:${s}`);
}
setInterval(updateClock, 1000);
updateClock();

// 语言切换
$("#langSwitch").change(function(){
    const newLang = $(this).val();
    $.post(apiOrder, {action:"save_lang", lang:newLang}, ()=>location.reload());
})

// 加载仪表盘未恢复告警下拉
function loadActiveFiringAlert(selectDom, bindValue=""){
    $.getJSON(apiAlert + "?act=active_firing", function(list){
        firingAlertList = list;
        const $sel = $(selectDom);
        $sel.html(`<option value="">-- <?php echo $t['no_alert_option']; ?> --</option>`);
        list.forEach(item=>{
            const uniqueKey = `${item.alert_name}|${item.instance}`;
            $sel.append(`
                <option value="${uniqueKey}" data-alert-name="${item.alert_name}" data-ip="${item.instance}">
                    [${item.instance}] ${item.alert_name}
                </option>
            `);
        })
        if(bindValue) $sel.val(bindValue);
    }).fail(()=>{
        $(selectDom).html(`<option value=""><?php echo $currentLang==='zh'?'实时告警加载失败':'Failed load active alerts' ?></option>`);
    })
}

// 新建告警下拉自动填充标题
$("#relateAlertSelect").on("change", function(){
    const opt = $(this).find("option:selected");
    const alertName = opt.data("alert-name");
    const ip = opt.data("ip");
    if(!alertName){
        $("#orderTitle").val("");
        $("#orderContent").val("");
        return;
    }
    $("#orderTitle").val(alertName);
    const desc = lang === "zh"
        ? `关联故障：${alertName}\n实例地址：${ip}\n故障状态：当前未恢复\n=====处理备注=====\n`
        : `Alert: ${alertName}\nInstance: ${ip}\nStatus: Firing\n=====Handling Note=====\n`;
    $("#orderContent").val(desc);
})

// 打开新建弹窗
$("#openCreateModal").click(function(){
    $("#createModal").css("display","flex");
    loadActiveFiringAlert("#relateAlertSelect");
})

// 打开编辑工单回填数据
$(document).on("click", ".edit-order", function(){
    const tr = $(this).closest("tr");
    // 回填主键ID
    $("#editOrderId").val(tr.data("id"));
    // 告警
    const bindRelateId = tr.data("relate");
    $("#editRelateAlertShow").val(bindRelateId);
    loadActiveFiringAlert("#editRelateAlertSelect", bindRelateId);
    // 基础内容
    $("#editTitle").val(tr.data("title"));
    $("#editContent").val(tr.data("content"));
    $("#editAssign").val(tr.data("assign"));
    $("#editModal").css("display","flex");
})

// 关闭弹窗
$(".modal-close, .modal-mask").click(function(e){
    if($(e.target).is(".modal-box") || $(e.target).closest(".modal-box").length) return;
    $(this).hide();
})

// ========== 新建工单保存 ==========
$("#submitOrder").click(function(){
    console.log("点击新建保存"); // F12控制台打印，判断是否触发点击
    const title = $("#orderTitle").val().trim();
    const content = $("#orderContent").val().trim();
    const assign_uid = $("#orderAssign").val();
    const relate_alert_id = $("#relateAlertSelect").val();
    // 通知人、渠道
    const notify_user = $("#notifyUserSelect").val() || [];
    const notify_channel = [];
    if($("#chMail").prop("checked")) notify_channel.push("mail");
    if($("#chDing").prop("checked")) notify_channel.push("dingtalk");
    if($("#chWecom").prop("checked")) notify_channel.push("wecom");

    if(!title) return alert(lang==="zh"?"请填写工单标题":"Please input title");

    $.post(apiOrder, {
        action: "create",
        title: title,
        content: content,
        assign_uid: assign_uid,
        relate_alert_id: relate_alert_id,
        notify_user: notify_user.join(","),
        notify_channel: notify_channel.join(",")
    }, function(res){
        console.log("新建返回：", res);
        let ret = JSON.parse(res);
        if(ret.code===0){
            alert(ret.msg);
            location.reload();
        }else{
            alert(ret.msg);
        }
    }).fail(function(xhr){
        console.log("新建请求失败：", xhr.responseText);
        alert(lang==="zh"?"提交请求失败":"Request failed");
    });
})

// ========== 编辑工单保存（修复通知下拉ID错误） ==========
$("#saveEdit").click(function(){
    console.log("点击编辑保存"); // 控制台打印判断点击是否生效
    const id = $("#editOrderId").val();
    const title = $("#editTitle").val().trim();
    const content = $("#editContent").val().trim();
    const assign_uid = $("#editAssign").val();
    const relate_alert_id = $("#editRelateAlertSelect").val();
    // 修复：编辑通知下拉ID是 notifyUserSelect，不是 editNotifyUser
    const notify_user = $("#notifyUserSelect").val() || [];
    const notify_channel = [];
    if($("#editChMail").prop("checked")) notify_channel.push("mail");
    if($("#editChDing").prop("checked")) notify_channel.push("dingtalk");
    if($("#editChWecom").prop("checked")) notify_channel.push("wecom");

    if(!title) return alert(lang==="zh"?"请填写工单标题":"Please input title");
    if(!id) return alert(lang==="zh"?"工单ID缺失，无法保存":"Order id missing");

    $.post(apiOrder, {
        action: "edit",
        id: id,
        title: title,
        content: content,
        assign_uid: assign_uid,
        relate_alert_id: relate_alert_id,
        notify_user: notify_user.join(","),
        notify_channel: notify_channel.join(",")
    }, function(res){
        console.log("编辑返回：", res);
        let ret = JSON.parse(res);
        if(ret.code===0){
            alert(ret.msg);
            location.reload();
        }else{
            alert(ret.msg);
        }
    }).fail(function(xhr){
        console.log("编辑请求失败：", xhr.responseText);
        alert(lang==="zh"?"保存请求失败":"Request failed");
    });
})

// 页面初始化
$(function(){
    loadActiveFiringAlert("#relateAlertSelect");
})
</script>
</body>
</html>
