<?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'];

// 数据库本地连接，避免远程拦截
$dbHost = '10.150.117.190';
$dbUser = 'root';
$dbPwd = 'hp93000';
$dbName = 'monitor';
$dbPort = 3306;
$conn = mysqli_connect($dbHost, $dbUser, $dbPwd, $dbName, $dbPort);
if (!$conn) {
    echo json_encode([
        'code' => 500,
        'msg' => '数据库连接失败：' . mysqli_connect_error()
    ]);
    exit;
}
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']);

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

// 1、新建工单（修复第50行引用报错）
if ($action === "create") {
    $title = trim($post['title'] ?? '');
    $content = trim($post['content'] ?? '');
    $assign = trim($post['assign_uid'] ?? '');
    $status = 1; // 单独定义变量，不能直接写1传入bind_param
    if (!$title || !$content) {
        echo json_encode(['code' => 400, 'msg' => '标题和内容不能为空']);
        exit;
    }
    $sql = "INSERT INTO work_order(title,content,create_uid,assign_uid,status,create_time,update_time) VALUES (?,?,?,?,?,NOW(),NOW())";
    $stmt = mysqli_prepare($conn, $sql);
    // 全部使用变量传参，禁止直接写数字/字符串
    mysqli_stmt_bind_param($stmt, 'ssssi', $title, $content, $loginUid, $assign, $status);
    $ok = mysqli_stmt_execute($stmt);
    if ($ok) {
        echo json_encode(['code' => 0, 'msg' => '工单提交成功']);
    } else {
        echo json_encode(['code' => 500, 'msg' => '提交失败：' . mysqli_error($conn)]);
    }
    exit;
}

// 2、修改工单状态
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($conn, $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($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'ii', $status, $id);
    mysqli_stmt_execute($stmt);
    echo json_encode(['code' => 0, 'msg' => '状态更新成功']);
    exit;
}

// 3、管理员分发工单
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($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'si', $assignUid, $id);
    mysqli_stmt_execute($stmt);
    echo json_encode(['code' => 0, 'msg' => '工单分发成功']);
    exit;
}

// 无效操作
echo json_encode(['code' => 400, 'msg' => '无效操作']);
mysqli_close($conn);
exit;
?>
