<?php
session_start();
require_once __DIR__ . '/../lib/config.php';
require_once __DIR__ . '/../lib/db_connect.php';
require_once __DIR__ . '/../includes/header.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];

// 检查用户是否是代理
$is_agent = false;
$agent_check = $conn->prepare("SELECT id FROM agents WHERE user_id = ?");
if ($agent_check === false) {
    die("代理检查预处理失败: " . $conn->error);
}
$agent_check->bind_param("i", $user_id);
$agent_check->execute();
if ($agent_check->get_result()->num_rows > 0) {
    $is_agent = true;
}
$agent_check->close();

// 获取用户信誉等级
$reputation_level = '正常信誉'; // 默认值
$reputation_stmt = $conn->prepare("SELECT reputation_level FROM users WHERE id = ?");
if ($reputation_stmt) {
    $reputation_stmt->bind_param("i", $user_id);
    $reputation_stmt->execute();
    $reputation_stmt->bind_result($reputation_level);
    $reputation_stmt->fetch();
    $reputation_stmt->close();
}

// 获取筛选参数
$search_account = isset($_GET['search_account']) ? trim($_GET['search_account']) : '';
$filter_status = isset($_GET['filter_status']) ? $_GET['filter_status'] : 'all';

// 分页设置
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

// 获取订单总数
$count_sql = "SELECT COUNT(*) AS total FROM orders WHERE user_id = ?";
$count_params = array($user_id);
$count_types = "i";

if (!empty($search_account)) {
    $count_sql .= " AND account_info LIKE ?";
    $count_params[] = "%$search_account%";
    $count_types .= "s";
}

$count_stmt = $conn->prepare($count_sql);
if ($count_stmt === false) {
    die("SQL错误: " . $conn->error);
}

$bind_names = array();
$bind_names[] = &$count_types;
for ($i = 0; $i < count($count_params); $i++) {
    $bind_name = 'bind' . $i;
    $$bind_name = $count_params[$i];
    $bind_names[] = &$$bind_name;
}

call_user_func_array(array($count_stmt, 'bind_param'), $bind_names);
$count_stmt->execute();
$total_result = $count_stmt->get_result()->fetch_assoc();
$total_orders = $total_result['total'];
$total_pages = ceil($total_orders / $perPage);

// 获取所有订单数据用于统计未创建任务的数量（不限制分页）
$uncreated_count = 0;
$uncreated_sql = "SELECT account_info FROM orders WHERE user_id = ?";
$uncreated_params = array($user_id);
$uncreated_types = "i";

if (!empty($search_account)) {
    $uncreated_sql .= " AND account_info LIKE ?";
    $uncreated_params[] = "%$search_account%";
    $uncreated_types .= "s";
}

$uncreated_stmt = $conn->prepare($uncreated_sql);
if ($uncreated_stmt === false) {
    die("SQL错误: " . $conn->error);
}

$bind_names = array();
$bind_names[] = &$uncreated_types;
for ($i = 0; $i < count($uncreated_params); $i++) {
    $bind_name = 'bind' . $i;
    $$bind_name = $uncreated_params[$i];
    $bind_names[] = &$$bind_name;
}

call_user_func_array(array($uncreated_stmt, 'bind_param'), $bind_names);
$uncreated_stmt->execute();
$uncreated_result = $uncreated_stmt->get_result();

