page.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. 'use client';
  2. import { useState, useEffect } from 'react';
  3. import { Plus, Search, RefreshCw, X, Lock } from 'lucide-react';
  4. import api from '@/lib/api';
  5. import { toast } from 'react-hot-toast';
  6. // 引入拆分后的组件
  7. import AccountTable, { Account } from '@/components/admin/accounts/AccountTable';
  8. import Pagination from '@/components/common/Pagination';
  9. export default function AdminAccountsPage() {
  10. // === 1. 状态定义 ===
  11. const [loading, setLoading] = useState<boolean>(true);
  12. const [data, setData] = useState<Account[]>([]);
  13. // 分页与搜索
  14. const [page, setPage] = useState(1); // 1-based UI
  15. const [pageSize] = useState(10);
  16. const [total, setTotal] = useState(0);
  17. const [keyword, setKeyword] = useState('');
  18. // 模态框状态
  19. const [showAddModal, setShowAddModal] = useState(false);
  20. const [showLockModal, setShowLockModal] = useState(false);
  21. const [selectedAccount, setSelectedAccount] = useState<Account | null>(null);
  22. // 表单状态
  23. const [addForm, setAddForm] = useState({
  24. pool_name: '',
  25. username: '',
  26. password: '',
  27. extra_data_str: '{}'
  28. });
  29. const [lockDuration, setLockDuration] = useState<number>(3600);
  30. // === 2. 数据获取 ===
  31. const fetchAccounts = async (targetPage: number = page) => {
  32. setLoading(true);
  33. try {
  34. // API 使用 0-based,前端使用 1-based
  35. // const apiPage = targetPage - 1;
  36. const res = await api.get('/api/account/list_all', {
  37. params: {
  38. page: targetPage,
  39. size: pageSize,
  40. keyword: keyword
  41. }
  42. });
  43. const resData = res.data?.data || {};
  44. if (resData && Array.isArray(resData.items)) {
  45. setData(resData.items);
  46. setTotal(resData.total || 0);
  47. } else {
  48. setData([]);
  49. setTotal(0);
  50. }
  51. setPage(targetPage);
  52. // 翻页滚动优化
  53. if (targetPage > 1) {
  54. window.scrollTo({ top: 0, behavior: 'smooth' });
  55. }
  56. } catch (error) {
  57. console.error("Fetch accounts failed", error);
  58. toast.error('获取列表失败');
  59. setData([]);
  60. } finally {
  61. setLoading(false);
  62. }
  63. };
  64. useEffect(() => {
  65. fetchAccounts(1);
  66. // eslint-disable-next-line react-hooks/exhaustive-deps
  67. }, []);
  68. const handleSearch = () => fetchAccounts(1);
  69. const handleKeyDown = (e: React.KeyboardEvent) => {
  70. if (e.key === 'Enter') handleSearch();
  71. };
  72. // === 3. 业务逻辑 ===
  73. const handleAddAccount = async () => {
  74. try {
  75. let extraDataJson = {};
  76. try {
  77. extraDataJson = JSON.parse(addForm.extra_data_str);
  78. } catch (e) {
  79. toast.error('Extra Data 必须是 JSON 格式');
  80. return;
  81. }
  82. await api.post('/api/account/add', {
  83. pool_name: addForm.pool_name,
  84. username: addForm.username,
  85. password: addForm.password,
  86. extra_data: extraDataJson
  87. });
  88. toast.success('添加成功');
  89. setShowAddModal(false);
  90. setAddForm({ pool_name: '', username: '', password: '', extra_data_str: '{}' });
  91. fetchAccounts(1);
  92. } catch (error) {
  93. toast.error('添加失败');
  94. }
  95. };
  96. const handleLockConfirm = async () => {
  97. if (!selectedAccount) return;
  98. try {
  99. await api.post('/api/account/lock', {
  100. pool_name: selectedAccount.pool_name,
  101. username: selectedAccount.username,
  102. duration: Number(lockDuration)
  103. });
  104. toast.success('锁定成功');
  105. setShowLockModal(false);
  106. fetchAccounts(page); // 刷新当前页
  107. } catch (error) {
  108. toast.error('锁定失败');
  109. }
  110. };
  111. const handleDisable = async (account: Account) => {
  112. if (!confirm(`确定要禁用账号 ${account.username} 吗?`)) return;
  113. try {
  114. await api.post('/api/account/disable', {
  115. pool_name: account.pool_name,
  116. username: account.username
  117. });
  118. toast.success('禁用成功');
  119. fetchAccounts(page);
  120. } catch (error) {
  121. toast.error('禁用失败');
  122. }
  123. };
  124. return (
  125. <div className="p-4 md:p-6 space-y-6">
  126. {/* === 头部区域 === */}
  127. <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
  128. <div>
  129. <h1 className="text-2xl font-bold text-slate-800">账号池管理</h1>
  130. <p className="text-sm text-slate-500 mt-1">管理爬虫账号、查看锁定状态及禁用异常账号</p>
  131. </div>
  132. <div className="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
  133. {/* 搜索框 */}
  134. <div className="relative w-full sm:w-auto md:w-64">
  135. <input
  136. type="text"
  137. placeholder="搜索账号 / Pool..."
  138. className="w-full pl-9 pr-4 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none transition shadow-sm"
  139. value={keyword}
  140. onChange={e => setKeyword(e.target.value)}
  141. onKeyDown={handleKeyDown}
  142. />
  143. <Search size={16} className="absolute left-3 top-2.5 text-gray-400" />
  144. </div>
  145. {/* 刷新 */}
  146. <button
  147. onClick={() => fetchAccounts(page)}
  148. className="flex items-center justify-center gap-2 px-4 py-2 bg-white border border-slate-300 rounded-lg hover:bg-slate-50 text-slate-600 font-medium transition shadow-sm w-full sm:w-auto"
  149. title="刷新列表"
  150. >
  151. <RefreshCw size={16} />
  152. <span className="sm:hidden">刷新</span>
  153. </button>
  154. {/* 新增 */}
  155. <button
  156. onClick={() => setShowAddModal(true)}
  157. className="flex items-center justify-center gap-2 px-4 py-2 bg-slate-900 text-white rounded-lg text-sm font-medium hover:bg-slate-800 transition shadow-sm w-full sm:w-auto"
  158. >
  159. <Plus size={16} /> 新增
  160. </button>
  161. </div>
  162. </div>
  163. {/* === 表格组件 === */}
  164. <AccountTable
  165. data={data}
  166. loading={loading}
  167. onLock={(acc) => { setSelectedAccount(acc); setShowLockModal(true); }}
  168. onDisable={handleDisable}
  169. />
  170. {/* === 分页组件 === */}
  171. <div className="mt-4">
  172. <Pagination
  173. currentPage={page}
  174. total={total}
  175. pageSize={pageSize}
  176. onPageChange={fetchAccounts} // 传递函数,分页组件点击时回调
  177. />
  178. </div>
  179. {/* === Modals === */}
  180. {/* 新增 Modal */}
  181. {showAddModal && (
  182. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 animate-in fade-in zoom-in-95 duration-200">
  183. <div className="bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden">
  184. <div className="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
  185. <h3 className="font-bold text-lg text-slate-800">新增账号</h3>
  186. <button onClick={() => setShowAddModal(false)} className="text-slate-400 hover:text-slate-600">
  187. <X size={20} />
  188. </button>
  189. </div>
  190. <div className="p-6 space-y-4 max-h-[80vh] overflow-y-auto">
  191. <div>
  192. <label className="block text-xs font-bold uppercase text-slate-500 mb-1.5">Pool Name</label>
  193. <input type="text" className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none text-sm" value={addForm.pool_name} onChange={e => setAddForm({...addForm, pool_name: e.target.value})} />
  194. </div>
  195. <div>
  196. <label className="block text-xs font-bold uppercase text-slate-500 mb-1.5">Username</label>
  197. <input type="text" className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none text-sm" value={addForm.username} onChange={e => setAddForm({...addForm, username: e.target.value})} />
  198. </div>
  199. <div>
  200. <label className="block text-xs font-bold uppercase text-slate-500 mb-1.5">Password</label>
  201. <input type="text" className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none text-sm" value={addForm.password} onChange={e => setAddForm({...addForm, password: e.target.value})} />
  202. </div>
  203. <div>
  204. <label className="block text-xs font-bold uppercase text-slate-500 mb-1.5">Extra Data (JSON)</label>
  205. <textarea className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none font-mono text-xs bg-slate-50" rows={4} value={addForm.extra_data_str} onChange={e => setAddForm({...addForm, extra_data_str: e.target.value})} placeholder='{"country": "fr"}' />
  206. </div>
  207. </div>
  208. <div className="px-6 py-4 bg-slate-50 flex justify-end gap-3 border-t">
  209. <button onClick={() => setShowAddModal(false)} className="px-4 py-2 text-sm text-slate-600 hover:bg-slate-200 rounded-lg">取消</button>
  210. <button onClick={handleAddAccount} className="px-4 py-2 text-sm font-bold bg-slate-900 text-white rounded-lg hover:bg-slate-800">确认添加</button>
  211. </div>
  212. </div>
  213. </div>
  214. )}
  215. {/* 锁定 Modal */}
  216. {showLockModal && selectedAccount && (
  217. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 animate-in fade-in zoom-in-95 duration-200">
  218. <div className="bg-white rounded-xl shadow-2xl w-full max-w-sm overflow-hidden">
  219. <div className="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-orange-50/50">
  220. <h3 className="font-bold text-lg text-orange-900 flex items-center gap-2">
  221. <Lock size={18} /> 锁定账号
  222. </h3>
  223. <button onClick={() => setShowLockModal(false)} className="text-slate-400 hover:text-slate-600">
  224. <X size={20} />
  225. </button>
  226. </div>
  227. <div className="p-6 space-y-4">
  228. <p className="text-sm text-slate-600 bg-orange-50 p-3 rounded-lg border border-orange-100">
  229. 正在锁定: <span className="font-bold text-slate-900">{selectedAccount.username}</span>
  230. </p>
  231. <div>
  232. <label className="block text-xs font-bold uppercase text-slate-500 mb-1.5">持续时间 (秒)</label>
  233. <input type="number" min="0" className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500 outline-none font-mono" value={lockDuration} onChange={e => setLockDuration(Number(e.target.value))} />
  234. <div className="flex gap-2 mt-2">
  235. <button onClick={() => setLockDuration(3600)} className="flex-1 text-xs bg-slate-100 border px-2 py-1 rounded hover:bg-slate-200">1小时</button>
  236. <button onClick={() => setLockDuration(86400)} className="flex-1 text-xs bg-slate-100 border px-2 py-1 rounded hover:bg-slate-200">1天</button>
  237. </div>
  238. </div>
  239. </div>
  240. <div className="px-6 py-4 bg-slate-50 flex justify-end gap-3 border-t">
  241. <button onClick={() => setShowLockModal(false)} className="px-4 py-2 text-sm text-slate-600 hover:bg-slate-200 rounded-lg">取消</button>
  242. <button onClick={handleLockConfirm} className="px-4 py-2 text-sm font-bold bg-orange-600 text-white rounded-lg hover:bg-orange-700">确认锁定</button>
  243. </div>
  244. </div>
  245. </div>
  246. )}
  247. </div>
  248. );
  249. }