const express = require("express"); const router = express.Router(); const { executeQuery } = require("../config/database"); // 列表:支持按 account 和 status 查询,分页 router.get("/", async (req, res) => { try { const { page = 1, pageSize = 10, account, status } = req.query; const offset = (page - 1) * pageSize; let whereConditions = []; let sqlParams = []; let countParams = []; if (account) { whereConditions.push("account LIKE ?"); sqlParams.push(`%${account}%`); countParams.push(`%${account}%`); } if (status !== undefined && status !== "") { whereConditions.push("status = ?"); const statusVal = parseInt(status); sqlParams.push(statusVal); countParams.push(statusVal); } const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : ""; const sql = ` SELECT id, hostname, account, info, status, create_time, update_time FROM chrome_login_data ${whereClause} ORDER BY create_time DESC LIMIT ? OFFSET ? `; const countSql = `SELECT COUNT(*) as total FROM chrome_login_data ${whereClause}`; sqlParams.push(parseInt(pageSize), offset); const [data, countResult] = await Promise.all([ executeQuery(sql, sqlParams), executeQuery(countSql, countParams), ]); res.json({ data, total: countResult[0]?.total || 0, page: parseInt(page), pageSize: parseInt(pageSize), }); } catch (error) { console.error("Error fetching accounts:", error); res.status(500).json({ error: "Internal server error" }); } }); // 详情 router.get("/:id", async (req, res) => { try { const { id } = req.params; const sql = ` SELECT id, hostname, account, info, status, create_time, update_time FROM chrome_login_data WHERE id = ? `; const rows = await executeQuery(sql, [id]); if (!rows || rows.length === 0) { return res.status(404).json({ error: "Account not found" }); } res.json(rows[0]); } catch (error) { console.error("Error fetching account detail:", error); res.status(500).json({ error: "Internal server error" }); } }); // 编辑更新 router.put("/:id", async (req, res) => { try { const { id } = req.params; const { hostname, account, info, status } = req.body; const sql = ` UPDATE chrome_login_data SET hostname = ?, account = ?, info = ?, status = ?, update_time = NOW() WHERE id = ? `; const params = [ hostname ?? null, account ?? null, info ?? null, status ?? null, id, ]; await executeQuery(sql, params); res.json({ message: "Account updated successfully" }); } catch (error) { console.error("Error updating account:", error); res.status(500).json({ error: "Internal server error" }); } }); module.exports = router;