while ($order = $uncreated_result->fetch_assoc()) {
    // 检查是否是重复账号修复订单
    if ($order['account_info'] === '重复账号已清除' || $order['account_info'] === '重复账号已修复') {
        continue;
    }
    
    // 解析账号信息
    $accountInfo = $order['account_info'];
    $accountInfo = str_replace(array("\r\n", "\r"), "\n", $accountInfo);
    $accountLines = explode("\n", $accountInfo);
    
    $account = isset($accountLines[0]) ? trim($accountLines[0]) : '';
    $password = isset($accountLines[1]) ? trim($accountLines[1]) : '';
    
    if (empty($account) || empty($password)) {
        if (preg_match('/账号[:：]\s*(\S+).*密码[:：]\s*(\S+)/', $accountInfo, $matches)) {
            $account = isset($matches[1]) ? trim($matches[1]) : '';
            $password = isset($matches[2]) ? trim($matches[2]) : '';
        } elseif (preg_match('/账号\s+(\S+).*密码\s+(\S+)/', $accountInfo, $matches)) {
            $account = isset($matches[1]) ? trim($matches[1]) : '';
            $password = isset($matches[2]) ? trim($matches[2]) : '';
        }
    }
    
    // 查询任务状态（修改点：移除用户限制）
    if (!empty($account) && !empty($password)) {
        $task_stmt = $conn->prepare("
            SELECT status 
            FROM tasks 
            WHERE account = ? AND password = ? 
            ORDER BY created_at DESC 
            LIMIT 1
        ");
        $task_stmt->bind_param("ss", $account, $password);
        $task_stmt->execute();
        $task_result = $task_stmt->get_result();
        if ($task_row = $task_result->fetch_assoc()) {
            if ($task_row['status'] === '未创建') {
                $uncreated_count++;
            }
        } else {
            $uncreated_count++;
        }
    }
}

// 获取当前页的订单数据
$sql = "SELECT * FROM orders WHERE user_id = ?";
$params = array($user_id);
$types = "i";

if (!empty($search_account)) {
    $sql .= " AND account_info LIKE ?";
    $params[] = "%$search_account%";
    $types .= "s";
}

$sql .= " ORDER BY created_at DESC LIMIT ?, ?";
$params[] = $offset;
$params[] = $perPage;
$types .= "ii";

$stmt = $conn->prepare($sql);
if ($stmt === false) {
    die("SQL错误: " . $conn->error);
}

$bind_names = array();
$bind_names[] = &$types;
for ($i = 0; $i < count($params); $i++) {
    $bind_name = 'bind' . $i;
    $$bind_name = $params[$i];
    $bind_names[] = &$$bind_name;
}

call_user_func_array(array($stmt, 'bind_param'), $bind_names);
$stmt->execute();
$result = $stmt->get_result();

$orders = [];

// 修复点：检查结果集是否有效
if ($result) {
    while ($order = $result->fetch_assoc()) {
        // 检查是否是重复账号修复订单
        if ($order['account_info'] === '重复账号已清除' || $order['account_info'] === '重复账号已修复') {
            continue;
        }
        
        // 解析账号信息
        $accountInfo = $order['account_info'];
        $accountInfo = str_replace(array("\r\n", "\r"), "\n", $accountInfo);
        $accountLines = explode("\n", $accountInfo);
        
        $account = isset($accountLines[0]) ? trim($accountLines[0]) : '';
        $password = isset($accountLines[1]) ? trim($accountLines[1]) : '';
        
        if (empty($account) || empty($password)) {
            if (preg_match('/账号[:：]\s*(\S+).*密码[:：]\s*(\S+)/', $accountInfo, $matches)) {
                $account = isset($matches[1]) ? trim($matches[1]) : '';
                $password = isset($matches[2]) ? trim($matches[2]) : '';
            } elseif (preg_match('/账号\s+(\S+).*密码\s+(\S+)/', $accountInfo, $matches)) {
                $account = isset($matches[1]) ? trim($matches[1]) : '';
                $password = isset($matches[2]) ? trim($matches[2]) : '';
            }
        }
        
        // 查询任务状态 - 从tasks表获取
        $task_status = '未创建';
        if (!empty($account) && !empty($password)) {
            $task_stmt = $conn->prepare("
                SELECT status 
                FROM tasks 
                WHERE account = ? AND password = ? 
                ORDER BY created_at DESC 
                LIMIT 1
            ");
            $task_stmt->bind_param("ss", $account, $password);
            $task_stmt->execute();
            $task_result = $task_stmt->get_result();
            if ($task_row = $task_result->fetch_assoc()) {
                $task_status = $task_row['status'];
            }
        }
        
        // 获取产品名称
        $product_stmt = $conn->prepare("SELECT name FROM products WHERE id = ?");
        $product_stmt->bind_param("i", $order['product_id']);
        $product_stmt->execute();
        $product_result = $product_stmt->get_result();
        $product_name = $product_result->fetch_assoc()['name'] ?? '未知产品';
        
        // 添加到订单列表
        $orders[] = [
            'id' => $order['id'],
            'product_id' => $order['product_id'],
            'product_name' => $product_name,
            'points_spent' => $order['points_spent'],
            'account_info' => $order['account_info'],
            'created_at' => $order['created_at'],
            'task_status' => $task_status,
            'account' => $account, // 保存解析后的账号
            'password' => $password // 保存解析后的密码
        ];
    }
}

// 应用状态筛选
if ($filter_status !== 'all') {
    $orders = array_filter($orders, function($order) use ($filter_status) {
        return $order['task_status'] === $filter_status;
    });
    
    $total_orders = count($orders);
    $total_pages = ceil($total_orders / $perPage);
    $orders = array_slice($orders, $offset, $perPage);
}

// 根据信誉等级设置不同的限制
$max_uncreated = 3; // 默认限制

if ($reputation_level === '优质信誉') {
    $max_uncreated = 9999; // 优质信誉不受限制
} elseif ($reputation_level === '正常信誉') {
    $max_uncreated = 10; // 正常信誉限制10个
} elseif ($reputation_level === '略差信誉' || $reputation_level === '超差信誉') {
    $max_uncreated = 3; // 略差和超差信誉限制3个
}

// 更新session中的限制信息 - 修改点：根据信誉等级设置不同的限制
if ($uncreated_count >= $max_uncreated) {
    $_SESSION['purchase_blocked'] = true;
    $_SESSION['purchase_block_reason'] = "您有超过{$max_uncreated}个未提交任务的账号，请先提交任务后再购买新账号。";
} else {
    unset($_SESSION['purchase_blocked']);
    unset($_SESSION['purchase_block_reason']);
}
?>

<div class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4>我购买的账号</h4>
        <!-- 添加未创建任务数量提示 -->
        <div class="alert alert-warning mb-0">
            未提交任务的账号: <span class="badge bg-danger"><?= $uncreated_count ?></span> 个
            <?php if ($uncreated_count >= $max_uncreated): ?>
                <span class="ms-2 text-danger"><i class="fas fa-ban me-1"></i>已达上限 (<?= $reputation_level ?>用户限制<?= $max_uncreated ?>个)，无法购买新账号</span>
            <?php endif; ?>
        </div>
        <?php if (!$is_agent): ?>
        <a href="submit_task.php" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left"></i> 新键任务
        </a>
        <?php endif; ?>
    </div>
    
    <!-- 添加筛选表单 -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="get" class="row g-3">
                <div class="col-md-6">
                    <label for="search_account" class="form-label">账号查询</label>
                    <input type="text" class="form-control" id="search_account" name="search_account" 
                           placeholder="输入账号信息" value="<?= htmlspecialchars($search_account) ?>">
                </div>
                <div class="col-md-4">
                    <label for="filter_status" class="form-label">任务状态</label>
                    <select class="form-select" id="filter_status" name="filter_status">
                        <option value="all" <?= $filter_status === 'all' ? 'selected' : '' ?>>全部状态</option>
                        <option value="未创建" <?= $filter_status === '未创建' ? 'selected' : '' ?>>未创建</option>
                        <option value="pending" <?= $filter_status === 'pending' ? 'selected' : '' ?>>待审核</option>
                        <option value="approved" <?= $filter_status === 'approved' ? 'selected' : '' ?>>已通过</option>
                        <option value="rejected" <?= $filter_status === 'rejected' ? 'selected' : '' ?>>已拒绝</option>
                        <option value="recall_initiated" <?= $filter_status === 'recall_initiated' ? 'selected' : '' ?>>扣回中</option>
                        <option value="recall_completed" <?= $filter_status === 'recall_completed' ? 'selected' : '' ?>>已扣回</option>
                        <option value="self_consumed" <?= $filter_status === 'self_consumed' ? 'selected' : '' ?>>已自留</option>
                    </select>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter me-1"></i> 筛选
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <?php if (!empty($orders)): ?>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>订单号</th>
                        <th>商品名称</th>
                        <th>消耗积分</th>
                        <th>账号信息</th>
                        <th>任务状态</th>
                        <th>下单时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order): 
                        $accountInfo = $order['account_info'];
                        $accountInfo = str_replace(array("\r\n", "\r"), "\n", $accountInfo);
                        $accountLines = explode("\n", $accountInfo);
                        
                        $account = isset($accountLines[0]) ? trim($accountLines[0]) : '';
                        $password = isset($accountLines[1]) ? trim($accountLines[1]) : '';
                        
                        if (empty($account) || empty($password)) {
                            if (preg_match('/账号[:：]\s*(\S+).*密码[:：]\s*(\S+)/', $accountInfo, $matches)) {
                                $account = isset($matches[1]) ? trim($matches[1]) : '';
                                $password = isset($matches[2]) ? trim($matches[2]) : '';
                            } elseif (preg_match('/账号\s+(\S+).*密码\s+(\S+)/', $accountInfo, $matches)) {
                                $account = isset($matches[1]) ? trim($matches[1]) : '';
                                $password = isset($matches[2]) ? trim($matches[2]) : '';
                            }
                        }
                        
                        // 如果任务状态为已通过，隐藏密码显示
                        if ($order['task_status'] === 'approved') {
                            $displayAccountInfo = $account . "\n" . "密码：******";
                        } else {
                            $displayAccountInfo = $accountInfo;
                        }
                        
                        $taskStatus = $order['task_status'];
                        $statusClass = '';
                        $statusText = '';
                        
                        switch ($taskStatus) {
                            case 'pending':
                                $statusClass = 'status-pending';
                                $statusText = '待审核';
                                break;
                            case 'approved':
                                $statusClass = 'status-approved';
                                $statusText = '已通过';
                                break;
                            case 'rejected':
                                $statusClass = 'status-rejected';
                                $statusText = '已拒绝';
                                break;
                            case 'recall_initiated':
                                $statusClass = 'status-recall_initiated';
                                $statusText = '扣回中';
                                break;
                            case 'recall_completed':
                                $statusClass = 'status-recall_completed';
                                $statusText = '已扣回';
                                break;
                            case 'self_consumed':
                                $statusClass = 'status-self_consumed';
                                $statusText = '已自留';
                                break;
                            default:
                                $statusClass = 'status-default';
                                $statusText = $taskStatus;
                        }
                    ?>
                        <tr>
                            <td><?= $order['id'] ?></td>
                            <td><?= htmlspecialchars($order['product_name']) ?></td>
                            <td><?= $order['points_spent'] ?></td>
                            <td>
                                <?php if (!empty($displayAccountInfo)): ?>
                                    <div class="d-flex align-items-center">
                                        <span class="account-info-text"><?= nl2br(htmlspecialchars($displayAccountInfo)) ?></span>
                                        <button class="btn btn-sm btn-outline-secondary ms-2 copy-btn" 
                                                data-text="<?= htmlspecialchars($displayAccountInfo) ?>">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </div>
                                <?php else: ?>
                                    <span class="text-muted">无账号信息</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge <?= $statusClass ?>"><?= $statusText ?></span>
                            </td>
                            <td><?= date('Y-m-d H:i', strtotime($order['created_at'])) ?></td>
                            <td>
                                <?php if (!empty($account) && !empty($password) && !empty($order['product_name'])): ?>
                                    <?php if ($taskStatus === 'approved'): ?>
                                        <button class="btn btn-sm btn-secondary" disabled>
                                            <i class="fas fa-check-circle me-1"></i>已完结
                                        </button>
                                    <?php elseif ($taskStatus === 'rejected'): ?>
                                        <?php if (!$is_agent): ?>
                                            <div class="d-flex">
                                                <button class="btn btn-sm btn-danger submit-task-btn me-1" 
                                                        data-account="<?= htmlspecialchars($account) ?>" 
                                                        data-password="<?= htmlspecialchars($password) ?>" 
                                                        data-product="<?= htmlspecialchars($order['product_name']) ?>">
                                                    <i class="fas fa-redo me-1"></i>重新提交
                                                </button>
                                                <button class="btn btn-sm btn-teal self-consume-btn" 
                                                        data-order-id="<?= $order['id'] ?>"
                                                        data-account="<?= htmlspecialchars($account) ?>"
                                                        data-password="<?= htmlspecialchars($password) ?>">
                                                    <i class="fas fa-user-lock me-1"></i>自留账号
                                                </button>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted">代理用户不可操作</span>
                                        <?php endif; ?>
                                    <?php elseif ($taskStatus === 'recall_completed'): ?>
                                        <?php if (!$is_agent): ?>
                                            <div class="d-flex">
                                                <button class="btn btn-sm btn-purple submit-task-btn me-1" 
                                                        data-account="<?= htmlspecialchars($account) ?>" 
                                                        data-password="<?= htmlspecialchars($password) ?>" 
                                                        data-product="<?= htmlspecialchars($order['product_name']) ?>">
                                                    <i class="fas fa-redo me-1"></i>重新提交
                                                </button>
                                                <button class="btn btn-sm btn-teal self-consume-btn" 
                                                        data-order-id="<?= $order['id'] ?>"
                                                        data-account="<?= htmlspecialchars($account) ?>"
                                                        data-password="<?= htmlspecialchars($password) ?>">
                                                    <i class="fas fa-user-lock me-1"></i>自留账号
                                                </button>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted">代理用户不可操作</span>
                                        <?php endif; ?>
                                    <?php elseif ($taskStatus === 'self_consumed'): ?>
                                        <div class="d-flex">
                                            <button class="btn btn-sm btn-secondary me-1" disabled>
                                                <i class="fas fa-user-lock me-1"></i>已自留
                                            </button>
                                            <button class="btn btn-sm btn-info view-account-info-btn" 
                                                    data-order-id="<?= $order['id'] ?>"
                                                    data-account="<?= htmlspecialchars($account) ?>"
                                                    data-password="<?= htmlspecialchars($password) ?>">
                                                <i class="fas fa-eye me-1"></i>查看账号信息
                                            </button>
                                        </div>
                                    <?php elseif ($taskStatus === '未创建'): ?>
                                        <div class="d-flex">
                                            <?php if (!$is_agent): ?>
                                                <button class="btn btn-sm btn-primary submit-task-btn me-1" 
                                                        data-account="<?= htmlspecialchars($account) ?>" 
                                                        data-password="<?= htmlspecialchars($password) ?>" 
                                                        data-product="<?= htmlspecialchars($order['product_name']) ?>">
                                                    <i class="fas fa-paper-plane me-1"></i>去交单
                                                </button>
                                            <?php endif; ?>
                                            <button class="btn btn-sm btn-teal self-consume-btn" 
                                                    data-order-id="<?= $order['id'] ?>"
                                                    data-account="<?= htmlspecialchars($account) ?>"
                                                    data-password="<?= htmlspecialchars($password) ?>">
                                                <i class="fas fa-user-lock me-1"></i>自留账号
                                            </button>
                                        </div>
                                    <?php else: ?>
                                        <?php if (!$is_agent): ?>
                                            <div class="d-flex">
                                                <button class="btn btn-sm btn-primary submit-task-btn me-1" 
                                                        data-account="<?= htmlspecialchars($account) ?>" 
                                                        data-password="<?= htmlspecialchars($password) ?>" 
                                                        data-product="<?= htmlspecialchars($order['product_name']) ?>">
                                                    <i class="fas fa-paper-plane me-1"></i>去交单
                                                </button>
                                                <button class="btn btn-sm btn-teal self-consume-btn" 
                                                        data-order-id="<?= $order['id'] ?>"
                                                        data-account="<?= htmlspecialchars($account) ?>"
                                                        data-password="<?= htmlspecialchars($password) ?>">
                                                    <i class="fas fa-user-lock me-1"></i>自留账号
                                                </button>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted">代理用户不可操作</span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <button class="btn btn-sm btn-secondary" disabled>
                                        <i class="fas fa-ban me-1"></i>不可操作
                                    </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total_pages > 1): ?>
            <nav>
                <ul class="pagination justify-content-center">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link pagination-link" href="?<?= 
                                http_build_query(array_merge(
                                    $_GET,
                                    ['page' => $page - 1]
                                )) 
                            ?>">上一页</a>
                        </li>
                    <?php endif; ?>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                            <a class="page-link pagination-link" href="?<?= 
                                http_build_query(array_merge(
                                    $_GET,
                                    ['page' => $i]
                                )) 
                            ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link pagination-link" href="?<?= 
                                http_build_query(array_merge(
                                    $_GET,
                                    ['page' => $page + 1]
                                )) 
                            ?>">下一页</a>
                        </li>
                    <?php endif; ?>
                </ul>
            </nav>
        <?php endif; ?>
    <?php else: ?>
        <div class="alert alert-info">
            <i class="fas fa-info-circle"></i> 暂无订单记录
        </div>
    <?php endif; ?>
