<?php
session_start();
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    session_destroy();
    header("Location: login.php");
    exit;
}
$loginUid = $_SESSION['user_id'];
$userName = $_SESSION['user_name'] ?? '';

$dbHost = '10.150.117.190';
$dbUser = 'root';
$dbPwd = 'hp93000';
$dbName = 'monitor';
$dbPort = 3306;

$conn = mysqli_connect($dbHost, $dbUser, $dbPwd, $dbName, $dbPort);
if (!$conn) {
    die("数据库连接失败：" . mysqli_connect_error() . " 错误码：" . mysqli_connect_errno());
}
mysqli_set_charset($conn, 'utf8mb4');

// 获取当前登录用户角色（是否管理员）
$isAdmin = 0;
$roleSql = "SELECT r.is_admin FROM sys_user u LEFT JOIN sys_role r ON u.role_id=r.id WHERE u.uid = ?";
$stmtRole = mysqli_prepare($conn, $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']);

// 获取所有用户（分发下拉框）
$userOptions = "";
$userRes = mysqli_query($conn, "SELECT uid, real_name, username FROM sys_user WHERE enable = 1");
while ($u = mysqli_fetch_assoc($userRes)) {
    $userOptions .= '<option value="' . $u['uid'] . '">' . $u['real_name'] . '(' . $u['username'] . ')</option>';
}

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

// 权限过滤SQL
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($conn, $cntSql);
if ($isAdmin !== 1) {
    mysqli_stmt_bind_param($stmtCnt, 'ss', $loginUid, $loginUid);
}
mysqli_stmt_execute($stmtCnt);
$cntRow = mysqli_fetch_assoc(mysqli_stmt_get_result($stmtCnt));
$total = intval($cntRow['total']);
$totalPage = 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($conn, $listSql);
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);
$orderList = [];
while ($row = mysqli_fetch_assoc($listResult)) {
    $orderList[] = $row;
}
mysqli_close($conn);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>工单管理</title>
<link rel="stylesheet" href="/static/css/font-awesome.min.css">
<script src="/static/js/jquery.min.js"></script>
<style>
*{box-sizing:border-box;margin:0;padding:0;font-family:"Microsoft YaHei",system-ui,sans-serif;color:#1D2129;font-size:14px;}
body{background:#F5F7FA;display:flex;}
/* 左侧侧边栏 与dashboard统一 */
.sidebar{width:220px;background:#0F172A;height:100vh;position:fixed;padding-top:20px;}
.sidebar-title{color:#fff;font-size:16px;padding:0 20px 20px;border-bottom:1px solid #222;margin-bottom:16px;}
.sidebar-menu a{display:block;color:#A1AEC0;padding:12px 20px;text-decoration:none;transition:0.2s;}
.sidebar-menu a:hover{background:#1E293B;color:#fff;}
.sidebar-menu a.active{background:#165DFF;color:#fff;}
.sidebar-menu i{margin-right:8px;width:16px;text-align:center;}
/* 主内容区域 */
.main-container{margin-left:220px;width:calc(100% - 220px);padding:20px;}
.header-top{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;}
.user-group{display:flex;gap:12px;align-items:center;}
/* 卡片通用 */
.card{background:#FFFFFF;border-radius:8px;padding:20px;box-shadow:0 1px 2px rgba(0,0,0,0.06);margin-bottom:16px;}
.card-title{font-size:16px;font-weight:500;margin-bottom:16px;}
/* 按钮统一样式 */
.btn{height:36px;padding:0 16px;border:none;border-radius:6px;cursor:pointer;display:flex;align-items:center;gap:6px;transition:0.15s;}
.btn-primary{background:#165DFF;color:#fff;}
.btn-primary:hover{background:#0E4BDB;}
.btn-outline{background:#fff;color:#4E5969;border:1px solid #DCDFE6;}
.btn-outline:hover{border-color:#165DFF;color:#165DFF;}
.btn-danger{background:#F53F3F;color:#fff;}
.btn-danger:hover{background:#D83636;}
.btn-sm{height:28px;padding:0 8px;font-size:13px;}
/* 表格 */
.table-wrap{overflow-x:auto;}
table{width:100%;border-collapse:collapse;}
th{background:#F5F7FA;padding:12px 10px;text-align:left;border-bottom:1px solid #E5E6EB;color:#4E5969;font-weight:500;white-space:nowrap;}
td{padding:12px 10px;border-bottom:1px solid #F2F3F5;}
/* 分页 */
.pagination{display:flex;justify-content:space-between;align-items:center;margin-top:16px;}
.pag-btn{height:32px;padding:0 12px;border:1px solid #DCDFE6;background:#fff;border-radius:6px;cursor:pointer;}
/* 弹窗遮罩 */
.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;}
.modal-box{width:680px;background:#fff;border-radius:8px;padding:24px;}
.modal-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;}
.modal-close{cursor:pointer;font-size:20px;color:#86909C;}
.form-row{margin-bottom:18px;}
.form-row label{display:block;margin-bottom:6px;color:#4E5969;}
.form-row input,.form-row select,.form-row textarea{width:100%;height:38px;padding:0 14px;border:1px solid #DCDFE6;border-radius:6px;font-size:14px;}
.form-row textarea{height:100px;resize:none;padding-top:10px;}
.form-desc{font-size:12px;color:#86909C;margin-top:4px;}
.btn-group{display:flex;gap:12px;}
/* 状态文字 */
.status-1{color:#FF7D00;}
.status-2{color:#165DFF;}
.status-3{color:#00B42A;}
.status-4{color:#86909C;}
</style>
</head>
<body>
<!-- 左侧侧边导航 -->
<div class="sidebar">
    <div class="sidebar-title">运维监控平台</div>
    <div class="sidebar-menu">
        <a href="dashboard.php"><i class="fa fa-home"></i> 监控大盘首页</a>
        <a href="alert_index.php"><i class="fa fa-bell"></i> 告警监控面板</a>
        <a href="alert_subscribe.php"><i class="fa fa-bell-o"></i> 告警订阅管理</a>
        <a href="work_order.php" class="active"><i class="fa fa-ticket"></i> 工单管理</a>
        <?php if ($isAdmin === 1): ?>
        <a href="sys_user.php"><i class="fa fa-users"></i> 用户管理</a>
        <?php endif; ?>
    </div>
</div>

<!-- 主内容 -->
<div class="main-container">
    <div class="header-top">
        <h2>工单管理</h2>
        <div class="user-group">
            <span><i class="fa fa-user"></i> <?php echo $userName; ?></span>
            <button class="btn btn-outline" onclick="if(confirm('确定退出账号？'))location.href='login.php'"><i class="fa fa-sign-out"></i> 退出登录</button>
        </div>
    </div>

    <!-- 操作栏 -->
    <div class="card">
        <div style="display:flex;justify-content:space-between;align-items:center;">
            <div class="card-title">工单列表</div>
            <button class="btn btn-primary" id="openCreateModal"><i class="fa fa-plus"></i> 新建工单</button>
        </div>
    </div>

    <!-- 工单列表表格 -->
    <div class="card">
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>工单标题</th>
                        <th>创建人</th>
                        <th>处理人</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($orderList) === 0): ?>
                    <tr>
                        <td colspan="8" class="empty-box">暂无工单数据</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($orderList as $item): ?>
                    <?php
                    // 状态文本
                    $statusText = '';
                    $statusClass = '';
                    switch ($item['status']) {
                        case 1: $statusText = '待处理'; $statusClass = 'status-1'; break;
                        case 2: $statusText = '处理中'; $statusClass = 'status-2'; break;
                        case 3: $statusText = '已完成'; $statusClass = 'status-3'; break;
                        case 4: $statusText = '已关闭'; $statusClass = 'status-4'; break;
                    }
                    ?>
                    <tr data-id="<?php echo $item['id']; ?>" data-assign="<?php echo $item['assign_uid']; ?>" data-status="<?php echo $item['status']; ?>">
                        <td><?php echo $item['id']; ?></td>
                        <td><?php echo htmlspecialchars($item['title']); ?></td>
                        <td><?php echo $item['create_name'] ?? '-'; ?></td>
                        <td><?php echo $item['assign_name'] ?? '未分配'; ?></td>
                        <td class="<?php echo $statusClass; ?>"><?php echo $statusText; ?></td>
                        <td><?php echo $item['create_time']; ?></td>
                        <td><?php echo $item['update_time'] ?? '-'; ?></td>
                        <td>
                            <?php if ($isAdmin === 1): ?>
                            <!-- 管理员：可分发工单 -->
                            <select class="assign-user" style="height:28px;padding:0 6px;border:1px solid #DCDFE6;border-radius:4px;">
                                <option value="">取消分配</option>
                                <?php echo $userOptions; ?>
                            </select>
                            <?php endif; ?>
                            <select class="status-select btn-sm" style="height:28px;padding:0 6px;border:1px solid #DCDFE6;border-radius:4px;margin-left:4px;">
                                <option value="1" <?php echo $item['status'] == 1 ? 'selected' : ''; ?>>待处理</option>
                                <option value="2" <?php echo $item['status'] == 2 ? 'selected' : ''; ?>>处理中</option>
                                <option value="3" <?php echo $item['status'] == 3 ? 'selected' : ''; ?>>已完成</option>
                                <option value="4" <?php echo $item['status'] == 4 ? 'selected' : ''; ?>>关闭</option>
                            </select>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <!-- 分页 -->
        <div class="pagination">
            <div>共 <?php echo $total; ?> 条工单</div>
            <div style="display:flex;gap:8px;align-items:center;">
                <?php if ($page > 1): ?>
                <button class="pag-btn" onclick="location.href='work_order.php?page=<?php echo $page - 1; ?>'">上一页</button>
                <?php endif; ?>
                <span>第<?php echo $page; ?> / <?php echo $totalPage; ?>页</span>
                <?php if ($page < $totalPage): ?>
                <button class="pag-btn" onclick="location.href='work_order.php?page=<?php echo $page + 1; ?>'">下一页</button>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- 新建工单弹窗 -->
<div class="modal-mask" id="createModal">
    <div class="modal-box">
        <div class="modal-head">
            <h3 class="card-title">新建故障工单</h3>
            <span class="modal-close" id="closeCreateModal">×</span>
        </div>
        <div class="form-row">
            <label>工单标题</label>
            <input type="text" id="orderTitle" placeholder="请输入故障/需求标题">
        </div>
        <div class="form-row">
            <label>工单内容描述</label>
            <textarea id="orderContent" placeholder="详细描述故障现象、操作步骤、期望处理结果"></textarea>
        </div>
        <div class="form-row">
            <label>分配处理人（可选）</label>
            <select id="orderAssign">
                <option value="">暂不分配</option>
                <?php echo $userOptions; ?>
            </select>
            <div class="form-desc">可后续在列表重新分发</div>
        </div>
        <div class="btn-group">
            <button class="btn btn-primary" id="submitOrder"><i class="fa fa-save"></i> 提交工单</button>
            <button class="btn btn-outline" id="resetForm"><i class="fa fa-refresh"></i> 重置</button>
        </div>
    </div>
</div>
<script>
const apiOrder = "./api/work_order_api.php";
const loginUid = "<?php echo $loginUid; ?>";
const isAdmin = <?php echo $isAdmin; ?>;

// 打开/关闭新建弹窗
$("#openCreateModal").click(()=>{
    console.log("打开新建工单弹窗");
    $("#createModal").css("display","flex");
});
$("#closeCreateModal").click(()=>$("#createModal").hide());
$("#resetForm").click(()=>{
    $("#orderTitle").val("");
    $("#orderContent").val("");
    $("#orderAssign").val("");
});

// 提交工单 增加console调试
$("#submitOrder").click(function(){
    console.log("点击提交按钮");
    const title = $("#orderTitle").val().trim();
    const content = $("#orderContent").val().trim();
    const assign = $("#orderAssign").val();
    console.log("表单数据：",{title,content,assign});

    if(!title) {
        alert("请填写工单标题");
        return;
    }
    if(!content) {
        alert("请填写工单内容");
        return;
    }

    $.ajax({
        url: apiOrder + "?action=create",
        method: "POST",
        contentType: "application/json",
        data: JSON.stringify({
            title: title,
            content: content,
            assign_uid: assign
        }),
        dataType: "json",
        success: function(res){
            console.log("接口返回数据：", res);
            alert(res.msg);
            if(res.code === 0) {
                location.reload();
            }
        },
        error: function(xhr,status,err){
            console.error("AJAX请求失败", xhr.responseText, err);
            alert("提交请求异常，请查看控制台F12");
        }
    })
});

// 变更工单状态
$(document).on("change", ".status-select", function(){
    const tr = $(this).closest("tr");
    const id = tr.data("id");
    const status = $(this).val();
    $.ajax({
        url: apiOrder + "?action=update_status",
        method: "POST",
        contentType: "application/json",
        data: JSON.stringify({id,status}),
        dataType: "json",
        success(res){
            console.log("状态更新返回：", res);
            if(res.code !== 0) alert(res.msg);
            else location.reload();
        },
        error(){
            alert("状态更新请求失败");
        }
    })
});

// 管理员分发工单
$(document).on("change", ".assign-user", function(){
    const tr = $(this).closest("tr");
    const id = tr.data("id");
    const assignUid = $(this).val();
    $.ajax({
        url: apiOrder + "?action=assign_order",
        method: "POST",
        contentType: "application/json",
        data: JSON.stringify({id,assign_uid:assignUid}),
        dataType: "json",
        success(res){
            console.log("分发工单返回：", res);
            if(res.code !== 0) alert(res.msg);
            else location.reload();
        },
        error(){
            alert("分发工单请求失败");
        }
    })
});
</script>