</div>

<!-- 分页加载动画弹窗 -->
<div class="modal fade" id="paginationLoadingModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="background: transparent; border: none; box-shadow: none;">
            <div class="modal-body text-center">
                <div class="loading-spinner mb-3">
                    <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
                <h5 class="text-white">正在加载数据...</h5>
                <p class="text-light mb-0">请稍候，系统正在处理您的请求</p>
            </div>
        </div>
    </div>
</div>

<!-- 确认弹窗 -->
<div class="modal fade" id="confirmSubmitModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-warning"><i class="fas fa-exclamation-triangle me-2"></i>警告</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确保账号没有错误，如错误，可能导致不回收或亏损问题</p>
                <div class="account-info-preview p-3 bg-light rounded mt-3">
                    <h6>账号信息预览：</h6>
                    <div id="previewAccount"></div>
                    <div id="previewPassword" class="mt-1"></div>
                    <div id="previewProduct" class="mt-1"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">再看看</button>
                <button type="button" class="btn btn-primary" id="confirmSubmitBtn">确保没错</button>
            </div>
        </div>
    </div>
</div>

<!-- 自留账号验证弹窗 -->
<div class="modal fade" id="verifySelfConsumeModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-warning"><i class="fas fa-user-lock me-2"></i>自留账号验证</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>请输入该账号的密码以验证并标记为自留账号：</p>
                <div class="mb-3">
                    <label for="verifyAccount" class="form-label">账号</label>
                    <input type="text" class="form-control" id="verifyAccount" readonly>
                </div>
                <div class="mb-3">
                    <label for="verifyPassword" class="form-label">密码</label>
                    <input type="password" class="form-control" id="verifyPassword" placeholder="请输入密码">
                </div>
                <input type="hidden" id="verifyOrderId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmVerifyBtn">验证并标记</button>
            </div>
        </div>
    </div>
</div>

<!-- 账号信息展示弹窗 -->
<div class="modal fade" id="accountInfoModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-success"><i class="fas fa-info-circle me-2"></i>Steam账号完整信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-success">
                    <i class="fas fa-check-circle me-2"></i>验证成功！该账号已标记为自留账号
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="card mb-3">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0"><i class="fas fa-user me-2"></i>账号信息</h6>
                            </div>
                            <div class="card-body">
                                <p><strong>账号:</strong> <span id="modalAccount"></span></p>
                                <p><strong>账号密码:</strong> <span id="modalAccountPassword"></span></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card mb-3">
                            <div class="card-header bg-info text-white">
                                <h6 class="mb-0"><i class="fas fa-envelope me-2"></i>邮箱信息</h6>
                            </div>
                            <div class="card-body">
                                <p><strong>邮箱账号:</strong> <span id="modalEmailAccount"></span></p>
                                <p><strong>邮箱密码:</strong> <span id="modalEmailPassword"></span></p>
                                <p><strong>邮箱地址:</strong> <span id="modalEmailAddress"></span></p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card">
                    <div class="card-header bg-warning text-dark">
                        <h6 class="mb-0"><i class="fas fa-money-bill me-2"></i>支出信息</h6>
                    </div>
                    <div class="card-body">
                        <p><strong>支出状态:</strong> <span class="badge bg-success" id="modalExpenditure">用户自留账号</span></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" data-bs-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>

<style>
.status-badge {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 0.85rem;
    font-weight: 500;
    text-align: center;
    min-width: 70px;
}

.status-pending {
    background-color: #ffc107;
    color: #000;
}

.status-approved {
    background-color: #28a745;
    color: #fff;
}

.status-rejected {
    background-color: #dc3545;
    color: #fff;
}

.status-recall_initiated {
    background-color: #ff9800;
    color: #fff;
}

.status-recall_completed {
    background-color: #9c27b0;
    color: #fff;
}

.status-self_consumed {
    background-color: #20c997;
    color: #fff;
}

.status-default {
    background-color: #6c757d;
    color: #fff;
}

.btn-purple {
    background-color: #6f42c1;
    border-color: #6f42c1;
    color: white;
}

.btn-purple:hover {
    background-color: #5a32a3;
    border-color: #5a32a3;
    color: white;
}

.btn-teal {
    background-color: #20c997;
    border-color: #20c997;
    color: white;
}

.btn-teal:hover {
    background-color: #199d76;
    border-color: #199d76;
    color: white;
}

/* 分页加载动画样式 */
#paginationLoadingModal .modal-content {
    background: rgba(0, 0, 0, 0.8) !important;
    border-radius: 15px;
    backdrop-filter: blur(10px);
}

#paginationLoadingModal .loading-spinner {
    animation: pulse 1.5s infinite;
}

@keyframes pulse {
    0% {
        transform: scale(1);
        opacity: 1;
    }
    50% {
        transform: scale(1.05);
        opacity: 0.8;
    }
    100% {
        transform: scale(1);
        opacity: 1;
    }
}

/* 平滑过渡效果 */
.main-content {
    transition: opacity 0.3s ease;
}

.main-content.fade-out {
    opacity: 0.7;
}

/* 分页链接样式 */
.pagination-link {
    transition: all 0.2s ease;
}

.pagination-link:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化确认弹窗相关变量
    let currentSubmitUrl = '';
    const confirmModal = new bootstrap.Modal(document.getElementById('confirmSubmitModal'));
    const verifyModal = new bootstrap.Modal(document.getElementById('verifySelfConsumeModal'));
    const accountInfoModal = new bootstrap.Modal(document.getElementById('accountInfoModal'));
    const paginationLoadingModal = new bootstrap.Modal(document.getElementById('paginationLoadingModal'));
    
    // 为所有分页链接添加点击事件
    document.querySelectorAll('.pagination-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const href = this.getAttribute('href');
            
            // 显示加载动画
            paginationLoadingModal.show();
            
            // 添加页面淡出效果
            document.querySelector('.main-content').classList.add('fade-out');
            
            // 延迟跳转以确保动画显示
            setTimeout(() => {
                window.location.href = href;
            }, 500);
        });
    });
    
    // 为筛选表单添加提交事件
    document.querySelector('form[method="get"]').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 显示加载动画
        paginationLoadingModal.show();
        
        // 添加页面淡出效果
        document.querySelector('.main-content').classList.add('fade-out');
        
        // 延迟提交以确保动画显示
        setTimeout(() => {
            this.submit();
        }, 500);
    });
    
    // 为所有提交任务按钮添加点击事件
    document.querySelectorAll('.submit-task-btn').forEach(button => {
        button.addEventListener('click', function() {
            const account = this.getAttribute('data-account');
            const password = this.getAttribute('data-password');
            const productName = this.getAttribute('data-product');
            
            // 构建跳转URL
            const params = new URLSearchParams();
            params.append('account', account);
            params.append('password', password);
            params.append('product_name', productName);
            currentSubmitUrl = '<?= BASE_URL ?>submit_task.php?' + params.toString();
            
            // 更新弹窗中的预览信息
            document.getElementById('previewAccount').innerHTML = `<strong>账号:</strong> ${account}`;
            document.getElementById('previewPassword').innerHTML = `<strong>密码:</strong> ${password}`;
            document.getElementById('previewProduct').innerHTML = `<strong>产品:</strong> ${productName}`;
            
            // 显示确认弹窗
            confirmModal.show();
        });
    });
    
    // 确认提交按钮点击事件
    document.getElementById('confirmSubmitBtn').addEventListener('click', function() {
        // 跳转到提交任务页面
        window.location.href = currentSubmitUrl;
    });
    
    // 复制按钮功能
    document.querySelectorAll('.copy-btn').forEach(button => {
        button.addEventListener('click', function() {
            const text = this.getAttribute('data-text');
            const originalHtml = this.innerHTML;
            
            const textarea = document.createElement('textarea');
            textarea.value = text;
            textarea.style.position = 'fixed';
            textarea.style.top = 0;
            textarea.style.left = 0;
            textarea.style.opacity = 0;
            document.body.appendChild(textarea);
            
            textarea.select();
            try {
                const success = document.execCommand('copy');
                if (success) {
                    this.innerHTML = '<i class="fas fa-check"></i>';
                    setTimeout(() => {
                        this.innerHTML = originalHtml;
                    }, 2000);
                }
            } catch (err) {
                console.error('复制失败:', err);
            } finally {
                document.body.removeChild(textarea);
            }
        });
    });
    
    // 自留账号按钮处理
    document.querySelectorAll('.self-consume-btn').forEach(button => {
        button.addEventListener('click', function() {
            const orderId = this.getAttribute('data-order-id');
            const account = this.getAttribute('data-account');
            const password = this.getAttribute('data-password');

            // 存储到全局变量，或者直接设置到模态框的字段中
            document.getElementById('verifyOrderId').value = orderId;
            document.getElementById('verifyAccount').value = account;
            document.getElementById('verifyPassword').value = ''; // 清空密码输入框

            // 显示验证模态框
            verifyModal.show();
        });
    });
    
    // 查看账号信息按钮处理
    document.querySelectorAll('.view-account-info-btn').forEach(button => {
        button.addEventListener('click', function() {
            const orderId = this.getAttribute('data-order-id');
            const account = this.getAttribute('data-account');
            const password = this.getAttribute('data-password');

            // 显示加载状态
            const viewBtn = this;
            const originalText = viewBtn.innerHTML;
            viewBtn.disabled = true;
            viewBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>加载中...';

            // 发送AJAX请求获取账号信息
            fetch('get_account_info.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'order_id=' + orderId + '&account=' + encodeURIComponent(account) + '&password=' + encodeURIComponent(password)
            })
            .then(response => response.text())
            .then(text => {
                // 恢复按钮状态
                viewBtn.disabled = false;
                viewBtn.innerHTML = originalText;
                
                try {
                    const data = JSON.parse(text);
                    
                    if (data.success) {
                        // 填充账号信息到展示模态框
                        document.getElementById('modalAccount').textContent = data.account_info.account || '无';
                        document.getElementById('modalAccountPassword').textContent = data.account_info.account_password || '无';
                        document.getElementById('modalEmailAccount').textContent = data.account_info.email_account || '无';
                        document.getElementById('modalEmailPassword').textContent = data.account_info.email_password || '无';
                        document.getElementById('modalEmailAddress').textContent = data.account_info.email_address || '无';
                        
                        // 显示账号信息模态框
                        accountInfoModal.show();
                    } else {
                        alert('获取账号信息失败: ' + (data.message || '未知错误'));
                    }
                } catch (e) {
                    console.error('JSON解析错误:', e);
                    console.error('服务器返回的内容:', text);
                    alert('服务器返回了无效的数据格式，请检查控制台查看详情。');
                }
            })
            .catch(error => {
                // 恢复按钮状态
                viewBtn.disabled = false;
                viewBtn.innerHTML = originalText;
                
                console.error('请求失败:', error);
                alert('网络错误，请检查网络连接或联系管理员。');
            });
        });
    });
    
    // 验证并标记按钮点击事件
    document.getElementById('confirmVerifyBtn').addEventListener('click', function() {
        const orderId = document.getElementById('verifyOrderId').value;
        const account = document.getElementById('verifyAccount').value;
        const password = document.getElementById('verifyPassword').value;

        if (!password) {
            alert('请输入密码！');
            return;
        }

        // 显示加载状态
        const verifyBtn = document.getElementById('confirmVerifyBtn');
        const originalText = verifyBtn.innerHTML;
        verifyBtn.disabled = true;
        verifyBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>验证中...';

        // 发送AJAX请求验证密码并获取账号信息
        fetch('verify_and_mark_self_consumed.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'order_id=' + orderId + '&account=' + encodeURIComponent(account) + '&password=' + encodeURIComponent(password)
        })
        .then(response => response.text())
        .then(text => {
            // 恢复按钮状态
            verifyBtn.disabled = false;
            verifyBtn.innerHTML = originalText;
            
            try {
                const data = JSON.parse(text);
                
                if (data.success) {
                    // 成功，关闭验证模态框
                    verifyModal.hide();
                    
                    // 填充账号信息到展示模态框
                    document.getElementById('modalAccount').textContent = data.account_info.account || '无';
                    document.getElementById('modalAccountPassword').textContent = data.account_info.account_password || '无';
                    document.getElementById('modalEmailAccount').textContent = data.account_info.email_account || '无';
                    document.getElementById('modalEmailPassword').textContent = data.account_info.email_password || '无';
                    document.getElementById('modalEmailAddress').textContent = data.account_info.email_address || '无';
                    
                    // 显示账号信息模态框
                    accountInfoModal.show();
                    
                    // 更新页面上的状态
                    const buttonContainer = document.querySelector('.self-consume-btn[data-order-id="' + orderId + '"]').closest('td');
                    const statusBadge = buttonContainer.closest('tr').querySelector('.status-badge');
                    statusBadge.textContent = '已自留';
                    statusBadge.className = 'status-badge status-self_consumed';
                    
                    // 更新操作按钮为查看账号信息按钮
                    buttonContainer.innerHTML = `
                        <div class="d-flex">
                            <button class="btn btn-sm btn-secondary me-1" disabled>
                                <i class="fas fa-user-lock me-1"></i>已自留
                            </button>
                            <button class="btn btn-sm btn-info view-account-info-btn" 
                                    data-order-id="${orderId}"
                                    data-account="${account}"
                                    data-password="${password}">
                                <i class="fas fa-eye me-1"></i>查看账号信息
                            </button>
                        </div>
                    `;
                    
                    // 重新绑定查看账号信息按钮的事件
                    document.querySelectorAll('.view-account-info-btn').forEach(button => {
                        button.addEventListener('click', function() {
                            const orderId = this.getAttribute('data-order-id');
                            const account = this.getAttribute('data-account');
                            const password = this.getAttribute('data-password');

                            // 显示加载状态
                            const viewBtn = this;
                            const originalText = viewBtn.innerHTML;
                            viewBtn.disabled = true;
                            viewBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>加载中...';

                            // 发送AJAX请求获取账号信息
                            fetch('get_account_info.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded'
                                },
                                body: 'order_id=' + orderId + '&account=' + encodeURIComponent(account) + '&password=' + encodeURIComponent(password)
                            })
                            .then(response => response.text())
                            .then(text => {
                                // 恢复按钮状态
                                viewBtn.disabled = false;
                                viewBtn.innerHTML = originalText;
                                
                                try {
                                    const data = JSON.parse(text);
                                    
                                    if (data.success) {
                                        // 填充账号信息到展示模态框
                                        document.getElementById('modalAccount').textContent = data.account_info.account || '无';
                                        document.getElementById('modalAccountPassword').textContent = data.account_info.account_password || '无';
                                        document.getElementById('modalEmailAccount').textContent = data.account_info.email_account || '无';
                                        document.getElementById('modalEmailPassword').textContent = data.account_info.email_password || '无';
                                        document.getElementById('modalEmailAddress').textContent = data.account_info.email_address || '无';
                                        
                                        // 显示账号信息模态框
                                        accountInfoModal.show();
                                    } else {
                                        alert('获取账号信息失败: ' + (data.message || '未知错误'));
                                    }
                                } catch (e) {
                                    console.error('JSON解析错误:', e);
                                    console.error('服务器返回的内容:', text);
                                    alert('服务器返回了无效的数据格式，请检查控制台查看详情。');
                                }
                            })
                            .catch(error => {
                                // 恢复按钮状态
                                viewBtn.disabled = false;
                                viewBtn.innerHTML = originalText;
                                
                                console.error('请求失败:', error);
                                alert('网络错误，请检查网络连接或联系管理员。');
                            });
                        });
                    });
                } else {
                    alert('验证失败: ' + (data.message || '未知错误'));
                }
            } catch (e) {
                console.error('JSON解析错误:', e);
                console.error('服务器返回的内容:', text);
                alert('服务器返回了无效的数据格式，请检查控制台查看详情。');
            }
        })
        .catch(error => {
            // 恢复按钮状态
            verifyBtn.disabled = false;
            verifyBtn.innerHTML = originalText;
            
            console.error('请求失败:', error);
            alert('网络错误，请检查网络连接或联系管理员。');
        });
    });
});
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>