From d77c317452dcdc8c340b6a5cff362e0232fa3264 Mon Sep 17 00:00:00 2001 From: Christ Date: Wed, 22 Jul 2026 12:51:37 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AF=B9=E9=BD=90=E9=97=B2=E9=B1=BC?= =?UTF-8?q?=E7=BB=AD=E6=9C=9F=E6=B5=81=E7=A8=8B=E5=B9=B6=E5=AE=8C=E5=96=84?= =?UTF-8?q?=E4=B8=9A=E5=8A=A1=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对齐官方 WebSocket 批量握手、注册、心跳、ACK、同步恢复及运行时设备标识生命周期。 保留 Cookie 完整属性,接入静默续期和保存登录信息设置,并在凭证更新后重建账号连接。 完善订单与商品同步、卡券和通知渠道交互,更新前端品牌、时间展示及嵌入资源。 补充 Go 与前端回归测试,确保完整检查和生产构建通过。 --- frontend/App.tsx | 9 +- frontend/components/AccountList.tsx | 42 +- frontend/components/CardList.tsx | 108 ++- frontend/components/Dashboard.tsx | 3 +- frontend/components/ItemList.tsx | 95 ++- frontend/components/Notifications.tsx | 177 ++++- frontend/components/OrderList.tsx | 77 ++- frontend/components/Rules.tsx | 2 +- frontend/components/Sidebar.tsx | 5 +- frontend/components/YdisksLogo.test.tsx | 21 + frontend/components/YdisksLogo.tsx | 43 ++ frontend/components/cardListState.test.ts | 19 + frontend/components/cardListState.ts | 13 + frontend/dateTime.test.ts | 13 + frontend/dateTime.ts | 19 + frontend/notificationEmailConfig.test.ts | 36 + frontend/notificationEmailConfig.ts | 59 ++ frontend/routing.test.ts | 5 +- frontend/services/api.test.ts | 12 + frontend/services/api.ts | 17 +- internal/account/manager_extra_test.go | 28 + internal/adapter/adapter_test.go | 2 +- internal/browser/cookierenew.go | 52 +- internal/db/account_tokens.go | 20 +- internal/db/account_tokens_test.go | 14 +- internal/db/orders.go | 4 + internal/engine/account.go | 313 +++++---- internal/engine/account_extra_test.go | 8 +- internal/engine/ai.go | 5 + internal/engine/ai_test.go | 24 +- internal/engine/keepalive_test.go | 34 +- internal/engine/run_test.go | 120 +++- internal/notify/notifier.go | 39 +- internal/notify/notifier_channels_test.go | 27 + internal/renewal/scheduler.go | 48 +- internal/renewal/scheduler_test.go | 2 +- internal/server/automation_handlers.go | 4 +- internal/server/card_batch_handlers.go | 4 +- internal/server/card_handlers.go | 4 +- internal/server/cookie_handlers.go | 72 ++ internal/server/cookie_handlers_test.go | 60 ++ internal/server/handler_errors_test.go | 2 +- internal/server/item_handlers.go | 44 ++ internal/server/item_handlers_test.go | 60 ++ .../server/item_publish_batch_handlers.go | 10 +- internal/server/order_handlers.go | 152 ++++- internal/server/order_handlers_extra_test.go | 37 +- internal/server/publish_batch_test.go | 21 + internal/server/server.go | 3 + ...r-BhUPp6x7.js => icons-vendor-RenKjhri.js} | 142 ++-- .../webui/static/assets/index-2Xnmtmdh.js | 19 - .../webui/static/assets/index-D0gOrWMZ.css | 1 - .../webui/static/assets/index-DWScSBc3.js | 19 + .../webui/static/assets/index-hVsGsb1z.css | 1 + internal/webui/static/index.html | 6 +- internal/xianyu/cookierefresh/cookies.go | 183 +++++ internal/xianyu/cookierefresh/cookies_test.go | 43 +- internal/xianyu/mtop/client.go | 28 +- internal/xianyu/mtop/item_detail.go | 139 ++++ internal/xianyu/mtop/item_detail_test.go | 58 ++ internal/xianyu/mtop/items.go | 1 + internal/xianyu/mtop/sold_orders.go | 240 +++++++ internal/xianyu/mtop/sold_orders_test.go | 81 +++ internal/xianyu/renew/service.go | 202 ++++-- internal/xianyu/renew/service_test.go | 74 +- internal/xianyu/ws/client.go | 632 +++++++++++------- internal/xianyu/ws/client_test.go | 31 +- internal/xianyu/ws/dial_test.go | 94 ++- internal/xianyu/ws/receive_loop_test.go | 6 +- 69 files changed, 3169 insertions(+), 819 deletions(-) create mode 100644 frontend/components/YdisksLogo.test.tsx create mode 100644 frontend/components/YdisksLogo.tsx create mode 100644 frontend/components/cardListState.test.ts create mode 100644 frontend/components/cardListState.ts create mode 100644 frontend/dateTime.test.ts create mode 100644 frontend/dateTime.ts create mode 100644 frontend/notificationEmailConfig.test.ts create mode 100644 frontend/notificationEmailConfig.ts rename internal/webui/static/assets/{icons-vendor-BhUPp6x7.js => icons-vendor-RenKjhri.js} (72%) delete mode 100644 internal/webui/static/assets/index-2Xnmtmdh.js delete mode 100644 internal/webui/static/assets/index-D0gOrWMZ.css create mode 100644 internal/webui/static/assets/index-DWScSBc3.js create mode 100644 internal/webui/static/assets/index-hVsGsb1z.css create mode 100644 internal/xianyu/mtop/item_detail.go create mode 100644 internal/xianyu/mtop/item_detail_test.go create mode 100644 internal/xianyu/mtop/sold_orders.go create mode 100644 internal/xianyu/mtop/sold_orders_test.go diff --git a/frontend/App.tsx b/frontend/App.tsx index 19fcc43..ba7cd10 100644 --- a/frontend/App.tsx +++ b/frontend/App.tsx @@ -8,6 +8,7 @@ import ItemList from './components/ItemList'; import Settings from './components/Settings'; import Rules from './components/Rules'; import Notifications from './components/Notifications'; +import { YdisksBrandIcon } from './components/YdisksLogo'; import { login, logout, verifySession } from './services/api'; import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react'; @@ -157,8 +158,8 @@ const App: React.FC = () => {
-
- Ydisks +
+

系统尚未初始化

为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。

@@ -202,8 +203,8 @@ const App: React.FC = () => { {/* Header with Logo */}
-
- Ydisks +
+

欢迎回来

Ydisks闲鱼助手 · 自动发货与管家系统

diff --git a/frontend/components/AccountList.tsx b/frontend/components/AccountList.tsx index fd95e19..3348beb 100644 --- a/frontend/components/AccountList.tsx +++ b/frontend/components/AccountList.tsx @@ -20,6 +20,8 @@ import { getAccountAISettings, getNotificationChannels, getAccountBindings, + getLongLoginSettings, + setLongLoginSettings, } from '../services/api'; import { shouldUpdateAccountPause } from './accountPause'; import { @@ -49,6 +51,7 @@ const AccountList: React.FC = () => { const [qrReauthTarget, setQrReauthTarget] = useState(null); const [activeModal, setActiveModal] = useState(null); const [editingAccount, setEditingAccount] = useState(null); + const [longLogin, setLongLogin] = useState({ loading: false, saving: false, canOpen: false, enabled: false, error: '' }); // 通知渠道绑定(编辑弹窗用) const [notifChannels, setNotifChannels] = useState([]); @@ -328,7 +331,28 @@ const AccountList: React.FC = () => { clear_password: false, }); setActiveModal('edit'); - await loadNotificationBindings(account.id); + setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' }); + const [, longLoginResult] = await Promise.allSettled([ + loadNotificationBindings(account.id), + getLongLoginSettings(account.id), + ]); + if (longLoginResult.status === 'fulfilled') { + setLongLogin({ loading: false, saving: false, canOpen: longLoginResult.value.can_open_long_login, enabled: longLoginResult.value.enabled, error: '' }); + } else { + setLongLogin({ loading: false, saving: false, canOpen: false, enabled: false, error: '无法读取闲鱼保存登录信息状态' }); + } + }; + + const handleLongLoginToggle = async () => { + if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return; + const enabled = !longLogin.enabled; + setLongLogin(current => ({ ...current, saving: true, error: '' })); + try { + const result = await setLongLoginSettings(editingAccount.id, enabled); + setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' }); + } catch (error) { + setLongLogin(current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' })); + } }; const openAIModal = async (account: AccountDetail) => { @@ -966,6 +990,22 @@ const AccountList: React.FC = () => { 登录信息
+
+
+
保存登录信息
+
状态直接读取并修改闲鱼官方长登录设置
+ {longLogin.error &&
{longLogin.error}
} +
+ +
{ const [appendTargetId, setAppendTargetId] = useState(''); const [appendContent, setAppendContent] = useState(''); const [appendResult, setAppendResult] = useState<{ added: number } | null>(null); + const [typeFilter, setTypeFilter] = useState(''); + const [nameSearch, setNameSearch] = useState(''); useEffect(() => { getCards().then(setCards); @@ -213,6 +216,10 @@ const CardList: React.FC = () => { }; const dataCards = cards.filter(c => c.type === 'data'); + const filteredCards = useMemo( + () => filterCards(cards, typeFilter, nameSearch), + [cards, nameSearch, typeFilter], + ); const downloadCardTemplate = () => { const headers = ['名称', '类型', '内容', '描述', '启用', '延迟秒', '多规格', '规格名', '规格值']; @@ -306,28 +313,61 @@ const CardList: React.FC = () => {
+
+
+
+ + +
+
+ + setNameSearch(event.target.value)} + className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm" + /> +
+
+
+ 显示 {filteredCards.length} / {cards.length} 组 +
+
- +
- - - - - - - + + + + + + + - {cards.map((card) => { + {filteredCards.map((card) => { // 计算库存或内容预览 let stockInfo = ''; if (card.type === 'data' && card.data_content) { const lines = card.data_content.split('\n').filter(line => line.trim()); stockInfo = `库存: ${lines.length} 条`; } else if (card.type === 'text' && card.text_content) { - stockInfo = card.text_content.substring(0, 20) + (card.text_content.length > 20 ? '...' : ''); + stockInfo = card.text_content; } else if (card.type === 'api' && card.api_config) { stockInfo = card.api_config.url; } else if (card.type === 'image' && card.image_url) { @@ -336,26 +376,26 @@ const CardList: React.FC = () => { return ( - - - - - - - @@ -415,10 +455,10 @@ const CardList: React.FC = () => {
卡密名称卡密组ID类型内容/库存描述状态操作卡密名称卡密组ID类型内容/库存描述状态操作
-
-
+
+
+
- {card.name} + {card.name}
+ - + { card.type === 'api' ? 'API' : '图片'} - + + {stockInfo} + {card.description || '-'} + -
+
+
- {cards.length === 0 && ( + {filteredCards.length === 0 && (
-

暂无卡密配置,请点击右上角添加。

+

{cards.length === 0 ? '暂无卡密配置,请点击右上角添加。' : '没有符合当前筛选条件的卡密组。'}

)}
diff --git a/frontend/components/Dashboard.tsx b/frontend/components/Dashboard.tsx index c73cc5e..ee09244 100644 --- a/frontend/components/Dashboard.tsx +++ b/frontend/components/Dashboard.tsx @@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from 'react'; import { DashboardStats, OrderAnalytics, Order, OrderStatus, Item } from '../types'; import { getDashboardStats, getOrderAnalytics, getValidOrders, getItems } from '../services/api'; import { getDateRange, getPreviousDateRange, TimeRange } from '../dateRange'; +import { formatLocalDateTime } from '../dateTime'; import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react'; import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Legend } from 'recharts'; @@ -588,7 +589,7 @@ const Dashboard: React.FC = () => {
{order.buyer_id}
{order.created_at && ( -
{order.created_at}
+
{formatLocalDateTime(order.created_at)}
)} diff --git a/frontend/components/ItemList.tsx b/frontend/components/ItemList.tsx index b405ed8..306937d 100644 --- a/frontend/components/ItemList.tsx +++ b/frontend/components/ItemList.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useRef, useState } from 'react'; +import React, { useEffect, useMemo, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { selectActivePublishBatch } from './itemPublishBatchState'; import { Item, AccountDetail, ShippingRule } from '../types'; @@ -19,7 +19,7 @@ import { deleteItem, getShippingRules } from '../services/api'; -import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, X } from 'lucide-react'; +import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react'; interface ItemListProps { onConfigureDelivery: (item: Item) => void; @@ -77,6 +77,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => { const [shippingRules, setShippingRules] = useState([]); const [accounts, setAccounts] = useState([]); const [selectedAccount, setSelectedAccount] = useState(''); + const [accountFilter, setAccountFilter] = useState(''); const [loading, setLoading] = useState(false); const [publishing, setPublishing] = useState(false); const [batchLoading, setBatchLoading] = useState(false); @@ -510,24 +511,72 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => { } }; + const accountMap = useMemo( + () => new Map(accounts.map(account => [account.id, account])), + [accounts], + ); + const visibleItems = useMemo( + () => accountFilter ? items.filter(item => item.cookie_id === accountFilter) : items, + [accountFilter, items], + ); + const accountName = (cookieId: string) => { + const account = accountMap.get(cookieId); + const name = account?.remark || account?.nickname; + return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`; + }; + const accountNickname = (cookieId: string) => { + const account = accountMap.get(cookieId); + return account?.remark || account?.nickname || '未命名账号'; + }; + return (
-
+

商品管理

监控并管理所有账号下的闲鱼商品。

-
- +
+
+ +
+ + +
+
+
+ +
+ + +
+
- {items.map(item => { + {visibleItems.map(item => { const linkedRules = rulesForItem(item); const hasRule = linkedRules.length > 0; return ( @@ -603,6 +652,10 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {

{item.item_title}

+
+ + {accountNickname(item.cookie_id)} +
ID: {item.item_id} @@ -622,10 +675,10 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
); })} - {items.length === 0 && ( + {visibleItems.length === 0 && (
- 暂无商品数据,请选择账号进行同步 + {accountFilter ? '该账号暂无商品数据' : '暂无商品数据,请选择账号进行同步'}
)}
@@ -675,7 +728,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
@@ -727,7 +780,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
@@ -857,7 +910,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => { onChange={e => setSelectedAccount(e.target.value)} > - {accounts.map(acc => )} + {accounts.map(acc => )}

表格中“账号ID”为空时,会使用这里选择的账号。

@@ -924,7 +977,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => { {[ - ['账号ID', '没有在上方选择默认账号时填写', '填写账号 ID;已经选择默认账号时可以留空'], + ['账号ID', '需要覆盖默认账号时填写', '上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行'], ['标题', '每个商品都要填', '填写买家能看到的商品标题'], ['描述', '可以留空', '留空时会使用商品标题作为描述'], ['价格', '每个商品都要填', '只填数字,例如 19.90'], diff --git a/frontend/components/Notifications.tsx b/frontend/components/Notifications.tsx index f862e0d..1905fb4 100644 --- a/frontend/components/Notifications.tsx +++ b/frontend/components/Notifications.tsx @@ -15,6 +15,7 @@ import { Check, MessageCircle, Mail, Webhook, Send as Telegram, Eye, EyeOff, Save, } from 'lucide-react'; import { normalizeSMTPSettings } from '../smtpSettings'; +import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../notificationEmailConfig'; type ChannelTypeMeta = { label: string; @@ -139,18 +140,14 @@ const CHANNEL_TYPES: Record = { icon: Mail, fields: [ { key: 'to_email', label: '收件邮箱', placeholder: 'receiver@example.com', required: true }, - { key: 'smtp_server', label: '覆盖 SMTP 服务器', placeholder: 'smtp.qq.com', help: '留空时使用上方系统级 SMTP 配置' }, - { key: 'smtp_port', label: '覆盖 SMTP 端口', placeholder: '587', type: 'number', help: '留空时使用系统级 SMTP 端口' }, - { key: 'smtp_user', label: '覆盖发件邮箱', placeholder: 'you@qq.com', help: '留空时使用系统级发件邮箱' }, - { key: 'smtp_password', label: '覆盖密码 / 授权码', type: 'password', help: '留空时使用系统级授权码' }, ], guide: { steps: [ - '先在页面上方保存系统级 SMTP 服务器、端口、发件邮箱和授权码', - '邮件渠道只需要填写收件邮箱', - '如果某个渠道要使用不同发件邮箱,再填写下面的覆盖 SMTP 字段', + '通常先保存页面中的系统 SMTP 配置', + '邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP', + '只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置', ], - note: '收件邮箱会写入 to_email;SMTP 字段留空时后端会复用系统级 SMTP 配置。', + note: '继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。', }, }, }; @@ -188,6 +185,7 @@ const Notifications: React.FC = ({ isAdmin = false }) => { const [smtp, setSmtp] = useState({}); const [smtpSaving, setSmtpSaving] = useState(false); const [showSmtpPassword, setShowSmtpPassword] = useState(false); + const [showChannelSmtpPassword, setShowChannelSmtpPassword] = useState(false); const [form, setForm] = useState({ name: '', @@ -256,18 +254,28 @@ const Notifications: React.FC = ({ isAdmin = false }) => { const openCreate = () => { setEditing(null); setForm({ name: '', type: 'bark', enabled: true, config: {}, event_types: [] }); + setShowChannelSmtpPassword(false); setShowModal(true); }; const openEdit = (ch: NotificationChannel) => { setEditing(ch); + const normalizedEmailConfig = ch.type === 'email' + ? normalizeEmailChannelConfig({ ...(ch.config || {}) }) + : null; + const config = normalizedEmailConfig + ? (normalizedEmailConfig.use_custom_smtp === true + ? enableCustomSMTP(normalizedEmailConfig, smtp) + : normalizedEmailConfig) + : { ...(ch.config || {}) }; setForm({ name: ch.name, type: ch.type, enabled: ch.enabled, - config: { ...(ch.config || {}) }, + config, event_types: ch.event_types || [], }); + setShowChannelSmtpPassword(false); setShowModal(true); }; @@ -283,9 +291,27 @@ const Notifications: React.FC = ({ isAdmin = false }) => { showToast('error', '请填写渠道名称'); return; } + let config = form.config; + if (form.type === 'email') { + config = buildEmailChannelConfig(form.config); + if (config.use_custom_smtp) { + const required = [ + ['smtp_server', '独立 SMTP 服务器'], + ['smtp_port', '独立 SMTP 端口'], + ['smtp_user', '独立 SMTP 登录邮箱'], + ['smtp_password', '独立 SMTP 密码 / 授权码'], + ['smtp_from_address', '独立 SMTP 发件地址'], + ] as const; + const missing = required.find(([key]) => !String(config[key] || '').trim()); + if (missing) { + showToast('error', `请填写 ${missing[1]}`); + return; + } + } + } setSaving(true); try { - const payload = { name: form.name.trim(), type: form.type, config: form.config, event_types: form.event_types, enabled: form.enabled }; + const payload = { name: form.name.trim(), type: form.type, config, event_types: form.event_types, enabled: form.enabled }; if (editing) { await updateNotificationChannel(editing.id, payload); } else { @@ -664,6 +690,137 @@ const Notifications: React.FC = ({ isAdmin = false }) => { ))}
+ {form.type === 'email' && ( +
+
+
+
SMTP 来源
+

+ {form.config.use_custom_smtp === true + ? '当前渠道使用一套完整、独立的发件配置。' + : '当前渠道完整继承系统 SMTP,只单独设置收件邮箱。'} +

+
+ +
+ + {form.config.use_custom_smtp === true && ( +
+
+
+ + setForm({ ...form, config: { ...form.config, smtp_server: e.target.value } })} + placeholder="smtp.qq.com" + className="w-full ios-input px-4 py-3 rounded-xl text-sm" + /> +
+
+ + setForm({ ...form, config: { ...form.config, smtp_port: e.target.value } })} + placeholder="587" + className="w-full ios-input px-4 py-3 rounded-xl text-sm" + /> +
+
+ +
+ + setForm({ ...form, config: { ...form.config, smtp_user: e.target.value } })} + placeholder="your-email@qq.com" + className="w-full ios-input px-4 py-3 rounded-xl text-sm" + /> +
+ +
+ +
+ setForm({ ...form, config: { ...form.config, smtp_password: e.target.value } })} + placeholder="输入密码或授权码" + className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm" + /> + +
+
+ +
+
+ + setForm({ ...form, config: { ...form.config, smtp_from_name: e.target.value } })} + placeholder="闲鱼自动回复系统" + className="w-full ios-input px-4 py-3 rounded-xl text-sm" + /> +
+
+ + setForm({ ...form, config: { ...form.config, smtp_from_address: e.target.value } })} + placeholder="your-email@qq.com" + className="w-full ios-input px-4 py-3 rounded-xl text-sm" + /> +
+
+ +
+ + +
+
+ )} +
+ )} +
diff --git a/frontend/components/OrderList.tsx b/frontend/components/OrderList.tsx index cf090a5..34700e7 100644 --- a/frontend/components/OrderList.tsx +++ b/frontend/components/OrderList.tsx @@ -1,9 +1,10 @@ -import React, { useEffect, useRef, useState } from 'react'; +import React, { useEffect, useMemo, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; -import { Order, OrderStatus, Item } from '../types'; -import { getOrders, syncOrders, syncSingleOrder, manualShipOrder, updateOrder, deleteOrder, importOrders, getItems } from '../services/api'; +import { AccountDetail, Order, OrderStatus, Item } from '../types'; +import { getOrders, syncOrders, syncSingleOrder, manualShipOrder, updateOrder, deleteOrder, importOrders, getItems, getAccountDetails } from '../services/api'; import { Search, MoreHorizontal, Truck, RefreshCw, Copy, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, Phone, MapPin, Upload, ExternalLink, Trash2 } from 'lucide-react'; import { failedOrderImportRows, normalizeOrderImportResult, OrderImportResult } from './orderImportState'; +import { formatLocalDateTime } from '../dateTime'; const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => { const styles = { @@ -36,8 +37,10 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => { const OrderList: React.FC = () => { const [orders, setOrders] = useState([]); const [items, setItems] = useState([]); + const [accounts, setAccounts] = useState([]); const [itemNames, setItemNames] = useState>({}); const [filter, setFilter] = useState('all'); + const [accountFilter, setAccountFilter] = useState(''); const [searchText, setSearchText] = useState(''); // 搜索文本 const [debouncedSearch, setDebouncedSearch] = useState(''); const requestSequence = useRef(0); @@ -65,7 +68,7 @@ const OrderList: React.FC = () => { setLoading(true); try { - const res = await getOrders(undefined, filter, page, 20, debouncedSearch); + const res = await getOrders(accountFilter || undefined, filter, page, 20, debouncedSearch); if (sequence !== requestSequence.current) return; setOrders(res.data); setTotalPages(res.total_pages); @@ -77,15 +80,15 @@ const OrderList: React.FC = () => { }; // 从订单的 item_id 查找对应的商品名称(通过标题匹配) - const getItemNameById = (orderId: string, orderItemTitle?: string): string => { + const getItemNameById = (cookieId: string, orderId: string, orderItemTitle?: string): string => { // 如果订单有 item_title,优先使用 if (orderItemTitle && orderItemTitle.trim()) { return orderItemTitle; } // 尝试通过 item_id 直接匹配 - if (itemNames[orderId]) { - return itemNames[orderId]; + if (itemNames[`${cookieId}:${orderId}`]) { + return itemNames[`${cookieId}:${orderId}`]; } // 尝试在商品列表中查找相似标题的商品 @@ -113,7 +116,7 @@ const OrderList: React.FC = () => { items.forEach(item => { // 使用 item_id 作为键,商品标题作为值 if (item.item_id) { - namesMap[item.item_id] = item.item_title || item.item_id; + namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id; } }); setItemNames(namesMap); @@ -123,7 +126,7 @@ const OrderList: React.FC = () => { const namesMap: Record = {}; itemsList.forEach(item => { if (item.item_id) { - namesMap[item.item_id] = item.item_title || item.item_id; + namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id; } }); setItemNames(namesMap); @@ -139,10 +142,11 @@ const OrderList: React.FC = () => { useEffect(() => { loadOrders(); - }, [filter, page, debouncedSearch]); + }, [accountFilter, filter, page, debouncedSearch]); useEffect(() => { - getItems().then((itemsList) => { + Promise.all([getAccountDetails(), getItems()]).then(([accountList, itemsList]) => { + setAccounts(accountList); setItems(itemsList); buildItemNamesMapFrom(itemsList); }).catch((e) => { @@ -150,10 +154,25 @@ const OrderList: React.FC = () => { }); }, []); + const accountMap = useMemo( + () => new Map(accounts.map(account => [account.id, account])), + [accounts], + ); + + const accountName = (cookieId: string) => { + const account = accountMap.get(cookieId); + const name = account?.remark || account?.nickname; + return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`; + }; + const accountNickname = (cookieId: string) => { + const account = accountMap.get(cookieId); + return account?.remark || account?.nickname || '未命名账号'; + }; + const handleSync = async () => { setLoading(true); try { - const result = await syncOrders(); + const result = await syncOrders(accountFilter || undefined, filter); await loadOrders(); if (result?.message) { alert(result.message); @@ -357,7 +376,22 @@ const OrderList: React.FC = () => { ))}
-
+
+
+ + +
+
{ onChange={(e) => { setSearchText(e.target.value); setPage(1); }} className="ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0" /> +
@@ -395,10 +430,14 @@ const OrderList: React.FC = () => {
- {getItemNameById(order.item_id, order.item_title)} + {getItemNameById(order.cookie_id, order.item_id, order.item_title)} +
+
+ + {accountNickname(order.cookie_id)}
订单ID: {order.order_id}
-
数量: {order.quantity} • {order.created_at}
+
数量: {order.quantity} • {formatLocalDateTime(order.created_at)}
@@ -536,6 +575,10 @@ const OrderList: React.FC = () => {
订单号
{selectedOrder.order_id}
+
+
所属账号
+
{accountNickname(selectedOrder.cookie_id)}
+
状态
@@ -550,7 +593,7 @@ const OrderList: React.FC = () => {
创建时间
-
{selectedOrder.created_at}
+
{formatLocalDateTime(selectedOrder.created_at)}
@@ -564,7 +607,7 @@ const OrderList: React.FC = () => { )}
- {getItemNameById(selectedOrder.item_id, selectedOrder.item_title)} + {getItemNameById(selectedOrder.cookie_id, selectedOrder.item_id, selectedOrder.item_title)}
商品ID: {selectedOrder.item_id}
{selectedOrder.item_price && ( diff --git a/frontend/components/Rules.tsx b/frontend/components/Rules.tsx index 74f0a11..58b2533 100644 --- a/frontend/components/Rules.tsx +++ b/frontend/components/Rules.tsx @@ -1280,7 +1280,7 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa updateVariant(index, { delay_seconds: Math.max(0, Number(event.target.value) || 0) })} className="w-28 ios-input px-2 py-1.5 rounded-lg text-xs" diff --git a/frontend/components/Sidebar.tsx b/frontend/components/Sidebar.tsx index b559585..0cb2fc5 100644 --- a/frontend/components/Sidebar.tsx +++ b/frontend/components/Sidebar.tsx @@ -1,5 +1,6 @@ import React from 'react'; import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap, Bell } from 'lucide-react'; +import { YdisksBrandIcon } from './YdisksLogo'; interface SidebarProps { activeTab: string; @@ -24,8 +25,8 @@ const Sidebar: React.FC = ({ activeTab, isAdmin = false, onNavigat
-
- Ydisks +
+

Ydisks闲鱼助手 PRO

diff --git a/frontend/components/YdisksLogo.test.tsx b/frontend/components/YdisksLogo.test.tsx new file mode 100644 index 0000000..a32eb02 --- /dev/null +++ b/frontend/components/YdisksLogo.test.tsx @@ -0,0 +1,21 @@ +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, test } from 'vitest'; +import YdisksLogo, { YdisksBrandIcon } from './YdisksLogo'; + +describe('YdisksLogo', () => { + test('uses the complete 256px brand coordinate system', () => { + const html = renderToStaticMarkup(); + expect(html).toContain('viewBox="0 0 256 256"'); + expect(html).toContain('M121.73,57.0003'); + expect(html).toContain('fill="currentColor"'); + }); + + test('renders the complete gradient squircle brand wrapper', () => { + const html = renderToStaticMarkup(); + expect(html).toContain('viewBox="0 0 120 120"'); + expect(html).toContain('id="login-squircle-gradient"'); + expect(html).toContain('M 114.00 60.00'); + expect(html).toContain('w-12 h-12'); + }); +}); diff --git a/frontend/components/YdisksLogo.tsx b/frontend/components/YdisksLogo.tsx new file mode 100644 index 0000000..87efac6 --- /dev/null +++ b/frontend/components/YdisksLogo.tsx @@ -0,0 +1,43 @@ +import React from 'react'; + +interface YdisksLogoProps { + className?: string; +} + +interface YdisksBrandIconProps { + sizeClass?: string; + logoClassName?: string; +} + +const YdisksLogo: React.FC = ({ className = 'w-full h-full text-white' }) => ( + +); + +export const YdisksBrandIcon: React.FC = ({ + sizeClass = 'w-12 h-12', + logoClassName = 'w-full h-full text-white', +}) => ( +
+
+
+ +
+ +
+
+
+); + +export default YdisksLogo; diff --git a/frontend/components/cardListState.test.ts b/frontend/components/cardListState.test.ts new file mode 100644 index 0000000..0ba6a07 --- /dev/null +++ b/frontend/components/cardListState.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, test } from 'vitest'; +import type { Card } from '../types'; +import { filterCards } from './cardListState'; + +const cards = [ + { id: 1, name: '年终总结 PPT', type: 'text' }, + { id: 2, name: '年终总结兑换码', type: 'data' }, + { id: 3, name: '产品介绍 PPT', type: 'text' }, +] as Card[]; + +describe('filterCards', () => { + test('combines type and name filters with AND semantics', () => { + expect(filterCards(cards, 'text', '年终')).toEqual([cards[0]]); + }); + + test('matches names case-insensitively and ignores surrounding whitespace', () => { + expect(filterCards(cards, '', ' ppt ')).toEqual([cards[0], cards[2]]); + }); +}); diff --git a/frontend/components/cardListState.ts b/frontend/components/cardListState.ts new file mode 100644 index 0000000..c82127c --- /dev/null +++ b/frontend/components/cardListState.ts @@ -0,0 +1,13 @@ +import type { Card } from '../types'; + +export const filterCards = ( + cards: Card[], + typeFilter: Card['type'] | '', + nameSearch: string, +): Card[] => { + const keyword = nameSearch.trim().toLocaleLowerCase(); + return cards.filter(card => ( + (!typeFilter || card.type === typeFilter) + && (!keyword || card.name.toLocaleLowerCase().includes(keyword)) + )); +}; diff --git a/frontend/dateTime.test.ts b/frontend/dateTime.test.ts new file mode 100644 index 0000000..bb1ac95 --- /dev/null +++ b/frontend/dateTime.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, test } from 'vitest'; +import { formatLocalDateTime } from './dateTime'; + +describe('formatLocalDateTime', () => { + test('uses the browser local timezone and the standard second-level format', () => { + expect(formatLocalDateTime(new Date(2026, 6, 15, 10, 54, 12))).toBe('2026-07-15 10:54:12'); + }); + + test('returns a placeholder for missing or invalid timestamps', () => { + expect(formatLocalDateTime()).toBe('-'); + expect(formatLocalDateTime('not-a-date')).toBe('-'); + }); +}); diff --git a/frontend/dateTime.ts b/frontend/dateTime.ts new file mode 100644 index 0000000..723e82f --- /dev/null +++ b/frontend/dateTime.ts @@ -0,0 +1,19 @@ +const padTwoDigits = (value: number): string => String(value).padStart(2, '0'); + +/** Format a timestamp in the browser's current timezone. */ +export const formatLocalDateTime = (value?: string | number | Date | null): string => { + if (value === undefined || value === null || value === '') return '-'; + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) return '-'; + + return [ + date.getFullYear(), + padTwoDigits(date.getMonth() + 1), + padTwoDigits(date.getDate()), + ].join('-') + ' ' + [ + padTwoDigits(date.getHours()), + padTwoDigits(date.getMinutes()), + padTwoDigits(date.getSeconds()), + ].join(':'); +}; diff --git a/frontend/notificationEmailConfig.test.ts b/frontend/notificationEmailConfig.test.ts new file mode 100644 index 0000000..e35ba16 --- /dev/null +++ b/frontend/notificationEmailConfig.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, test } from 'vitest'; +import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from './notificationEmailConfig'; + +describe('email notification SMTP modes', () => { + test('recognizes legacy channel overrides as custom SMTP', () => { + expect(normalizeEmailChannelConfig({ to_email: 'to@example.com', smtp_server: 'legacy.example.com' }).use_custom_smtp).toBe(true); + }); + + test('inherit mode removes every channel-level SMTP override', () => { + expect(buildEmailChannelConfig({ + to_email: ' to@example.com ', + use_custom_smtp: false, + smtp_server: 'stale.example.com', + smtp_use_tls: false, + })).toEqual({ to_email: 'to@example.com', use_custom_smtp: false }); + }); + + test('custom mode starts from a complete copy of system SMTP settings', () => { + const result = enableCustomSMTP({ to_email: 'to@example.com' }, { + smtp_server: 'smtp.example.com', + smtp_port: 465, + smtp_user: 'from@example.com', + smtp_password: 'secret', + smtp_use_tls: false, + smtp_use_ssl: true, + }); + expect(result).toMatchObject({ + use_custom_smtp: true, + smtp_server: 'smtp.example.com', + smtp_port: 465, + smtp_from_address: 'from@example.com', + smtp_use_tls: false, + smtp_use_ssl: true, + }); + }); +}); diff --git a/frontend/notificationEmailConfig.ts b/frontend/notificationEmailConfig.ts new file mode 100644 index 0000000..952b195 --- /dev/null +++ b/frontend/notificationEmailConfig.ts @@ -0,0 +1,59 @@ +const smtpOverrideKeys = [ + 'smtp_server', + 'smtp_port', + 'smtp_user', + 'smtp_password', + 'smtp_from_name', + 'smtp_from_address', + 'smtp_use_tls', + 'smtp_use_ssl', +] as const; + +const parseBoolean = (value: unknown, fallback: boolean): boolean => { + if (typeof value === 'boolean') return value; + if (typeof value === 'string') { + if (['true', '1', 'yes', 'on'].includes(value.toLowerCase())) return true; + if (['false', '0', 'no', 'off'].includes(value.toLowerCase())) return false; + } + return fallback; +}; + +export const normalizeEmailChannelConfig = (config: Record): Record => { + const hasExplicitMode = Object.prototype.hasOwnProperty.call(config, 'use_custom_smtp'); + const hasLegacyOverrides = smtpOverrideKeys.some(key => String(config[key] ?? '').trim() !== ''); + return { + ...config, + use_custom_smtp: hasExplicitMode + ? parseBoolean(config.use_custom_smtp, false) + : hasLegacyOverrides, + }; +}; + +export const enableCustomSMTP = ( + config: Record, + systemSettings: Record, +): Record => { + const next: Record = { ...config, use_custom_smtp: true }; + for (const key of smtpOverrideKeys) { + if (String(next[key] ?? '').trim() === '' && systemSettings[key] !== undefined) { + next[key] = systemSettings[key]; + } + } + next.smtp_port ||= 587; + next.smtp_from_address ||= next.smtp_user || ''; + next.smtp_use_tls = parseBoolean(next.smtp_use_tls, true); + next.smtp_use_ssl = parseBoolean(next.smtp_use_ssl, false); + return next; +}; + +export const buildEmailChannelConfig = (config: Record): Record => { + const normalized = normalizeEmailChannelConfig(config); + const result: Record = { + to_email: String(normalized.to_email ?? '').trim(), + use_custom_smtp: normalized.use_custom_smtp === true, + }; + if (result.use_custom_smtp) { + for (const key of smtpOverrideKeys) result[key] = normalized[key]; + } + return result; +}; diff --git a/frontend/routing.test.ts b/frontend/routing.test.ts index 5d3a72c..00943c2 100644 --- a/frontend/routing.test.ts +++ b/frontend/routing.test.ts @@ -71,13 +71,14 @@ describe('frontend navigation routing', () => { expect(settings).toContain('只有网络不可用或超时才回退本机引擎'); }); - test('email notification config uses backend recipient field names', () => { + test('email notification config separates system and custom SMTP modes', () => { const notifications = readFrontendFile('components/Notifications.tsx'); expect(notifications).toContain('interface NotificationsProps'); expect(notifications).toContain('isAdmin && ('); expect(notifications).toContain("key: 'to_email'"); - expect(notifications).toContain('留空时使用上方系统级 SMTP 配置'); + expect(notifications).toContain('完整继承系统 SMTP'); + expect(notifications).toContain('use_custom_smtp'); expect(notifications).not.toContain("key: 'from'"); expect(notifications).not.toContain('注册验证码'); }); diff --git a/frontend/services/api.test.ts b/frontend/services/api.test.ts index 0c6915a..be6de25 100644 --- a/frontend/services/api.test.ts +++ b/frontend/services/api.test.ts @@ -187,6 +187,18 @@ test('getItems normalizes multi-spec flags from backend values', async () => { }); }); +test('getItems forwards the selected account filter', async () => { + const fetchMock = vi.fn().mockResolvedValue(jsonResponse([])); + vi.stubGlobal('fetch', fetchMock); + + await getItems('account-2'); + + expect(fetchMock).toHaveBeenCalledWith('/items?cookie_id=account-2', expect.objectContaining({ + method: 'GET', + credentials: 'include', + })); +}); + test('getSystemSettings normalizes numeric renewal retention', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ ai_model: 'qwen-plus', diff --git a/frontend/services/api.ts b/frontend/services/api.ts index ae7c030..93e91b2 100644 --- a/frontend/services/api.ts +++ b/frontend/services/api.ts @@ -159,6 +159,19 @@ export const updateAccountSettings = async (id: string, data: AccountSettingsUpd return put(`/cookies/${id}/settings`, data); }; +export interface LongLoginSettings { + can_open_long_login: boolean; + enabled: boolean; +} + +export const getLongLoginSettings = async (id: string): Promise => { + return get(`/cookies/${id}/long-login`); +}; + +export const setLongLoginSettings = async (id: string, enabled: boolean): Promise => { + return put(`/cookies/${id}/long-login`, { enabled }); +}; + export interface PasswordLoginStartResponse { success: boolean; session_id?: string; @@ -413,8 +426,8 @@ export const appendCardData = async (cardId: string | number, content: string): const normalizeBooleanFlag = (value: unknown): boolean => value === true || value === 1 || value === '1'; -export const getItems = async (): Promise => { - const res = await get('/items'); +export const getItems = async (cookieId?: string): Promise => { + const res = await get('/items', cookieId ? { cookie_id: cookieId } : undefined); const items = Array.isArray(res) ? res : (res.items || []); return items.map((item: any) => ({ ...item, diff --git a/internal/account/manager_extra_test.go b/internal/account/manager_extra_test.go index 31976a9..2440c24 100644 --- a/internal/account/manager_extra_test.go +++ b/internal/account/manager_extra_test.go @@ -3,6 +3,7 @@ package account import ( "context" "errors" + "log/slog" "path/filepath" "strings" "sync" @@ -12,8 +13,34 @@ import ( "xianyu-go/internal/db" "xianyu-go/internal/engine" "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/ws" ) +type fakeWSDialer struct{} + +func (fakeWSDialer) Dial(context.Context, ws.Config, *slog.Logger) (engine.WSConn, error) { + return fakeWSConn{}, nil +} + +type fakeWSConn struct{} + +func (fakeWSConn) Register(context.Context, string, string) error { return nil } +func (fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error { + <-ctx.Done() + return ctx.Err() +} +func (fakeWSConn) ReceiveLoop(ctx context.Context, _ func(map[string]any)) error { + <-ctx.Done() + return ctx.Err() +} +func (fakeWSConn) Close() error { return nil } +func (fakeWSConn) SendText(context.Context, string, string, string, string) error { + return nil +} +func (fakeWSConn) SendImage(context.Context, string, string, string, string, int, int) error { + return nil +} + // fakeMtop 是注入 engine.Account 的可控 mtop 客户端,避免真实网络。 // refreshErr 非空时 RefreshToken 返回该错误;block 非空时阻塞到该 chan // 关闭或 ctx 取消(用于让 Run 挂起、模拟"账号在线运行中")。 @@ -98,6 +125,7 @@ func startAccountWithMtop(t *testing.T, mgr *Manager, cookieID, cookieValue stri Handler: mgr.handler, Logger: mgr.logger, MTop: mtopClient, + WSDialer: fakeWSDialer{}, }) accCtx, accCancel := context.WithCancel(runCtx) ma := &managedAccount{ diff --git a/internal/adapter/adapter_test.go b/internal/adapter/adapter_test.go index 8036164..eb80dae 100644 --- a/internal/adapter/adapter_test.go +++ b/internal/adapter/adapter_test.go @@ -112,7 +112,7 @@ func verifiedRenewService(t *testing.T) (xrenew.Service, func()) { _, _ = w.Write([]byte(`{"content":{"success":true}}`)) case "/silentHasLogin.do": http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"}) - _, _ = w.Write([]byte(`{"content":{"success":true}}`)) + _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`)) case "/setLoginSettings.do": http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"}) _, _ = w.Write([]byte(`{"content":{"success":true}}`)) diff --git a/internal/browser/cookierenew.go b/internal/browser/cookierenew.go index 824cfdf..6fc81b0 100644 --- a/internal/browser/cookierenew.go +++ b/internal/browser/cookierenew.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "strconv" "strings" "time" @@ -175,13 +176,31 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt } defer func() { _ = page.Close() }() - if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{ - WaitUntil: playwright.WaitUntilStateDomcontentloaded, - Timeout: playwright.Float(60000), - }); err != nil { - m.logger.Warn("COOKIES续期访问首页异常", "cookieID", cookieID, "err", err) + navigate := func() error { + _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{ + WaitUntil: playwright.WaitUntilStateDomcontentloaded, + Timeout: playwright.Float(60000), + }) + return err + } + if expectsOfficialSilentLogin(cookieStr) { + response, err := page.ExpectResponse("**/newlogin/silentHasLogin.do**", navigate, playwright.PageExpectResponseOptions{Timeout: playwright.Float(7000)}) + if err != nil { + return "", nil, fmt.Errorf("等待官网静默续期请求完成: %w", err) + } + if response == nil || response.Status() < 200 || response.Status() >= 300 { + return "", nil, fmt.Errorf("官网静默续期 HTTP 状态异常") + } + // 插件在业务成功后立即 location.reload;等待短暂调度窗口,再等待 + // 新文档进入 DOMContentLoaded,避免提取续期前 Cookie。 + page.WaitForTimeout(500) + _ = page.WaitForLoadState(playwright.PageWaitForLoadStateOptions{ + State: playwright.LoadStateDomcontentloaded, + Timeout: playwright.Float(5000), + }) + } else if err := navigate(); err != nil { + m.logger.Warn("COOKIES续期访问消息页异常", "cookieID", cookieID, "err", err) } - time.Sleep(quickRenewPageLoadWait) if err := verifyHomeLoginState(page); err != nil { return "", nil, err } @@ -199,6 +218,27 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt return newCookies, newSnapshot, nil } +func expectsOfficialSilentLogin(cookieStr string) bool { + cookies := cookierefresh.ParseCookieString(cookieStr) + now := time.Now().UnixMilli() + if futureCookieMillis(cookies["sdkSilent"], now) { + return false + } + return futureCookieMillis(cookies["havana_lgc_exp"], now) || futureCookieMillis(cookies["cookie3_bak_exp"], now) +} + +func futureCookieMillis(raw string, now int64) bool { + raw = strings.TrimSpace(raw) + if raw == "" { + return false + } + value, err := strconv.ParseInt(raw, 10, 64) + if err != nil { + return true + } + return value > now +} + // CookieRenewSnapshot 兼容旧调用,等价于定时 COOKIES 快照续期。 func (m *Manager) CookieRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) { return m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless) diff --git a/internal/db/account_tokens.go b/internal/db/account_tokens.go index 431aad5..c0c7c03 100644 --- a/internal/db/account_tokens.go +++ b/internal/db/account_tokens.go @@ -7,11 +7,9 @@ import ( "fmt" ) -// AccountToken 持久化的账号登录凭证缓存(device_id + accessToken)。 -// -// 设计动机(参考 xianyu-auto-reply 的 xy_token_cache): -// - device_id 跨进程重启复用,避免每次重启换新设备 ID 触发阿里端设备绑定/风控; -// - accessToken 缓存后,短重启可复用、瞬时 mtop 失败可回退到上次有效 token,不掉线。 +// AccountToken 持久化最近一次页面运行实例的 device_id 和 token 请求元数据。 +// accessToken 不用于后续 WebSocket 注册;官方消息页在每次 loginV2/reConnect +// 前都会重新获取 token,页面重载后也会生成新的 device_id。 type AccountToken struct { CookieID string DeviceID string @@ -56,17 +54,9 @@ func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToke return t.SaveBound(ctx, cookieID, deviceID, accessToken, expireAt, "") } -// SaveBound persists an access token together with the canonical Cookie state -// from which it was issued. The binding lets a later reconnect reject a stale -// token after an independent Cookie renewal without rotating device_id. +// SaveBound persists an access token together with the page-runtime device ID +// and canonical Cookie state from which it was issued. func (t *AccountTokens) SaveBound(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64, cookieFingerprint string) error { - // device_id is an account identity, not part of the expiring token cache. - // Once stored, token refreshes must never replace it. - if existing, err := t.Get(ctx, cookieID); err == nil && existing.DeviceID != "" { - deviceID = existing.DeviceID - } else if err != nil && !errors.Is(err, ErrNotFound) { - return err - } encryptedDeviceID, err := t.codec.encrypt("device-id", cookieID, deviceID) if err != nil { return err diff --git a/internal/db/account_tokens_test.go b/internal/db/account_tokens_test.go index a15d26d..c4b70d8 100644 --- a/internal/db/account_tokens_test.go +++ b/internal/db/account_tokens_test.go @@ -39,21 +39,21 @@ func TestAccountTokens_CRUD(t *testing.T) { t.Fatalf("Get 返回不匹配: %+v", tk) } - // 再次 Save 更新 token,但永久 device ID 不允许覆盖。 + // 页面运行实例变化后,再次 Save 同步更新 device ID 和 token。 if err := store.Tokens.SaveBound(ctx, "cid", "dev-2", "tok-2", expire+1, "cookie-hash-2"); err != nil { t.Fatalf("Save upsert: %v", err) } tk, _ = store.Tokens.Get(ctx, "cid") - if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 || tk.CookieFingerprint != "cookie-hash-2" { + if tk.DeviceID != "dev-2" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 || tk.CookieFingerprint != "cookie-hash-2" { t.Fatalf("upsert 后字段应更新: %+v", tk) } - // Clear 只清 token,永久 device ID 必须保留。 + // Clear 只清 token,保留最近一次页面运行实例的 device ID。 if err := store.Tokens.Clear(ctx, "cid"); err != nil { t.Fatalf("Clear: %v", err) } tk, err = store.Tokens.Get(ctx, "cid") - if err != nil || tk.DeviceID != "dev-1" || tk.AccessToken != "" || tk.ExpireAt != 0 || tk.CookieFingerprint != "" { + if err != nil || tk.DeviceID != "dev-2" || tk.AccessToken != "" || tk.ExpireAt != 0 || tk.CookieFingerprint != "" { t.Fatalf("Clear 后 device ID 应保留且 token 清空: tk=%+v err=%v", tk, err) } @@ -63,7 +63,7 @@ func TestAccountTokens_CRUD(t *testing.T) { } } -func TestAccountTokens_DeviceIDSurvivesTokenLifecycle(t *testing.T) { +func TestAccountTokens_SaveTracksLatestRuntimeDeviceID(t *testing.T) { store, cleanup := newTestDB(t) defer cleanup() ctx := context.Background() @@ -83,8 +83,8 @@ func TestAccountTokens_DeviceIDSurvivesTokenLifecycle(t *testing.T) { t.Fatal(err) } afterRestart, err := store.Tokens.GetOrCreateDeviceID(ctx, "cid", "device-after-restart") - if err != nil || first != "device-first" || afterRestart != first { - t.Fatalf("device ID changed across token lifecycle: first=%q after=%q err=%v", first, afterRestart, err) + if err != nil || first != "device-first" || afterRestart != "device-replacement" { + t.Fatalf("未保留最近一次运行时 device ID: first=%q after=%q err=%v", first, afterRestart, err) } } diff --git a/internal/db/orders.go b/internal/db/orders.go index 07a7da9..3a82868 100644 --- a/internal/db/orders.go +++ b/internal/db/orders.go @@ -201,6 +201,9 @@ func orderUpsertAssignments(opts OrderUpsertOpts) ([]string, []any) { if opts.SystemShipped != nil { add("system_shipped", boolToInt(*opts.SystemShipped), true) } + if opts.IsBargain != nil { + add("is_bargain", boolToInt(*opts.IsBargain), true) + } add("chat_id", opts.ChatID, opts.ChatID != "") add("item_id", opts.ItemID, opts.ItemID != "") add("buyer_id", opts.BuyerID, opts.BuyerID != "") @@ -277,6 +280,7 @@ type OrderUpsertOpts struct { ReceiverAddr string ReceiverCity string ChatID string + IsBargain *bool SystemShipped *bool } diff --git a/internal/engine/account.go b/internal/engine/account.go index ebe8775..33efcc3 100644 --- a/internal/engine/account.go +++ b/internal/engine/account.go @@ -18,6 +18,7 @@ import ( "xianyu-go/internal/automation" "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/cookierefresh" "xianyu-go/internal/xianyu/mtop" "xianyu-go/internal/xianyu/protocol" "xianyu-go/internal/xianyu/renew" @@ -87,7 +88,6 @@ type tokenCaptchaHandler interface { const ( tokenRefreshStarted = "started" tokenRefreshSuccess = "success" - tokenRefreshSuccessFromCache = "success_from_cache" tokenRefreshFailedCaptcha = "failed_captcha" tokenRefreshFailedCaptchaError = "failed_captcha_exception" tokenRefreshFailedTimeout = "failed_timeout" @@ -141,7 +141,7 @@ type Account struct { store *db.Store mtop mtop.Client renewer cookieRenewer - wsDialer wsDialer + wsDialer WSDialer handler Handler logger *slog.Logger @@ -200,6 +200,7 @@ type debounceEntry struct { // WSConn 是 Account 对 ws 连接的最小契约。*ws.Conn 实现该接口; // 测试可注入 fakeWSConn 以隔离真实 WS 握手与网络。 type WSConn interface { + Register(ctx context.Context, deviceID, accessToken string) error HeartbeatLoop(ctx context.Context, interval time.Duration) error ReceiveLoop(ctx context.Context, onMessage func(map[string]any)) error Close() error @@ -207,15 +208,15 @@ type WSConn interface { SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error } -// wsDialer 抽象 ws.Dial,便于测试替身。 -type wsDialer interface { +// WSDialer 抽象 WebSocket 打开阶段,便于测试隔离真实网络。 +type WSDialer interface { Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error) } type defaultDialer struct{} func (defaultDialer) Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error) { - return ws.Dial(ctx, cfg, logger) + return ws.Open(ctx, cfg, logger) } type cookieRenewer interface { @@ -243,6 +244,8 @@ type Config struct { MTop mtop.Client // Renewer 可选:注入 Cookie 接口续期服务以便测试 mock。nil 时使用默认实现。 Renewer cookieRenewer + // WSDialer 可选:用于测试隔离原生 WebSocket 握手。 + WSDialer WSDialer } // New 构造单账号运行时(未启动)。 @@ -262,6 +265,10 @@ func New(cfg Config) *Account { } cookies := protocol.TransCookies(cfg.CookieStr) myid := cookies["unb"] + wsDialer := cfg.WSDialer + if wsDialer == nil { + wsDialer = defaultDialer{} + } a := &Account{ CookieID: cfg.CookieID, CookieStr: cfg.CookieStr, @@ -269,7 +276,7 @@ func New(cfg Config) *Account { store: cfg.Store, mtop: mtopClient, renewer: renewer, - wsDialer: defaultDialer{}, + wsDialer: wsDialer, handler: cfg.Handler, logger: logger.With("account", cfg.CookieID), deviceID: protocol.GenerateDeviceID(myid), @@ -281,14 +288,6 @@ func New(cfg Config) *Account { runtimeMessage: "正在启动账号服务", runtimeUpdatedAt: time.Now(), } - if cfg.Store != nil && cfg.Store.Tokens != nil { - deviceID, err := cfg.Store.Tokens.GetOrCreateDeviceID(context.Background(), cfg.CookieID, a.deviceID) - if err != nil { - logger.Error("读取或保存账号 device ID 失败", "account", cfg.CookieID, "err", err) - } else { - a.deviceID = deviceID - } - } if cfg.Store != nil { a.reply = NewReplyService(cfg.CookieID, cfg.Store, a, nil, NewAIReplier(cfg.CookieID, cfg.Store, logger), logger) } @@ -308,6 +307,11 @@ func (a *Account) Run(parent context.Context) error { a.runtimeCtx = ctx a.accepting = true a.taskMu.Unlock() + // 对应官网页面初始化时执行一次 auto-login plugin。成功更新 Cookie 时, + // adoptRecoveredCookie 会旋转本次引擎身份,等价于页面 reload 后新建引擎。 + if a.renewer != nil { + _ = a.tryAPIRenew(ctx) + } for { if ctx.Err() != nil { @@ -322,8 +326,25 @@ func (a *Account) Run(parent context.Context) error { // 每次新建 IM 连接前吸收数据库中的最新 Cookie。健康连接不会被续期任务 // 主动打断;Cookie 变化只会使本次重连放弃旧 token 并重新派生。 a.reloadCookieFromDB(ctx) - token, cookieStr, err := a.acquireRuntimeToken(ctx) + + // 官网先完成原生 WebSocket 握手,再从 authTokenCallback 获取本次 + // 连接专用 token,最后发送 /reg。 + conn, err := a.wsDialer.Dial(ctx, ws.Config{Recorder: a.wsRecorder()}, a.logger) if err != nil { + a.logger.Error("WS 握手失败", "err", err) + if retryErr := a.handleWSConnectFailure(ctx, err, &invalidTokenRetried); retryErr != nil { + return retryErr + } + continue + } + connectedAt := time.Now() + // The official web client calls + // mtop.taobao.idlemessage.pc.login.token from authTokenCallback for every + // loginV2/reConnect attempt. Do the same here: an access token belongs to + // one connection attempt and must never be reused for a later /reg. + token, cookieStr, err := a.acquireFreshConnectionToken(ctx) + if err != nil { + _ = conn.Close() a.logger.Error("获取 token 失败", "err", err) a.mu.Lock() status := a.lastTokenStatus @@ -374,23 +395,7 @@ func (a *Account) Run(parent context.Context) error { a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务") a.logger.Info("token 刷新成功") - // 2) 连接 WS + 注册。 - var recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string) - if a.store != nil && a.store.WSMessages != nil { - recorder = func(direction, rawText, parsedJSON, parseStatus, errMsg string) { - if err := a.store.WSMessages.Add(context.Background(), db.WSMessage{ - CookieID: a.CookieID, - Direction: direction, - RawText: rawText, - ParsedJSON: parsedJSON, - MessageKind: "", - ParseStatus: parseStatus, - Error: errMsg, - }); err != nil { - a.logger.Error("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err) - } - } - } + // 2) 使用刚获得的 token 注册已经打开的 WS。 a.mu.Lock() deviceID := a.deviceID a.mu.Unlock() @@ -400,50 +405,17 @@ func (a *Account) Run(parent context.Context) error { } if !a.cookieSnapshotMatchesDB(ctx, cookieStr) { credentialUnlock() + _ = conn.Close() a.reloadCookieFromDB(ctx) continue } - attemptStartedAt := time.Now() - conn, err := a.wsDialer.Dial(ctx, ws.Config{ - CookieStr: cookieStr, - DeviceID: deviceID, - AccessToken: token, - Recorder: recorder, - }, a.logger) + err = conn.Register(ctx, deviceID, token) credentialUnlock() if err != nil { - a.logger.Error("WS 连接失败", "err", err) - if ws.IsInvalidTokenError(err) && !invalidTokenRetried { - invalidTokenRetried = true - a.clearCurrentToken() - a.clearTokenCache(ctx) - a.setRuntimeState(RuntimeConnecting, "消息凭证被拒绝,正在重新获取一次新凭证") - continue - } - if ws.IsConnectLimitError(err) { - a.setRuntimeState(RuntimeReconnecting, "消息服务连接数受限,正在限速重试") - if sleepCtx(ctx, withRetryJitter(30*time.Second)) != nil { - return ctx.Err() - } - continue - } - a.mu.Lock() - a.connFailures++ - failures := a.connFailures - a.mu.Unlock() - if ws.IsInvalidTokenError(err) || ws.IsAuthenticationError(err) { - a.clearCurrentToken() - a.clearTokenCache(ctx) - } - a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试") - if failures >= MaxConnectionFailures { - if err := a.handleMaxFailures(ctx); err != nil { - return err - } - continue - } - if sleepCtx(ctx, a.retryDelay("ws_dial")) != nil { - return ctx.Err() + _ = conn.Close() + a.logger.Error("WS 注册失败", "err", err) + if retryErr := a.handleWSConnectFailure(ctx, err, &invalidTokenRetried); retryErr != nil { + return retryErr } continue } @@ -494,11 +466,13 @@ func (a *Account) Run(parent context.Context) error { // 正常 close 的 async-for 会直接进入下一轮,不计任何失败。 if recvErr == nil { + a.clearConnectionToken(ctx) a.setRuntimeState(RuntimeReconnecting, "消息连接已结束,正在重新连接") continue } if isEstablishedNetworkError(recvErr) { + a.clearConnectionToken(ctx) a.mu.Lock() a.networkFailures++ networkFailures := a.networkFailures @@ -530,7 +504,7 @@ func (a *Account) Run(parent context.Context) error { a.connFailures++ failures := a.connFailures a.mu.Unlock() - if time.Since(attemptStartedAt) < 15*time.Second { + if time.Since(connectedAt) < 15*time.Second { a.clearTokenCache(ctx) } a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,稍后自动重连") @@ -548,6 +522,67 @@ func (a *Account) Run(parent context.Context) error { } } +func (a *Account) wsRecorder() func(direction, rawText, parsedJSON, parseStatus, errMsg string) { + if a.store == nil || a.store.WSMessages == nil { + return nil + } + return func(direction, rawText, parsedJSON, parseStatus, errMsg string) { + if err := a.store.WSMessages.Add(context.Background(), db.WSMessage{ + CookieID: a.CookieID, + Direction: direction, + RawText: rawText, + ParsedJSON: parsedJSON, + MessageKind: "", + ParseStatus: parseStatus, + Error: errMsg, + }); err != nil { + a.logger.Error("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err) + } + } +} + +func (a *Account) handleWSConnectFailure(ctx context.Context, err error, invalidTokenRetried *bool) error { + if ws.IsInvalidTokenError(err) && !*invalidTokenRetried { + *invalidTokenRetried = true + a.clearCurrentToken() + a.clearTokenCache(ctx) + a.setRuntimeState(RuntimeConnecting, "消息凭证被拒绝,正在重新获取一次新凭证") + return nil + } + if ws.IsConnectLimitError(err) { + a.setRuntimeState(RuntimeReconnecting, "消息服务连接数受限,正在限速重试") + return sleepCtx(ctx, withRetryJitter(30*time.Second)) + } + a.mu.Lock() + a.connFailures++ + failures := a.connFailures + a.mu.Unlock() + if ws.IsInvalidTokenError(err) || ws.IsAuthenticationError(err) { + a.clearCurrentToken() + a.clearTokenCache(ctx) + } + a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试") + if failures >= MaxConnectionFailures { + return a.handleMaxFailures(ctx) + } + return sleepCtx(ctx, a.retryDelay("ws_connect")) +} + +// acquireFreshConnectionToken mirrors the official web message client: +// authTokenCallback obtains a fresh login.token result before every WebSocket +// loginV2/reConnect and the returned accessToken is used only for that /reg. +func (a *Account) acquireFreshConnectionToken(ctx context.Context) (string, string, error) { + return a.refreshToken(ctx) +} + +// clearConnectionToken ends the lifetime of the token used by the previous +// WebSocket attempt. The page-runtime device ID remains stable until a Cookie +// update maps to an official page reload. +func (a *Account) clearConnectionToken(ctx context.Context) { + a.clearCurrentToken() + a.clearTokenCache(ctx) +} + // Stop 优雅停止。 func (a *Account) Stop() { a.mu.Lock() @@ -768,6 +803,7 @@ func (a *Account) tryAPIRenew(ctx context.Context) bool { } updated := false if res.NewCookies != "" && res.NewCookies != cookieStr { + a.persistRenewCookieSnapshot(ctx, cookieStr, res.NewCookies, res.SetCookies) updated = a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期") } if res.Success { @@ -785,6 +821,25 @@ func (a *Account) tryAPIRenew(ctx context.Context) bool { return false } +func (a *Account) persistRenewCookieSnapshot(ctx context.Context, oldCookies, newCookies string, setCookies []string) { + if a.store == nil || a.store.Cookies == nil { + return + } + detail, err := a.store.Cookies.GetDetails(ctx, a.CookieID) + if err != nil || detail == nil { + return + } + snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON) + if len(snapshot) == 0 { + snapshot = cookierefresh.SnapshotFromCookieString(oldCookies, ".goofish.com") + } + snapshot = cookierefresh.ApplySetCookies(snapshot, renew.SilentHasLoginURL, setCookies, time.Now()) + metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) + if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix()); err != nil { + a.logger.Warn("保存接口续期 Cookie 快照失败", "err", err) + } +} + // adoptRecoveredCookie 统一接收“轻量检查/接口续期/浏览器恢复”拿到的新 Cookie。 // Cookie 变更意味着旧 accessToken 与 session 绑定关系失效,必须清 token 缓存, // 让下一轮 acquireToken 使用新 Cookie 重新派生凭证。 @@ -799,6 +854,7 @@ func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source s return false } a.replaceCookieStr(newCookies) + a.rotateDeviceID(newCookies) a.clearCurrentToken() if a.store != nil && a.store.Cookies != nil { if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, newCookies); err != nil { @@ -906,8 +962,8 @@ func (a *Account) recordShortDisconnect(connectedDuration time.Duration) bool { } // refreshToken 调 mtop token API,返回 (accessToken, 更新后的 cookie)。 -// 成功时把 token + device_id 缓存到 DB(saveTokenCache),供进程重启复用与 -// 稳态重连时跳过 mtop(acquireToken 命中缓存即直接返回)。 +// 成功时记录 token 的服务端过期时间并保持 device_id 持久化,但连接流程 +// 不会复用该 token;下一次 loginV2/reConnect 仍会重新调用本方法。 func (a *Account) refreshToken(ctx context.Context) (string, string, error) { return a.refreshTokenWithMinGap(ctx, false) } @@ -1008,8 +1064,20 @@ func (a *Account) adoptTokenResponseCookies(ctx context.Context, cookieStr strin } a.replaceCookieStr(res.UpdatedCookies) if a.store != nil && a.store.Cookies != nil { - if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, res.UpdatedCookies); err != nil { - a.logger.Error("token 响应后保存 cookie 失败", "cookie_id", a.CookieID, "err", err) + detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID) + if detailErr == nil && detail != nil { + snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON) + if len(snapshot) == 0 { + snapshot = cookierefresh.SnapshotFromCookieString(cookieStr, ".goofish.com") + } + snapshot = cookierefresh.ReconcileSnapshotWithCookieString(snapshot, res.UpdatedCookies) + metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) + detailErr = a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.UpdatedCookies, metadata, time.Now().Unix()) + } else { + detailErr = a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, res.UpdatedCookies) + } + if detailErr != nil { + a.logger.Error("token 响应后保存 cookie 失败", "cookie_id", a.CookieID, "err", detailErr) } } return res.UpdatedCookies @@ -1062,39 +1130,23 @@ func (a *Account) tokenCaptchaCooldownRemaining() time.Duration { return remaining } -// acquireToken 取用于 WS /reg 的 accessToken:缓存命中且未过期则跳过 mtop(降低风控 -// 与瞬时失败影响),否则调 refreshToken 重新派生并落库缓存。 -// -// 设计:稳态重连时复用未过期缓存 token,避免每次重连都打 mtop(降低风控触发)。 -// 缓存 token 若已被服务端失效,dial 后会短连接断开 → clearTokenCache → 下轮重新派生,自愈。 +// acquireToken is kept for internal callers and tests, but intentionally does +// not reuse the persisted accessToken. Official web reconnects always invoke +// the login.token API before /reg. func (a *Account) acquireToken(ctx context.Context) (string, string, error) { return a.acquireTokenWithMinGap(ctx, false) } -// acquireRuntimeToken 对齐参考主循环:网络重连时只要内存 token 仍存在就直接 -// 复用;只有认证分支明确清空它后,才重新检查数据库缓存或调用 Token API。 +// acquireRuntimeToken is retained as a compatibility wrapper for focused +// tests and older internal callers. It follows the same fresh-token rule. func (a *Account) acquireRuntimeToken(ctx context.Context) (string, string, error) { - a.mu.Lock() - token := a.currentToken - cookieStr := a.CookieStr - a.mu.Unlock() - if strings.TrimSpace(token) != "" { - return token, cookieStr, nil - } - return a.acquireToken(ctx) + return a.acquireFreshConnectionToken(ctx) } func (a *Account) acquireTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) { - if token, ok := a.cachedTokenIfFresh(ctx); ok { - a.mu.Lock() - a.currentToken = token - a.lastTokenRefresh = time.Now() - a.lastTokenStatus = tokenRefreshSuccessFromCache - cookieStr := a.CookieStr - a.mu.Unlock() - a.logger.Info("使用缓存的 accessToken,跳过 mtop 刷新") - return token, cookieStr, nil - } + // Invalidate any access token left by an older process/attempt before asking + // MTOP for the token that will be bound to this connection. + a.clearTokenCache(ctx) return a.refreshToken(ctx) } @@ -1130,39 +1182,9 @@ func tokenFailureIsNonCounted(status string) bool { } } -// cachedTokenIfFresh 返回未过期的缓存 accessToken。无缓存 / 已过期返回 ok=false。 -func (a *Account) cachedTokenIfFresh(ctx context.Context) (string, bool) { - if a.store == nil || a.store.Tokens == nil { - return "", false - } - tk, err := a.store.Tokens.Get(ctx, a.CookieID) - if err != nil { - return "", false - } - a.mu.Lock() - cookieStr := a.CookieStr - a.mu.Unlock() - expectedFingerprint := credentialCookieFingerprint(cookieStr) - if tk.AccessToken == "" || tk.ExpireAt <= time.Now().Unix() || - tk.CookieFingerprint == "" || tk.CookieFingerprint != expectedFingerprint { - // 参考实现发现过期缓存后立即删除整行,再进入标准 token 请求。 - if tk.AccessToken != "" { - a.clearTokenCache(ctx) - } - return "", false - } - // 命中缓存时同步复用其 device_id,保证 token 与 /reg.did 一致。 - if tk.DeviceID != "" { - a.mu.Lock() - a.deviceID = tk.DeviceID - a.mu.Unlock() - } - return tk.AccessToken, true -} - -// saveTokenCache uses the expiry returned by the token API. A response without -// a usable accessTokenExpiredTime remains valid for the current process only; -// it is deliberately not assigned a guessed multi-hour lifetime. +// saveTokenCache records the server expiry and current page-runtime identity. +// It is diagnostic state only: acquireToken never reads the accessToken back +// for a later WebSocket registration. func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, cookieStr string) { if a.store == nil || a.store.Tokens == nil || accessToken == "" { return @@ -1206,6 +1228,7 @@ func (a *Account) reloadCookieFromDB(ctx context.Context) bool { } a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID) a.replaceCookieStr(d.Value) + a.rotateDeviceID(d.Value) a.clearCurrentToken() a.clearTokenCache(ctx) a.mu.Lock() @@ -1322,6 +1345,16 @@ func (a *Account) replaceCookieStr(cookieStr string) { } } +func (a *Account) rotateDeviceID(cookieStr string) { + userID := protocol.TransCookies(cookieStr)["unb"] + a.mu.Lock() + if userID == "" { + userID = a.UserID + } + a.deviceID = protocol.GenerateDeviceID(userID) + a.mu.Unlock() +} + // UpdateCookie 用外部刷新得到的新 cookie 更新运行时状态。 func (a *Account) UpdateCookie(cookieStr string) { if strings.TrimSpace(cookieStr) == "" { @@ -1346,9 +1379,15 @@ func (a *Account) UpdateCookie(cookieStr string) { } } a.replaceCookieStr(cookieStr) - // Updating credentials does not close a healthy connection. Clearing the - // in-memory and persisted token makes the next reconnect authenticate from - // this Cookie snapshot instead of reusing a token issued for the old one. + a.rotateDeviceID(cookieStr) + // 官网静默续期成功会 location.reload()。本地收到外部 Cookie 更新时关闭 + // 健康连接,让主循环立即用新 Cookie、新 device ID 和新 token 重建。 a.clearCurrentToken() a.clearTokenCache(context.Background()) + a.mu.Lock() + conn := a.conn + a.mu.Unlock() + if conn != nil { + _ = conn.Close() + } } diff --git a/internal/engine/account_extra_test.go b/internal/engine/account_extra_test.go index f07a485..aff8e86 100644 --- a/internal/engine/account_extra_test.go +++ b/internal/engine/account_extra_test.go @@ -275,8 +275,8 @@ func TestTryAPIRenewSuccessShortCircuitsRecovery(t *testing.T) { if saved != "unb=123; _m_h5_tk=tk_2;" { t.Fatalf("DB cookie 未更新: %q", saved) } - if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID { - t.Fatalf("接口续期后应清 token 并保留 device ID: tk=%+v err=%v", tk, err) + if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" { + t.Fatalf("接口续期后应清 token;数据库中的旧 device ID 不再参与运行时身份: tk=%+v err=%v", tk, err) } } @@ -306,8 +306,8 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) { if saved != "unb=123; _m_h5_tk=partial;" { t.Fatalf("部分 cookie 应先保存到 DB: %q", saved) } - if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID { - t.Fatalf("部分 cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err) + if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" { + t.Fatalf("部分 cookie 更新后应清 token: tk=%+v err=%v", tk, err) } } diff --git a/internal/engine/ai.go b/internal/engine/ai.go index 42ec1dd..0737833 100644 --- a/internal/engine/ai.go +++ b/internal/engine/ai.go @@ -54,6 +54,11 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult, if err != nil || cfg == nil || !cfg.AIEnabled { return nil, nil // 未启用 AI } + // AI 设置面向砍价场景。普通未命中消息继续交给默认回复,避免 AI + // 抢答问候、售后等与砍价无关的消息。 + if !bargainMessageRe.MatchString(strings.ToLower(m.Text)) { + return nil, nil + } aiCfg, err := a.globalAIConfig(ctx) if err != nil { return nil, fmt.Errorf("读取全局 AI 配置失败: %w", err) diff --git a/internal/engine/ai_test.go b/internal/engine/ai_test.go index 413728e..5161643 100644 --- a/internal/engine/ai_test.go +++ b/internal/engine/ai_test.go @@ -76,7 +76,7 @@ func TestAIReply_DisabledReturnsNil(t *testing.T) { a := NewAIReplier("cid", s, nil) // 无配置记录 → 未启用 → nil。 - res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1")) + res, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1")) if err != nil || res != nil { t.Fatalf("未配置应返回 nil,nil: res=%+v err=%v", res, err) } @@ -97,7 +97,7 @@ func TestAIReply_NoAPIKeyReturnsNil(t *testing.T) { s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`) a := NewAIReplier("cid", s, nil) - res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1")) + res, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1")) if err != nil || res != nil { t.Fatalf("无 APIKey 应返回 nil,nil: res=%+v err=%v", res, err) } @@ -137,7 +137,7 @@ func TestAIReply_HTTPErrorDegrades(t *testing.T) { s.Settings.Set(ctx, "ai_api_url", srv.URL) a := NewAIReplier("cid", s, nil) - res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1")) + res, err := a.Reply(ctx, chatMsg("还能优惠吗", "item1", "chat1")) if err == nil { t.Fatalf("HTTP 500 应返回错误,got res=%+v", res) } @@ -165,7 +165,7 @@ func TestAIReply_EmptyChoicesReturnsNil(t *testing.T) { s.Settings.Set(ctx, "ai_api_url", srv.URL) a := NewAIReplier("cid", s, nil) - res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1")) + res, err := a.Reply(ctx, chatMsg("可以便宜一点吗", "item1", "chat1")) if err != nil || res != nil { t.Fatalf("空 choices 应返回 nil,nil: res=%+v err=%v", res, err) } @@ -182,7 +182,7 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) { s.Settings.Set(ctx, "ai_api_url", srv.URL) a := NewAIReplier("cid", s, nil) - res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1")) + res, err := a.Reply(ctx, chatMsg("最低多少钱", "item1", "chat1")) if err != nil { t.Fatalf("成功调用不应报错: %v", err) } @@ -191,6 +191,20 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) { } } +func TestAIReply_NonBargainMessageFallsThrough(t *testing.T) { + s, cleanup := newAIStore(t) + defer cleanup() + ctx := context.Background() + s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`) + s.Settings.Set(ctx, "ai_api_key", "sk-test") + s.Settings.Set(ctx, "ai_api_url", "http://127.0.0.1:1") + + res, err := NewAIReplier("cid", s, nil).Reply(ctx, chatMsg("在吗,什么时候发货", "item1", "chat1")) + if err != nil || res != nil { + t.Fatalf("非砍价消息应交给默认回复: res=%+v err=%v", res, err) + } +} + // TestGlobalAIConfig 默认值兜底 + 显式设置覆盖。 func TestGlobalAIConfig(t *testing.T) { s, cleanup := newAIStore(t) diff --git a/internal/engine/keepalive_test.go b/internal/engine/keepalive_test.go index f508cd7..8bd53bb 100644 --- a/internal/engine/keepalive_test.go +++ b/internal/engine/keepalive_test.go @@ -118,8 +118,10 @@ func (s *statusMtop) CheckLoginStatusContext(context.Context, string) (*mtop.Log return s.result, s.err } -// TestAcquireToken_CacheHitSkipsMtop 缓存命中且未过期时跳过 mtop 调用。 -func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) { +// TestAcquireToken_CacheHitStillFetchesFreshToken matches the official web +// client: every connection attempt calls login.token even when a persisted +// token has not reached its advertised expiry. +func TestAcquireToken_CacheHitStillFetchesFreshToken(t *testing.T) { mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}} acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() @@ -129,11 +131,11 @@ func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) { if err != nil { t.Fatalf("acquireToken: %v", err) } - if token != "cached-tok" { - t.Fatalf("应使用缓存 token,got %s", token) + if token != "tok-mtop" { + t.Fatalf("应使用新获取 token,got %s", token) } - if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 { - t.Fatalf("缓存命中不应调用 mtop,got %d", calls) + if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 { + t.Fatalf("每次连接都应调用 mtop,got %d", calls) } if !strings.Contains(cookies, "_m_h5_tk=tk_1") { t.Fatalf("缓存命中应返回其绑定的 Cookie: %q", cookies) @@ -160,7 +162,7 @@ func TestAcquireToken_RejectsCacheBoundToDifferentCookie(t *testing.T) { } } -func TestAcquireRuntimeTokenPreservesMemoryTokenWithoutDatabaseCache(t *testing.T) { +func TestAcquireRuntimeTokenReplacesMemoryToken(t *testing.T) { mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}} acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() @@ -168,11 +170,11 @@ func TestAcquireRuntimeTokenPreservesMemoryTokenWithoutDatabaseCache(t *testing. _ = store.Tokens.Clear(context.Background(), "cid") token, _, err := acc.acquireRuntimeToken(context.Background()) - if err != nil || token != "runtime-token" { + if err != nil || token != "tok-mtop" { t.Fatalf("runtime token=%q err=%v", token, err) } - if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 { - t.Fatalf("网络重连复用内存 token 时不应调用 mtop,calls=%d", calls) + if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 { + t.Fatalf("网络重连应获取新 token,calls=%d", calls) } } @@ -218,6 +220,7 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) { acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() + oldDeviceID := acc.deviceID saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix()) res := acc.tryLoginStatusCheck(context.Background()) if !res.recovered || res.riskRequired { @@ -230,8 +233,8 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) { if err != nil || saved != newCookie { t.Fatalf("DB Cookie 未更新: got %q err=%v", saved, err) } - if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID { - t.Fatalf("Cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err) + if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID { + t.Fatalf("Cookie 更新后应清 token 并为页面重载轮换 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err) } } @@ -266,6 +269,7 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) { acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"}) defer cleanup() // 预置旧 session 的 token 缓存。 + oldDeviceID := acc.deviceID saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix()) // 外部更新 DB cookie(模拟重新扫码),userID=0 复用现有 user_id。 newCookie := "unb=123; _m_h5_tk=newtk_2; sgcookie=abc" @@ -276,9 +280,9 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) { if got := acc.CurrentCookieStr(); got != newCookie { t.Fatalf("应采纳 DB 新 cookie,got %s", got) } - // 新 cookie 对应新 session,旧 token 应清除但 device ID 必须保留。 - if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID { - t.Fatalf("cookie 变更后应清 token 并保留 device ID: tk=%+v err=%v", tk, err) + // 新 cookie 对应官网页面重载:旧 token 清除,运行时 device ID 轮换。 + if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID { + t.Fatalf("cookie 变更后应清 token 并轮换运行时 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err) } } diff --git a/internal/engine/run_test.go b/internal/engine/run_test.go index 18c06bc..0ec6b5d 100644 --- a/internal/engine/run_test.go +++ b/internal/engine/run_test.go @@ -3,6 +3,7 @@ package engine import ( "context" "errors" + "fmt" "log/slog" "path/filepath" "sync" @@ -58,10 +59,33 @@ func (f *fakeFailTokenMtop) RefreshTokenWithDeviceIDContext(context.Context, str return nil, f.err } +type sequencedTokenMtop struct { + fakeRunMtop + mu sync.Mutex + devices []string + cookies []string + calls int +} + +func (s *sequencedTokenMtop) RefreshTokenWithDeviceIDContext(_ context.Context, cookieStr, deviceID string) (*mtop.RefreshResult, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.calls++ + s.devices = append(s.devices, deviceID) + s.cookies = append(s.cookies, cookieStr) + return &mtop.RefreshResult{ + AccessToken: fmt.Sprintf("fresh-%d", s.calls), + AccessTokenExpireAt: time.Now().Add(time.Hour).Unix(), + }, nil +} + // fakeWSConn 实现 WSConn,可控地投递消息并阻塞到 ctx 取消。 type fakeWSConn struct { mu sync.Mutex closed bool + registerErr error + registeredDID string + registeredTok string sentTexts []string sentImages []string heartbeatDone chan struct{} @@ -72,6 +96,15 @@ type fakeWSConn struct { recvErr error } +func (f *fakeWSConn) Register(_ context.Context, deviceID, accessToken string) error { + f.mu.Lock() + f.registeredDID = deviceID + f.registeredTok = accessToken + err := f.registerErr + f.mu.Unlock() + return err +} + func (f *fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error { <-ctx.Done() if f.heartbeatDone != nil { @@ -221,13 +254,12 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) { time.Sleep(50 * time.Millisecond) } - // 初始 token 应通过 ws.Config.AccessToken 传给 Dial(非 SetAccessToken)。 - d := acc.wsDialer.(*fakeDialer) - d.mu.Lock() - gotToken := d.lastCfg.AccessToken == "tok-1" - d.mu.Unlock() + // token 必须在握手成功后通过 Register 发送,而不是在 Dial 前获得。 + conn.mu.Lock() + gotToken := conn.registeredTok == "tok-1" + conn.mu.Unlock() if !gotToken { - t.Fatal("Dial 未收到 ws.Config.AccessToken=tok-1") + t.Fatal("Register 未收到 token=tok-1") } // 取消 ctx → Run 应退出。 @@ -272,7 +304,7 @@ func TestRun_DialFailureIncrementsFailures(t *testing.T) { } } -// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并复用当前内存 token。 +// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并重新获取 token。 func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) { mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}} acc, _, _, cleanup := newRunAccount(t, mtopClient) @@ -311,12 +343,52 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) { case <-time.After(3 * time.Second): t.Fatal("重连后 ctx 取消 Run 未退出") } - if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 { - t.Fatalf("正常重连应复用内存 token,不应重复请求 mtop: calls=%d", calls) + if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 { + t.Fatalf("正常重连应重新请求 mtop: calls=%d", calls) } } -func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) { +func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) { + mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "unused"}} + acc, _, _, cleanup := newRunAccount(t, mtopClient) + defer cleanup() + dialer := &fakeDialer{results: []dialResult{ + {conn: &fakeWSConn{recvBlock: false}}, + {conn: &fakeWSConn{recvBlock: true}}, + }} + acc.wsDialer = dialer + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- acc.Run(ctx) }() + waitForDialCalls(t, dialer, 2) + cancel() + <-done + + dialer.mu.Lock() + conns := append([]*fakeWSConn(nil), dialer.conns...) + dialer.mu.Unlock() + if len(conns) < 2 { + t.Fatalf("dial conns=%d want>=2", len(conns)) + } + conns[0].mu.Lock() + firstToken := conns[0].registeredTok + conns[0].mu.Unlock() + conns[1].mu.Lock() + secondToken := conns[1].registeredTok + conns[1].mu.Unlock() + if firstToken != "fresh-1" || secondToken != "fresh-2" { + t.Fatalf("reconnect tokens=%v", []string{firstToken, secondToken}) + } + mtopClient.mu.Lock() + devices := append([]string(nil), mtopClient.devices...) + mtopClient.mu.Unlock() + if len(devices) != 2 || devices[0] == "" || devices[0] != devices[1] { + t.Fatalf("device IDs must remain stable: %v", devices) + } +} + +func TestRun_EstablishedNetworkErrorClearsConnectionToken(t *testing.T) { mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}} acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() @@ -340,15 +412,15 @@ func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) { currentToken := acc.currentToken networkFailures := acc.networkFailures acc.mu.Unlock() - if networkFailures != 1 || currentToken != "tok-1" { + if networkFailures != 1 || currentToken != "" { cancel() <-done - t.Fatalf("网络断线不应清空内存 token: failures=%d token=%q", networkFailures, currentToken) + t.Fatalf("网络断线应结束当前 token 生命周期: failures=%d token=%q", networkFailures, currentToken) } - if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "tok-1" { + if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "" { cancel() <-done - t.Fatalf("网络断线不应删除 token 缓存: cached=%+v err=%v", cached, err) + t.Fatalf("网络断线应清除 token 缓存: cached=%+v err=%v", cached, err) } cancel() select { @@ -366,7 +438,7 @@ func TestRun_InvalidRegTokenFetchesOneFreshTokenImmediately(t *testing.T) { acc, _, _, cleanup := newRunAccount(t, mtopClient) defer cleanup() dialer := &fakeDialer{results: []dialResult{ - {err: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}}, + {conn: &fakeWSConn{registerErr: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}}}, {conn: &fakeWSConn{recvBlock: true}}, }} acc.wsDialer = dialer @@ -384,7 +456,7 @@ func TestRun_InvalidRegTokenFetchesOneFreshTokenImmediately(t *testing.T) { } func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) { - mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "token"}} + mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "token"}} acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() newCookie := "unb=123; _m_h5_tk=db-renewed_2; cookie2=new" @@ -406,16 +478,13 @@ func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) { cancel() <-done - dialer.mu.Lock() - configs := append([]ws.Config(nil), dialer.configs...) - dialer.mu.Unlock() - if len(configs) < 2 { - t.Fatalf("dial configs=%d want>=2", len(configs)) + mtopClient.mu.Lock() + cookies := append([]string(nil), mtopClient.cookies...) + mtopClient.mu.Unlock() + if len(cookies) < 2 || cookies[1] != newCookie { + t.Fatalf("second token Cookie=%v want=%q", cookies, newCookie) } - if configs[1].CookieStr != newCookie { - t.Fatalf("second dial Cookie=%q want=%q", configs[1].CookieStr, newCookie) - } - if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 { + if calls := mtopClient.calls; calls != 2 { t.Fatalf("Cookie change should invalidate token for reconnect, calls=%d", calls) } } @@ -462,6 +531,7 @@ func TestRun_DisabledAccountExits(t *testing.T) { func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) { acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial}) defer cleanup() + acc.wsDialer = &fakeDialer{results: []dialResult{{conn: &fakeWSConn{recvBlock: true}}}} h := &failingRefreshHandler{} acc.handler = h acc.mu.Lock() diff --git a/internal/notify/notifier.go b/internal/notify/notifier.go index 5d7fad7..44e9c34 100644 --- a/internal/notify/notifier.go +++ b/internal/notify/notifier.go @@ -597,15 +597,15 @@ func (n *Notifier) sendTelegram(cfg map[string]any, message string) error { func (n *Notifier) sendEmail(cfg map[string]any, message string) error { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - server := n.configOrSetting(ctx, cfg, "smtp_server", "") - port := n.configOrSetting(ctx, cfg, "smtp_port", "587") - user := n.configOrSetting(ctx, cfg, "smtp_user", "") - pass := n.configOrSetting(ctx, cfg, "smtp_password", "") - useTLS := parseConfigBool(n.configOrSetting(ctx, cfg, "smtp_use_tls", "true"), true) - useSSL := parseConfigBool(n.configOrSetting(ctx, cfg, "smtp_use_ssl", "false"), false) - fromAddress := n.configOrSetting(ctx, cfg, "smtp_from_address", "") - fromName := n.configOrSetting(ctx, cfg, "smtp_from_name", "") - legacyFrom := n.configOrSetting(ctx, cfg, "smtp_from", "") + server := n.smtpConfigValue(ctx, cfg, "smtp_server", "") + port := n.smtpConfigValue(ctx, cfg, "smtp_port", "587") + user := n.smtpConfigValue(ctx, cfg, "smtp_user", "") + pass := n.smtpConfigValue(ctx, cfg, "smtp_password", "") + useTLS := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_tls", "true"), true) + useSSL := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_ssl", "false"), false) + fromAddress := n.smtpConfigValue(ctx, cfg, "smtp_from_address", "") + fromName := n.smtpConfigValue(ctx, cfg, "smtp_from_name", "") + legacyFrom := n.smtpConfigValue(ctx, cfg, "smtp_from", "") to := strOr(cfg, "to_email", strOr(cfg, "email", "")) if server == "" || user == "" || to == "" { return fmt.Errorf("邮件配置不完整:请配置系统 SMTP 或在邮件渠道中覆盖 SMTP,并填写收件邮箱") @@ -751,6 +751,27 @@ func (n *Notifier) configOrSetting(ctx context.Context, cfg map[string]any, key, return fallbackValue } +// smtpConfigValue keeps legacy per-field fallback behavior for existing rows, +// while new rows use an explicit all-system or all-channel SMTP mode. +func (n *Notifier) smtpConfigValue(ctx context.Context, cfg map[string]any, key, fallbackValue string) string { + modeValue, hasExplicitMode := cfg["use_custom_smtp"] + if !hasExplicitMode { + return n.configOrSetting(ctx, cfg, key, fallbackValue) + } + if parseConfigBool(fmt.Sprintf("%v", modeValue), false) { + if value := strings.TrimSpace(strOr(cfg, key, "")); value != "" { + return value + } + return fallbackValue + } + if n.store != nil && n.store.Settings != nil { + if value, err := n.store.Settings.Get(ctx, key); err == nil && strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return fallbackValue +} + // postJSON 通用 JSON POST。 func (n *Notifier) postJSON(url string, payload any) error { body, err := json.Marshal(payload) diff --git a/internal/notify/notifier_channels_test.go b/internal/notify/notifier_channels_test.go index 0f63d7a..eb28877 100644 --- a/internal/notify/notifier_channels_test.go +++ b/internal/notify/notifier_channels_test.go @@ -568,6 +568,33 @@ func TestSendEmail_UsesSystemSMTPFallback(t *testing.T) { } } +func TestSMTPConfigValueUsesExclusiveExplicitModes(t *testing.T) { + store, cleanup := newNotifyStoreBare(t) + defer cleanup() + ctx := context.Background() + if err := store.Settings.Set(ctx, "smtp_server", "system.example.com"); err != nil { + t.Fatal(err) + } + n := New("cid", store, nil) + + if got := n.smtpConfigValue(ctx, map[string]any{ + "use_custom_smtp": false, + "smtp_server": "stale-channel.example.com", + }, "smtp_server", ""); got != "system.example.com" { + t.Fatalf("system mode mixed in channel override: %q", got) + } + if got := n.smtpConfigValue(ctx, map[string]any{ + "use_custom_smtp": true, + }, "smtp_server", ""); got != "" { + t.Fatalf("custom mode inherited system value: %q", got) + } + if got := n.smtpConfigValue(ctx, map[string]any{ + "smtp_server": "legacy-channel.example.com", + }, "smtp_server", ""); got != "legacy-channel.example.com" { + t.Fatalf("legacy channel override compatibility lost: %q", got) + } +} + // TestSendEmail_IncompleteConfig 配置不完整应报错。 func TestSendEmail_IncompleteConfig(t *testing.T) { n := New("cid", nil, nil) diff --git a/internal/renewal/scheduler.go b/internal/renewal/scheduler.go index e2601bb..02fe783 100644 --- a/internal/renewal/scheduler.go +++ b/internal/renewal/scheduler.go @@ -46,6 +46,10 @@ type AccountStarter interface { Start(ctx context.Context, cookieID, cookieValue string) error } +type accountRestarter interface { + Restart(ctx context.Context, cookieID string) error +} + type BrowserRenewer interface { BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) @@ -101,7 +105,9 @@ func (s *Scheduler) Run(ctx context.Context) { return } go s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew) - go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, true, apiCookieRenewInterval, s.executeAPICookieRenew) + // 官网静默插件只在页面/账号运行时启动时执行,不做每小时轮询。保留 + // 调度器入口供显式兼容配置使用,但默认关闭。 + go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, false, apiCookieRenewInterval, s.executeAPICookieRenew) go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeBrowserCookieRefresh) } @@ -165,8 +171,7 @@ func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account d } updated := cookierefresh.ChangedCookieNames(account.Value, res.UpdatedCookies) if res.UpdatedCookies != "" && res.UpdatedCookies != account.Value { - metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON) - if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil { + if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, res.UpdatedCookies, account.MetadataJSON, time.Now().Unix()); err != nil { s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated, time.Since(started)) return } @@ -195,7 +200,13 @@ func (s *Scheduler) executeAPICookieRenew(ctx context.Context) { func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) { credentialUnlock := s.store.LockAccountCredentials(account.ID) - defer credentialUnlock() + shouldRestart := false + defer func() { + credentialUnlock() + if shouldRestart { + s.restartAccount(ctx, account.ID) + } + }() account = s.reloadRenewalAccount(ctx, account) started := time.Now() res, err := s.renewAPI(ctx, account.Value) @@ -215,10 +226,17 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou stepDetails = append(stepDetails, fmt.Sprintf("result: success=%v skipped=%v reason=%s", res.Success, res.Skipped, res.SkipReason)) updated := cookierefresh.ChangedCookieNames(account.Value, res.NewCookies) if res.NewCookies != "" && res.NewCookies != account.Value { - if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)) { + snapshot := cookierefresh.SnapshotFromMetadata(account.MetadataJSON) + if len(snapshot) == 0 { + snapshot = cookierefresh.SnapshotFromCookieString(account.Value, ".goofish.com") + } + snapshot = cookierefresh.ApplySetCookies(snapshot, apirenew.SilentHasLoginURL, res.SetCookies, time.Now()) + metadata := cookierefresh.MetadataWithSnapshot(account.MetadataJSON, snapshot) + if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, metadata) { s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount}) return } + shouldRestart = account.Enabled && res.Success } status := "failed" if res.Skipped { @@ -288,7 +306,13 @@ func (s *Scheduler) executeBrowserCookieRefresh(ctx context.Context) { func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string, account db.RenewalAccount, schedule db.CookieRefreshSchedule) { credentialUnlock := s.store.LockAccountCredentials(account.ID) - defer credentialUnlock() + shouldRestart := false + defer func() { + credentialUnlock() + if shouldRestart { + s.restartAccount(ctx, account.ID) + } + }() account = s.reloadRenewalAccount(ctx, account) started := time.Now() if s.browser == nil { @@ -326,6 +350,8 @@ func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string, s.logger.Warn("cookies_refresh 启动账号失败", "account", account.ID, "err", err) } } + } else if len(updated) > 0 { + shouldRestart = true } nextExpire := time.Now().Add(browserSuccessDelay()).Unix() schedule.Disabled = false @@ -350,6 +376,16 @@ func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string, }) } +func (s *Scheduler) restartAccount(ctx context.Context, cookieID string) { + restarter, ok := s.starter.(accountRestarter) + if !ok { + return + } + if err := restarter.Restart(ctx, cookieID); err != nil { + s.logger.Warn("Cookie 更新后重启账号失败", "account", cookieID, "err", err) + } +} + func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string) (*apirenew.Result, error) { runCtx, cancel := context.WithTimeout(ctx, 90*time.Second) defer cancel() diff --git a/internal/renewal/scheduler_test.go b/internal/renewal/scheduler_test.go index 0b73781..5b43059 100644 --- a/internal/renewal/scheduler_test.go +++ b/internal/renewal/scheduler_test.go @@ -360,7 +360,7 @@ func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { requests.Add(1) http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)}) - _, _ = w.Write([]byte(`{"content":{"success":true},"marker":"single-silent"}`)) + _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}},"marker":"single-silent"}`)) })) defer srv.Close() diff --git a/internal/server/automation_handlers.go b/internal/server/automation_handlers.go index a81d61f..dc1319f 100644 --- a/internal/server/automation_handlers.go +++ b/internal/server/automation_handlers.go @@ -266,8 +266,8 @@ func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, r if act.DeliveryCount <= 0 { act.DeliveryCount = 1 } - if act.DelaySeconds < 0 || act.DelaySeconds > 86400 { - return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 86400 秒之间") + if act.DelaySeconds < 0 || act.DelaySeconds > 3600 { + return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 3600 秒之间") } if act.ConfigJSON == "" { act.ConfigJSON = "{}" diff --git a/internal/server/card_batch_handlers.go b/internal/server/card_batch_handlers.go index 68173d8..314c17d 100644 --- a/internal/server/card_batch_handlers.go +++ b/internal/server/card_batch_handlers.go @@ -92,8 +92,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) { continue } delaySeconds := atoiPublishDefault(firstImportString(m, "delay_seconds", "延迟秒"), 0) - if delaySeconds < 0 || delaySeconds > 86400 { - results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "延时发货必须在 0 到 86400 秒之间"}) + if delaySeconds < 0 || delaySeconds > 3600 { + results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "延时发货必须在 0 到 3600 秒之间"}) failed++ continue } diff --git a/internal/server/card_handlers.go b/internal/server/card_handlers.go index 4920486..35758f8 100644 --- a/internal/server/card_handlers.go +++ b/internal/server/card_handlers.go @@ -136,8 +136,8 @@ func decodeCard(r *http.Request) (*db.CardFull, error) { default: return nil, errStr("类型必须为 text、data、image 或 api") } - if req.DelaySeconds < 0 || req.DelaySeconds > 86400 { - return nil, errStr("延时发货必须在 0 到 86400 秒之间") + if req.DelaySeconds < 0 || req.DelaySeconds > 3600 { + return nil, errStr("延时发货必须在 0 到 3600 秒之间") } switch req.Type { case "text": diff --git a/internal/server/cookie_handlers.go b/internal/server/cookie_handlers.go index 97724d8..eab2bf7 100644 --- a/internal/server/cookie_handlers.go +++ b/internal/server/cookie_handlers.go @@ -13,6 +13,8 @@ import ( "xianyu-go/internal/auth" "xianyu-go/internal/db" "xianyu-go/internal/engine" + "xianyu-go/internal/xianyu/cookierefresh" + xrenew "xianyu-go/internal/xianyu/renew" ) // mountCookies 账号 cookie 管理端点。 @@ -24,6 +26,8 @@ func (s *Server) mountCookies(r chi.Router) { r.Put("/cookies/{cid}", s.updateCookie) r.Put("/cookies/{cid}/login-info", s.updateCookieLoginInfo) r.Put("/cookies/{cid}/settings", s.updateCookieSettings) + r.Get("/cookies/{cid}/long-login", s.getLongLoginSettings) + r.Put("/cookies/{cid}/long-login", s.setLongLoginSettings) r.Post("/cookies/{cid}/refresh-profile", s.refreshCookieProfile) r.Get("/cookie/{cid}/details", s.getCookieDetails) r.Put("/cookies/{cid}/status", s.setCookieStatus) @@ -35,6 +39,74 @@ func (s *Server) mountCookies(r chi.Router) { r.Get("/cookies/{cid}/pause-duration", s.getCookiePauseDuration) } +func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + detail, ok := s.requireCookieOwner(w, r, cid) + if !ok { + return + } + result, err := s.CookieRenew.QueryLongLoginSettings(r.Context(), detail.Value) + if err != nil { + writeErr(w, http.StatusBadGateway, err.Error()) + return + } + if err := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.QueryLoginSettingsURL); err != nil { + writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败") + return + } + writeJSON(w, http.StatusOK, result) +} + +func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + detail, ok := s.requireCookieOwner(w, r, cid) + if !ok { + return + } + var req struct { + Enabled *bool `json:"enabled"` + } + if err := decodeJSON(r, &req); err != nil || req.Enabled == nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + result, err := s.CookieRenew.SetLongLoginSettings(r.Context(), detail.Value, *req.Enabled) + if err != nil { + writeErr(w, http.StatusBadGateway, err.Error()) + return + } + if err := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.SetLoginSettingsURL); err != nil { + writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败") + return + } + writeJSON(w, http.StatusOK, result) +} + +func (s *Server) persistLongLoginCookies(ctx context.Context, detail *db.CookieDetail, result *xrenew.LongLoginSettings, requestURL string) error { + if result == nil || result.NewCookies == "" || result.NewCookies == detail.Value { + return nil + } + snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON) + if len(snapshot) == 0 { + snapshot = cookierefresh.SnapshotFromCookieString(detail.Value, ".goofish.com") + } + snapshot = cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now()) + metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) + if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); err != nil { + s.Logger.Warn("保存长登录 Cookie 失败", "cookie_id", detail.ID, "err", err) + return err + } + if s.Store.Tokens != nil { + _ = s.Store.Tokens.Clear(ctx, detail.ID) + } + if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, detail.ID) { + if err := s.Manager.Restart(ctx, detail.ID); err != nil { + s.Logger.Warn("保存登录信息更新后重启账号失败", "cookie_id", detail.ID, "err", err) + } + } + return nil +} + type updateCookieSettingsRequest struct { Cookie *string `json:"cookie"` Remark *string `json:"remark"` diff --git a/internal/server/cookie_handlers_test.go b/internal/server/cookie_handlers_test.go index e2d1ee2..6548894 100644 --- a/internal/server/cookie_handlers_test.go +++ b/internal/server/cookie_handlers_test.go @@ -11,8 +11,68 @@ import ( "time" "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/cookierefresh" + xrenew "xianyu-go/internal/xianyu/renew" ) +func TestLongLoginSettingsProxyAndPersistCookieSnapshot(t *testing.T) { + passport := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("fromSite") != "77" || r.URL.Query().Get("appName") != "xianyu" || r.URL.Query().Get("bizEntrance") != "web" { + t.Fatalf("query=%s", r.URL.RawQuery) + } + if strings.Contains(r.URL.Path, "set") { + if err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" { + t.Fatalf("form=%v err=%v", r.Form, err) + } + } + w.Header().Add("Set-Cookie", "havana_lgc_exp=4102444800000; Domain=.goofish.com; Path=/; Secure; HttpOnly; SameSite=None") + _, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`)) + })) + defer passport.Close() + + srv, store, cleanup := newTestServer(t) + defer cleanup() + srv.CookieRenew = xrenew.Service{ + HTTPClient: passport.Client(), + QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do", + SetLoginSettingsURL: passport.URL + "/setLoginSettings.do", + } + h := srv.Router() + session := loginHelper(t, h) + + for _, request := range []*http.Request{ + httptest.NewRequest(http.MethodGet, "/cookies/acc1/long-login", nil), + httptest.NewRequest(http.MethodPut, "/cookies/acc1/long-login", strings.NewReader(`{"enabled":true}`)), + } { + request.AddCookie(session) + recorder := httptest.NewRecorder() + h.ServeHTTP(recorder, request) + if recorder.Code != http.StatusOK { + t.Fatalf("%s status=%d body=%s", request.Method, recorder.Code, recorder.Body.String()) + } + var result xrenew.LongLoginSettings + if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || !result.CanOpenLongLogin || !result.Enabled { + t.Fatalf("result=%+v err=%v", result, err) + } + } + + detail, err := store.Cookies.GetDetails(context.Background(), "acc1") + if err != nil || !strings.Contains(detail.Value, "havana_lgc_exp=4102444800000") { + t.Fatalf("cookie detail=%+v err=%v", detail, err) + } + snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON) + var longLoginCookie *cookierefresh.BrowserCookie + for i := range snapshot { + if snapshot[i].Name == "havana_lgc_exp" { + longLoginCookie = &snapshot[i] + break + } + } + if longLoginCookie == nil || longLoginCookie.Domain != ".goofish.com" || !longLoginCookie.Secure || !longLoginCookie.HTTPOnly { + t.Fatalf("未保留 Set-Cookie 属性: %+v", snapshot) + } +} + // TestListCookies 列表 cookie_id。 func TestListCookies(t *testing.T) { srv, _, cleanup := newTestServer(t) diff --git a/internal/server/handler_errors_test.go b/internal/server/handler_errors_test.go index 22d4012..8975334 100644 --- a/internal/server/handler_errors_test.go +++ b/internal/server/handler_errors_test.go @@ -78,7 +78,7 @@ func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) { for _, body := range []string{ `{"name":"API 卡密","type":"api","enabled":true}`, `{"name":"非法类型","type":"unknown","enabled":true}`, - `{"name":"延时错误","type":"text","text_content":"x","delay_seconds":86401,"enabled":true}`, + `{"name":"延时错误","type":"text","text_content":"x","delay_seconds":3601,"enabled":true}`, `{"name":"空文本","type":"text","text_content":" ","enabled":true}`, `{"name":"空库存","type":"data","data_content":"\n","enabled":true}`, `{"name":"空图片","type":"image","image_url":"","enabled":true}`, diff --git a/internal/server/item_handlers.go b/internal/server/item_handlers.go index 72d4b51..c61dfa9 100644 --- a/internal/server/item_handlers.go +++ b/internal/server/item_handlers.go @@ -267,6 +267,14 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusInternalServerError, "查询失败") return } + cookieID := strings.TrimSpace(r.URL.Query().Get("cookie_id")) + if cookieID != "" { + if _, ok := all[cookieID]; !ok { + writeErr(w, http.StatusForbidden, "无权限操作该账号") + return + } + all = map[string]string{cookieID: all[cookieID]} + } result := []map[string]any{} for cid := range all { items, _ := s.Store.Items.AllForCookie(r.Context(), cid) @@ -307,6 +315,11 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) { s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err) } } + detailCookies := cookieValue + if res.UpdatedCookies != "" { + detailCookies = res.UpdatedCookies + } + s.enrichSyncedItemMultiSpec(ctx, client, detailCookies, req.CookieID, res.Items) saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items) writeJSON(w, http.StatusOK, map[string]any{ "success": true, @@ -344,6 +357,11 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err) } } + detailCookies := cookieValue + if res.UpdatedCookies != "" { + detailCookies = res.UpdatedCookies + } + s.enrichSyncedItemMultiSpec(ctx, client, detailCookies, req.CookieID, res.Items) saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items) writeJSON(w, http.StatusOK, map[string]any{ "success": true, @@ -391,6 +409,11 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m ItemDetail: item.ItemDetail, }) if err == nil { + if item.IsMultiSpec { + if multiErr := s.Store.Items.SetMultiSpec(ctx, cookieID, item.ID, true); multiErr != nil && s.Logger != nil { + s.Logger.Warn("保存商品多规格状态失败", "cookie_id", cookieID, "item_id", item.ID, "err", multiErr) + } + } saved++ } else if s.Logger != nil { s.Logger.Warn("保存商品失败", "cookie_id", cookieID, "item_id", item.ID, "err", err) @@ -399,6 +422,27 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m return saved } +func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) { + fetcher, ok := client.(mtop.ItemDetailFetcher) + if !ok { + return + } + for index := range items { + if items[index].IsMultiSpec || s.Store.Items.IsMultiSpec(ctx, cookieID, items[index].ID) { + items[index].IsMultiSpec = true + continue + } + isMultiSpec, err := fetcher.DetectItemMultiSpec(ctx, cookies, items[index].ID) + if err != nil { + if s.Logger != nil { + s.Logger.Warn("识别商品多规格状态失败", "cookie_id", cookieID, "item_id", items[index].ID, "err", err) + } + continue + } + items[index].IsMultiSpec = isMultiSpec + } +} + func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) { cid := chi.URLParam(r, "cookie_id") if _, ok := s.requireCookieOwner(w, r, cid); !ok { diff --git a/internal/server/item_handlers_test.go b/internal/server/item_handlers_test.go index 4650a6b..40b182c 100644 --- a/internal/server/item_handlers_test.go +++ b/internal/server/item_handlers_test.go @@ -357,6 +357,33 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) { } } +func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) { + srv, store, cleanup := newTestServer(t) + defer cleanup() + srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) { + body := `{"ret":["SUCCESS::调用成功"],"data":{}}` + if strings.Contains(req.URL.String(), "mtop.idle.web.xyh.item.list") { + body = `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"id":"multi-item","title":"多规格商品","detailParams":{"itemId":"multi-item"}}}]}}` + } else if strings.Contains(req.URL.String(), "mtop.taobao.idle.pc.detail") { + body = `{"ret":["SUCCESS::调用成功"],"data":{"multiSKU":true,"skuDO":{"skuList":[{"id":"a"},{"id":"b"}]}}}` + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil + })) + h := srv.Router() + cookie := loginHelper(t, h) + req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(`{"cookie_id":"acc1","page_size":10}`)) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } + item, err := store.Items.Get(context.Background(), "acc1", "multi-item") + if err != nil || !item.IsMultiSpec { + t.Fatalf("item=%+v err=%v", item, err) + } +} + // TestSyncItemsFromAccountFail mtop 返回非成功 → 502。 func TestSyncItemsFromAccountFail(t *testing.T) { srv, _, cleanup := newTestServer(t) @@ -595,6 +622,39 @@ func TestItemCRUD(t *testing.T) { } } +func TestListItemsFiltersByOwnedAccount(t *testing.T) { + srv, store, cleanup := newTestServer(t) + defer cleanup() + ctx := context.Background() + admin, _ := store.Users.GetByUsername(ctx, "admin") + if err := store.Cookies.Save(ctx, "acc2", "unb=456; _m_h5_tk=tk2_1;", admin.ID); err != nil { + t.Fatal(err) + } + _, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','item-a','商品A'),('acc2','item-b','商品B')`) + h := srv.Router() + cookie := loginHelper(t, h) + + req := httptest.NewRequest(http.MethodGet, "/items?cookie_id=acc2", nil) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + var rows []map[string]any + if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &rows) != nil { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } + if len(rows) != 1 || rows[0]["cookie_id"] != "acc2" || rows[0]["item_id"] != "item-b" { + t.Fatalf("rows=%+v", rows) + } + + forbidden := httptest.NewRequest(http.MethodGet, "/items?cookie_id=not-owned", nil) + forbidden.AddCookie(cookie) + forbiddenRec := httptest.NewRecorder() + h.ServeHTTP(forbiddenRec, forbidden) + if forbiddenRec.Code != http.StatusForbidden { + t.Fatalf("status=%d body=%s", forbiddenRec.Code, forbiddenRec.Body.String()) + } +} + // TestItemGetNotFound 不存在商品 404。 func TestItemGetNotFound(t *testing.T) { srv, _, cleanup := newTestServer(t) diff --git a/internal/server/item_publish_batch_handlers.go b/internal/server/item_publish_batch_handlers.go index 44a4c10..0e114e7 100644 --- a/internal/server/item_publish_batch_handlers.go +++ b/internal/server/item_publish_batch_handlers.go @@ -103,7 +103,11 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) return } defaultCookieID := strings.TrimSpace(r.FormValue("default_cookie_id")) - if defaultCookieID != "" && !s.cookieOwnedByUser(r.Context(), sess.UserID, defaultCookieID) { + if defaultCookieID == "" { + writeErr(w, http.StatusBadRequest, "请选择默认发布账号") + return + } + if !s.cookieOwnedByUser(r.Context(), sess.UserID, defaultCookieID) { writeErr(w, http.StatusForbidden, "默认账号不属于当前用户") return } @@ -1111,8 +1115,8 @@ func (s *Server) validatePublishAutomation(ctx context.Context, userID int64, cf if action.DeliveryCount <= 0 { errs = append(errs, prefix+"每件份数必须大于0") } - if action.DelaySeconds < 0 || action.DelaySeconds > 86400 { - errs = append(errs, prefix+"延迟秒必须在 0 到 86400 之间") + if action.DelaySeconds < 0 || action.DelaySeconds > 3600 { + errs = append(errs, prefix+"延迟秒必须在 0 到 3600 之间") } } } diff --git a/internal/server/order_handlers.go b/internal/server/order_handlers.go index 868f4bb..c1d13b5 100644 --- a/internal/server/order_handlers.go +++ b/internal/server/order_handlers.go @@ -2,6 +2,7 @@ package server import ( "context" + "errors" "fmt" "net/http" "strconv" @@ -12,9 +13,11 @@ import ( "xianyu-go/internal/auth" "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" ) const refreshOrderChunkSize = 100 +const maxSoldOrderPages = 100 type refreshTarget struct { OrderID string @@ -162,10 +165,6 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) { } func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) { - if s.Browser == nil { - writeErr(w, http.StatusServiceUnavailable, "浏览器自动化未启用,无法刷新订单") - return - } sess := auth.SessionFromContext(r.Context()) all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) if err != nil { @@ -183,6 +182,32 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) { all = map[string]string{cookieID: value} } + discovered, listUpdated, failed := 0, 0, 0 + results := []map[string]any{} + newOrderIDs := make(map[string]struct{}) + if fetcher, ok := s.mtopClient().(mtop.SoldOrderFetcher); ok { + for cid, cookieValue := range all { + accountDiscovered, accountUpdated, accountNewIDs, discoveryErr := s.discoverSoldOrders(r.Context(), fetcher, cid, cookieValue) + discovered += accountDiscovered + listUpdated += accountUpdated + for orderID := range accountNewIDs { + newOrderIDs[orderID] = struct{}{} + } + result := map[string]any{ + "cookie_id": cid, "stage": "discover", "success": discoveryErr == nil, + "discovered": accountDiscovered, "updated": accountUpdated, + } + if discoveryErr != nil { + failed++ + result["error"] = discoveryErr.Error() + } + results = append(results, result) + } + } else { + failed++ + results = append(results, map[string]any{"stage": "discover", "success": false, "error": "当前 MTop 客户端不支持订单列表发现"}) + } + ordersByCookie := map[string][]refreshTarget{} for cid := range all { for offset := 0; ; offset += 500 { @@ -196,7 +221,8 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) { continue } // 稳定状态无需反复抓取;但历史订单若缺少实付金额,仍需补全详情。 - if isStableOrderStatus(currentStatus) && strings.TrimSpace(row.Amount) != "" { + _, isNewOrder := newOrderIDs[row.OrderID] + if !isNewOrder && isStableOrderStatus(currentStatus) && strings.TrimSpace(row.Amount) != "" { continue } ordersByCookie[cid] = append(ordersByCookie[cid], refreshTarget{OrderID: row.OrderID, CurrentStatus: currentStatus}) @@ -211,18 +237,39 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) { for _, targets := range ordersByCookie { total += len(targets) } + if s.Browser == nil { + message := "订单列表同步完成" + if discovered > 0 { + message = fmt.Sprintf("订单列表同步完成,发现并导入 %d 个新订单", discovered) + } + if total > 0 { + message += fmt.Sprintf(";浏览器自动化未启用,已跳过 %d 个订单的详情补全", total) + } + writeJSON(w, http.StatusOK, map[string]any{ + "success": failed == 0, + "message": message, + "summary": map[string]int{ + "discovered": discovered, "list_updated": listUpdated, "detail_total": total, + "total": total, "updated": 0, "no_change": 0, "failed": failed, + }, + "results": results, + }) + return + } if total == 0 { writeJSON(w, http.StatusOK, map[string]any{ - "success": true, - "message": "没有需要刷新的订单", - "summary": map[string]int{"total": 0, "updated": 0, "no_change": 0, "failed": 0}, - "results": []any{}, + "success": failed == 0, + "message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered), + "summary": map[string]int{ + "discovered": discovered, "list_updated": listUpdated, "detail_total": 0, + "total": 0, "updated": 0, "no_change": 0, "failed": failed, + }, + "results": results, }) return } - updated, noChange, failed := 0, 0, 0 - results := []map[string]any{} + updated, noChange := 0, 0 for cid, targets := range ordersByCookie { cookieValue := all[cid] if cookieValue == "" { @@ -298,13 +345,90 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) { } } writeJSON(w, http.StatusOK, map[string]any{ - "success": true, - "message": "订单刷新完成", - "summary": map[string]int{"total": total, "updated": updated, "no_change": noChange, "failed": failed}, + "success": failed == 0, + "message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered), + "summary": map[string]int{ + "discovered": discovered, "list_updated": listUpdated, "detail_total": total, + "total": total, "updated": updated, "no_change": noChange, "failed": failed, + }, "results": results, }) } +func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, error) { + discovered, updated := 0, 0 + newOrderIDs := make(map[string]struct{}) + for pageNumber := 1; pageNumber <= maxSoldOrderPages; pageNumber++ { + page, err := fetcher.FetchSoldOrdersPage(ctx, cookies, pageNumber, 30) + if err != nil { + return discovered, updated, newOrderIDs, err + } + pageChanged := false + for _, remote := range page.Items { + if normalizedAmount, ok := db.NormalizeOrderAmount(remote.Amount); ok { + remote.Amount = normalizedAmount + } + existing, getErr := s.Store.Orders.Get(ctx, remote.OrderID) + isNew := errors.Is(getErr, db.ErrNotFound) + if getErr != nil && !isNew { + return discovered, updated, newOrderIDs, fmt.Errorf("读取订单 %s 失败: %w", remote.OrderID, getErr) + } + changed := isNew || soldOrderChanged(existing, remote) + status := remote.OrderStatus + if !isNew && status == "unknown" { + status = "" + } + var isBargain *bool + if remote.IsBargain { + value := true + isBargain = &value + } + if err := s.Store.Orders.Upsert(ctx, remote.OrderID, db.OrderUpsertOpts{ + ItemID: remote.ItemID, BuyerID: remote.BuyerID, CookieID: cookieID, + OrderStatus: status, Quantity: remote.Quantity, Amount: remote.Amount, + ReceiverName: remote.ReceiverName, ReceiverPhone: remote.ReceiverPhone, + ReceiverAddr: remote.ReceiverAddr, ReceiverCity: remote.ReceiverCity, + IsBargain: isBargain, + }); err != nil { + return discovered, updated, newOrderIDs, fmt.Errorf("保存订单 %s 失败: %w", remote.OrderID, err) + } + if isNew { + discovered++ + newOrderIDs[remote.OrderID] = struct{}{} + } else if changed { + updated++ + } + pageChanged = pageChanged || changed + } + if !page.NextPage || len(page.Items) == 0 { + return discovered, updated, newOrderIDs, nil + } + // 卖家列表按新到旧排列。一整页都已存在且字段未变化时,更早页也无需重复扫描。 + if !pageChanged { + return discovered, updated, newOrderIDs, nil + } + } + return discovered, updated, newOrderIDs, fmt.Errorf("订单列表超过 %d 页,已停止继续同步", maxSoldOrderPages) +} + +func soldOrderChanged(existing *db.Order, remote mtop.SoldOrder) bool { + if existing == nil { + return true + } + statusChanged := remote.OrderStatus != "" && remote.OrderStatus != "unknown" && + db.NormalizeOrderStatus(existing.OrderStatus) != remote.OrderStatus + return statusChanged || + (remote.ItemID != "" && existing.ItemID != remote.ItemID) || + (remote.BuyerID != "" && existing.BuyerID != remote.BuyerID) || + (remote.Quantity != "" && existing.Quantity != remote.Quantity) || + (remote.Amount != "" && existing.Amount != remote.Amount) || + (remote.ReceiverName != "" && existing.ReceiverName != remote.ReceiverName) || + (remote.ReceiverPhone != "" && existing.ReceiverPhone != remote.ReceiverPhone) || + (remote.ReceiverAddr != "" && existing.ReceiverAddr != remote.ReceiverAddr) || + (remote.ReceiverCity != "" && existing.ReceiverCity != remote.ReceiverCity) || + (remote.IsBargain && existing.IsBargain == 0) +} + func chunkRefreshTargets(targets []refreshTarget, size int) [][]refreshTarget { if size <= 0 { size = refreshOrderChunkSize diff --git a/internal/server/order_handlers_extra_test.go b/internal/server/order_handlers_extra_test.go index 85eb24f..333cc54 100644 --- a/internal/server/order_handlers_extra_test.go +++ b/internal/server/order_handlers_extra_test.go @@ -4,13 +4,14 @@ import ( "context" "encoding/json" "fmt" + "io" "net/http" "net/http/httptest" "strings" "testing" ) -// TestRefreshOrdersNoBrowser 浏览器未启用时应 503。 +// TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。 func TestRefreshOrdersNoBrowser(t *testing.T) { srv, _, cleanup := newTestServer(t) defer cleanup() @@ -21,8 +22,38 @@ func TestRefreshOrdersNoBrowser(t *testing.T) { req.AddCookie(cookie) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) - if rec.Code != http.StatusServiceUnavailable { - t.Fatalf("无浏览器应 503,got %d body=%s", rec.Code, rec.Body.String()) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "订单列表同步完成") { + t.Fatalf("无浏览器仍应同步列表,got %d body=%s", rec.Code, rec.Body.String()) + } +} + +func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) { + srv, store, cleanup := newTestServer(t) + defer cleanup() + srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) { + body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"1","items":[{` + + `"commonData":{"orderId":"sold-new-1","itemId":"item-new","orderStatus":"待发货","inRefund":"false"},` + + `"buyerInfoVO":{"buyerId":"buyer-1","name":"张三","phone":"13800000000","address":"上海市"},` + + `"priceVO":{"totalPrice":"19.90","buyNum":"2"},` + + `"rightVO":{"btnList":[{"tradeAction":"SKIP_PIN"}]}}]}}}` + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil + })) + h := srv.Router() + cookie := loginHelper(t, h) + req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"discovered":1`) { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } + order, err := store.Orders.Get(context.Background(), "sold-new-1") + if err != nil { + t.Fatal(err) + } + if order.CookieID != "acc1" || order.ItemID != "item-new" || order.OrderStatus != "pending_ship" || + order.Amount != "19.90" || order.Quantity != "2" || order.IsBargain != 1 || order.ReceiverName != "张三" { + t.Fatalf("discovered order=%+v", order) } } diff --git a/internal/server/publish_batch_test.go b/internal/server/publish_batch_test.go index aba1e36..d539416 100644 --- a/internal/server/publish_batch_test.go +++ b/internal/server/publish_batch_test.go @@ -122,6 +122,27 @@ func TestPreviewItemPublishBatchNoFile(t *testing.T) { } } +func TestPreviewItemPublishBatchRequiresDefaultAccount(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + cookie := loginHelper(t, h) + + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + file, _ := mw.CreateFormFile("file", "products.csv") + file.Write([]byte("标题,价格,图片\n商品A,12.50,https://example.com/a.png\n")) + _ = mw.Close() + req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf) + req.Header.Set("Content-Type", mw.FormDataContentType()) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "请选择默认发布账号") { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } +} + // TestPreviewItemPublishBatchBadDefaultCookie 默认账号不属于当前用户 403。 func TestPreviewItemPublishBatchBadDefaultCookie(t *testing.T) { srv, _, cleanup := newTestServer(t) diff --git a/internal/server/server.go b/internal/server/server.go index a1cf555..864133c 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -27,6 +27,7 @@ import ( "xianyu-go/internal/webui" "xianyu-go/internal/xianyu/mtop" "xianyu-go/internal/xianyu/qrlogin" + xrenew "xianyu-go/internal/xianyu/renew" ) type qrLoginService interface { @@ -63,6 +64,7 @@ type Server struct { PasswordLogin passwordLoginRunner notifier *notify.Notifier MTop mtop.Client + CookieRenew xrenew.Service QRLogin qrLoginService Logger *slog.Logger WebDir string // 前端静态资源目录(含 index.html) @@ -110,6 +112,7 @@ func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure PasswordLogin: passwordLoginRunnerForBrowser(bm), notifier: notifier, MTop: mtop.NewClient(), + CookieRenew: xrenew.Service{}, QRLogin: qrMgr, Logger: logger, WebDir: webDir, diff --git a/internal/webui/static/assets/icons-vendor-BhUPp6x7.js b/internal/webui/static/assets/icons-vendor-RenKjhri.js similarity index 72% rename from internal/webui/static/assets/icons-vendor-BhUPp6x7.js rename to internal/webui/static/assets/icons-vendor-RenKjhri.js index 2b2be20..20980d2 100644 --- a/internal/webui/static/assets/icons-vendor-BhUPp6x7.js +++ b/internal/webui/static/assets/icons-vendor-RenKjhri.js @@ -23,329 +23,339 @@ import{r as s}from"./react-vendor-DZnRGM0-.js";/** * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const m=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],L1=e("activity",m);/** + */const m=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],P1=e("activity",m);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],V1=e("arrow-right",u);/** + */const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],S1=e("arrow-right",u);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const w=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],P1=e("bell",w);/** + */const w=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],U1=e("bell",w);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const $=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],S1=e("bot",$);/** + */const $=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],E1=e("bot",$);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const N=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],U1=e("box",N);/** + */const N=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],B1=e("box",N);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const f=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],E1=e("check",f);/** + */const f=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],D1=e("check",f);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const b=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],B1=e("chevron-down",b);/** + */const b=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],R1=e("chevron-down",b);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const C=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],D1=e("chevron-left",C);/** + */const q=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],T1=e("chevron-left",q);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const q=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],R1=e("chevron-right",q);/** + */const z=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Z1=e("chevron-right",z);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const z=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],T1=e("circle-alert",z);/** + */const A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],F1=e("circle-alert",A);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Z1=e("circle-check",A);/** + */const C=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],I1=e("circle-check",C);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const j=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],I1=e("circle-dashed",j);/** + */const H=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],K1=e("circle-dashed",H);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const H=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K1=e("clock-3",H);/** + */const j=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],O1=e("clock-3",j);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const L=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],O1=e("clock",L);/** + */const L=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],W1=e("clock",L);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const V=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],W1=e("cloud-upload",V);/** + */const V=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],G1=e("cloud-upload",V);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const P=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],F1=e("code",P);/** + */const P=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q1=e("code",P);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const S=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],G1=e("copy",S);/** + */const S=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],J1=e("copy",S);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const U=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],Q1=e("credit-card",U);/** + */const U=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],X1=e("credit-card",U);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const E=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],J1=e("database",E);/** + */const E=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Y1=e("database",E);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const B=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],X1=e("dollar-sign",B);/** + */const B=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],e0=e("dollar-sign",B);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const D=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Y1=e("external-link",D);/** + */const D=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],a0=e("external-link",D);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const R=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],e0=e("eye-off",R);/** + */const R=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],t0=e("eye-off",R);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const T=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],a0=e("eye",T);/** + */const T=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],o0=e("eye",T);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Z=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],t0=e("file-down",Z);/** + */const Z=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],c0=e("file-down",Z);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const I=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],o0=e("file-text",I);/** + */const F=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],h0=e("file-text",F);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],c0=e("gift",K);/** + */const I=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],s0=e("funnel",I);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const O=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],h0=e("image",O);/** + */const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],n0=e("gift",K);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const W=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],s0=e("key",W);/** + */const O=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],d0=e("image",O);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const F=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],n0=e("layers",F);/** + */const W=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],y0=e("key",W);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const G=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],d0=e("layout-dashboard",G);/** + */const G=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],k0=e("layers",G);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Q=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],y0=e("link-2",Q);/** + */const Q=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],r0=e("layout-dashboard",Q);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const J=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],k0=e("list-plus",J);/** + */const J=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],i0=e("link-2",J);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const X=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],r0=e("loader-circle",X);/** + */const X=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],p0=e("list-plus",X);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Y=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],i0=e("lock-keyhole",Y);/** + */const Y=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],l0=e("loader-circle",Y);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const e1=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],p0=e("lock",e1);/** + */const e1=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],_0=e("lock-keyhole",e1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const a1=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],l0=e("log-out",a1);/** + */const a1=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],M0=e("lock",a1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const t1=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],_0=e("mail",t1);/** + */const t1=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],v0=e("log-out",t1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const o1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],M0=e("message-circle",o1);/** + */const o1=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],x0=e("mail",o1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const c1=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],v0=e("package-check",c1);/** + */const c1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],g0=e("message-circle",c1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const h1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],x0=e("package-plus",h1);/** + */const h1=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],m0=e("package-check",h1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const s1=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],g0=e("package",s1);/** + */const s1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],u0=e("package-plus",s1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const n1=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],m0=e("pen",n1);/** + */const n1=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],w0=e("package",n1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const d1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],u0=e("plus",d1);/** + */const d1=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],$0=e("pen",d1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const y1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],w0=e("power",y1);/** + */const y1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],N0=e("plus",y1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const k1=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],$0=e("qr-code",k1);/** + */const k1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],f0=e("power",k1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const r1=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],N0=e("refresh-cw",r1);/** + */const r1=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],b0=e("qr-code",r1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const i1=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],f0=e("save",i1);/** + */const i1=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],q0=e("refresh-cw",i1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const p1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],b0=e("search",p1);/** + */const p1=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],z0=e("save",p1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const l1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],C0=e("send",l1);/** + */const l1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],A0=e("search",l1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const _1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],q0=e("settings",_1);/** + */const _1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],C0=e("send",_1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const M1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],z0=e("shield-check",M1);/** + */const M1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],H0=e("settings",M1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const v1=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],A0=e("shopping-bag",v1);/** + */const v1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],j0=e("shield-check",v1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const x1=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],j0=e("shopping-cart",x1);/** + */const x1=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],L0=e("shopping-bag",x1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const g1=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],H0=e("sparkles",g1);/** + */const g1=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],V0=e("shopping-cart",g1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const m1=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],L0=e("square-pen",m1);/** + */const m1=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],P0=e("sliders-horizontal",m1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const u1=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],V0=e("trash-2",u1);/** + */const u1=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],S0=e("sparkles",u1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const w1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],P0=e("trending-up",w1);/** + */const w1=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],U0=e("square-pen",w1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const $1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],S0=e("triangle-alert",$1);/** + */const $1=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],E0=e("trash-2",$1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const N1=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],U0=e("truck",N1);/** + */const N1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],B0=e("trending-up",N1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const f1=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],E0=e("upload",f1);/** + */const f1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],D0=e("triangle-alert",f1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const b1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],B0=e("user-round",b1);/** + */const b1=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],R0=e("truck",b1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const C1=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],D0=e("user",C1);/** + */const q1=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],T0=e("upload",q1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const q1=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],R0=e("users",q1);/** + */const z1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Z0=e("user-round",z1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const z1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],T0=e("webhook",z1);/** + */const A1=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],F0=e("user",A1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const A1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Z0=e("x",A1);/** + */const C1=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],I0=e("users",C1);/** * @license lucide-react v0.562.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const j1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],I0=e("zap",j1);export{J1 as $,L1 as A,U1 as B,Q1 as C,X1 as D,Y1 as E,G1 as F,o0 as G,k0 as H,h0 as I,t0 as J,s0 as K,d0 as L,F1 as M,x0 as N,W1 as O,g0 as P,$0 as Q,N0 as R,A0 as S,P0 as T,R0 as U,Z1 as V,I1 as W,Z0 as X,y0 as Y,I0 as Z,V1 as _,P1 as a,B1 as a0,z0 as a1,i0 as a2,B0 as a3,M0 as a4,K1 as a5,c0 as a6,n0 as a7,C0 as a8,_0 as a9,T0 as aa,p0 as ab,q0 as b,H0 as c,l0 as d,T1 as e,j0 as f,v0 as g,S0 as h,r0 as i,D0 as j,E1 as k,S1 as l,O1 as m,m0 as n,w0 as o,V0 as p,e0 as q,a0 as r,f0 as s,u0 as t,U0 as u,b0 as v,L0 as w,D1 as x,R1 as y,E0 as z}; + */const H1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],K0=e("webhook",H1);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const j1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],O0=e("x",j1);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const L1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],W0=e("zap",L1);export{i0 as $,P1 as A,B1 as B,X1 as C,e0 as D,a0 as E,P0 as F,J1 as G,h0 as H,d0 as I,p0 as J,y0 as K,r0 as L,c0 as M,Q1 as N,s0 as O,w0 as P,b0 as Q,q0 as R,L0 as S,B0 as T,I0 as U,u0 as V,G1 as W,O0 as X,I1 as Y,W0 as Z,K1 as _,U1 as a,S1 as a0,Y1 as a1,R1 as a2,j0 as a3,_0 as a4,Z0 as a5,g0 as a6,O1 as a7,n0 as a8,k0 as a9,C0 as aa,x0 as ab,K0 as ac,M0 as ad,H0 as b,S0 as c,v0 as d,F1 as e,V0 as f,m0 as g,D0 as h,l0 as i,F0 as j,D1 as k,E1 as l,W1 as m,$0 as n,f0 as o,E0 as p,t0 as q,o0 as r,z0 as s,N0 as t,R0 as u,A0 as v,U0 as w,T1 as x,Z1 as y,T0 as z}; diff --git a/internal/webui/static/assets/index-2Xnmtmdh.js b/internal/webui/static/assets/index-2Xnmtmdh.js deleted file mode 100644 index 9b4b10a..0000000 --- a/internal/webui/static/assets/index-2Xnmtmdh.js +++ /dev/null @@ -1,19 +0,0 @@ -import{j as e,r as n,b as ke,c as Qt,d as Kt}from"./react-vendor-DZnRGM0-.js";import{L as Yt,U as wt,S as kt,C as Fs,B as Ct,Z as Ts,a as is,b as zs,c as St,d as Xt,e as os,A as Xs,D as Zt,f as Zs,P as At,g as gs,E as It,T as Ht,h as ea,i as Le,Q as Ss,j as Os,k as We,l as rs,m as Hs,R as qe,n as Rt,o as sa,p as Ve,X as Ne,K as ta,q as ns,r as es,s as Je,t as Ge,u as et,v as aa,w as cs,x as la,y as ra,z as hs,F as na,G as st,I as tt,H as ia,J as oa,M as ca,N as As,O as ys,V as $t,W as da,Y as xa,_ as qs,$ as ma,a0 as ua,a1 as Ms,a2 as at,a3 as pa,a4 as _s,a5 as Lt,a6 as ha,a7 as ga,a8 as Us,a9 as Pt,aa as ba,ab as ya}from"./icons-vendor-BhUPp6x7.js";import{R as fs,B as fa,X as lt,Y as rt,T as Is,a as ja,C as Rs,A as Na,b as va,c as _a,P as nt,d as it,L as wa}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))d(u);new MutationObserver(u=>{for(const b of u)if(b.type==="childList")for(const k of b.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&d(k)}).observe(document,{childList:!0,subtree:!0});function l(u){const b={};return u.integrity&&(b.integrity=u.integrity),u.referrerPolicy&&(b.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?b.credentials="include":u.crossOrigin==="anonymous"?b.credentials="omit":b.credentials="same-origin",b}function d(u){if(u.ep)return;u.ep=!0;const b=l(u);fetch(u.href,b)}})();const ka=({activeTab:s,isAdmin:t=!1,onNavigate:l,onLogout:d})=>{const u=[{id:"dashboard",icon:Yt,label:"仪表盘"},{id:"accounts",icon:wt,label:"账号管理"},{id:"orders",icon:kt,label:"订单管理"},{id:"cards",icon:Fs,label:"卡密库存"},{id:"items",icon:Ct,label:"商品列表"},{id:"rules",icon:Ts,label:"自动化规则"},{id:"notifications",icon:is,label:"通知设置"},...t?[{id:"settings",icon:zs,label:"系统与AI"}]:[]];return e.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[e.jsx("div",{className:"w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5",style:{filter:"drop-shadow(0 4px 12px rgba(0,148,247,0.25))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),e.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",e.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),e.jsx("nav",{className:"space-y-2",children:u.map(b=>{const k=b.icon,O=s===b.id;return e.jsxs("button",{onClick:()=>l(b.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${O?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[e.jsx(k,{className:`w-5 h-5 transition-colors ${O?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:b.label}),O&&e.jsx(St,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},b.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:d,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[e.jsx(Xt,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},Ca=3e4,Sa=10*6e4;let $s=!1;const Et=()=>{$s||typeof window>"u"||($s=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{$s=!1}))},Aa=s=>{if(!s)return"";const t=new URLSearchParams;for(const[d,u]of Object.entries(s))u!=null&&t.set(d,String(u));const l=t.toString();return l?`?${l}`:""},Cs=async(s,t,l={})=>{var R;const d=Aa(l.params),u=`${t}${d}`,b=Dt(l.signal,l.timeoutMs??Ca);let k;try{k=await fetch(u,{method:s,credentials:"include",signal:b.signal,headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)})}catch(f){throw b.signal.aborted?new Error((R=l.signal)!=null&&R.aborted?"请求已取消":"请求超时,请稍后重试"):f}finally{b.cleanup()}const p=(k.headers.get("content-type")||"").includes("application/json");if(!k.ok){k.status===401&&!l.skipAuthLogout&&Et();const f=p?await k.json().catch(()=>{}):await k.text().catch(()=>{}),Q=typeof f=="string"?f:(f==null?void 0:f.detail)||(f==null?void 0:f.message)||(f==null?void 0:f.msg);throw new Error(Q||`请求失败: ${k.status}`)}return p?await k.json():await k.text()},ge=async(s,t,l)=>Cs("GET",s,{params:t,...l}),pe=async(s,t,l)=>Cs("POST",s,{body:t,...l}),Ee=async(s,t,l)=>Cs("PUT",s,{body:t,...l}),Me=async(s,t,l)=>Cs("DELETE",s,{params:t,...l}),bs=async(s,t,l={})=>{var p;const d=Dt(l.signal,l.timeoutMs??Sa);let u;try{u=await fetch(s,{method:"POST",credentials:"include",signal:d.signal,body:t})}catch(R){throw d.signal.aborted?new Error((p=l.signal)!=null&&p.aborted?"请求已取消":"上传超时,请稍后重试"):R}finally{d.cleanup()}const O=(u.headers.get("content-type")||"").includes("application/json")?await u.json().catch(()=>{}):await u.text().catch(()=>{});if(!u.ok){u.status===401&&Et();const R=typeof O=="string"?O:(O==null?void 0:O.detail)||(O==null?void 0:O.message)||(O==null?void 0:O.msg),f=new Error(R||"请求失败: "+u.status);throw f.payload=O,f}return O},Dt=(s,t)=>{const l=new AbortController,d=()=>l.abort(s==null?void 0:s.reason);s!=null&&s.aborted?d():s==null||s.addEventListener("abort",d,{once:!0});const u=globalThis.setTimeout(()=>l.abort(new DOMException("timeout","TimeoutError")),Math.max(1,t));return{signal:l.signal,cleanup:()=>{globalThis.clearTimeout(u),s==null||s.removeEventListener("abort",d)}}},ws=s=>{const t=s.getFullYear(),l=String(s.getMonth()+1).padStart(2,"0"),d=String(s.getDate()).padStart(2,"0");return`${t}-${l}-${d}`},Ws=(s,t)=>{const l=new Date(s);return l.setHours(12,0,0,0),l.setDate(l.getDate()+t),l},Bs=(s,t)=>({startDate:ws(Ws(s,-(t-1))),endDate:ws(s)}),ot=(s,t=new Date,l="",d="")=>{if(s==="custom"&&l&&d){if(l>d)throw new Error("开始日期不能晚于结束日期");return{startDate:l,endDate:d}}return s==="yesterday"?Bs(Ws(t,-1),1):Bs(t,s==="3days"?3:s==="30days"?30:s==="today"?1:7)},Ia=s=>{const t=new Date(`${s.startDate}T12:00:00`),l=new Date(`${s.endDate}T12:00:00`),d=Math.round((l.getTime()-t.getTime())/864e5)+1,u=Ws(t,-1);return Bs(u,d)},Ra=s=>{const t={...s};if("renewal_log_retention_days"in t){const l=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(l)?l:10}return t},$a=async s=>pe("/login",s,{skipAuthLogout:!0}),Ft=async()=>ge("/verify"),La=async()=>pe("/logout",{}),Pa=async s=>Ee("/account/credentials",s),Ea=(s,t)=>{const l=s.avatar_url||"";if(!l)return"";try{const d=new URL(l,window.location.origin);return d.hostname.endsWith("alicdn.com")&&d.searchParams.set("_v",t),d.toString()}catch{return l}},Vs=async s=>{const t=await ge("/cookies/details",void 0,s),l=Date.now().toString();return t.map(d=>({id:d.id,value:"",cookie:"",enabled:d.enabled,auto_confirm:d.auto_confirm,remark:d.remark,note:d.remark,pause_duration:d.pause_duration,paused_until:Number(d.paused_until||0),paused:d.paused===!0,username:d.username||"",login_password:"",show_browser:d.show_browser===!0||d.show_browser===1||d.show_browser==="1"||d.show_browser==="true",nickname:d.nickname||d.remark||`账号 ${d.id.substring(0,6)}`,avatar_url:Ea(d,l),profile_error:d.profile_error||"",ai_enabled:!1}))},Da=async s=>ge("/cookies/runtime-status",void 0,s),Fa=async s=>pe("/qr-login/generate",void 0,s),Ta=async(s,t)=>ge(`/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),Oa=async(s,t)=>pe(`/qr-login/complete-verification/${s}`,{target_account_id:t||""}),qa=async(s,t)=>Ee(`/cookies/${s}/status`,{enabled:t}),Ma=async s=>Me(`/cookies/${s}`),Ba=async(s,t)=>Ee(`/cookies/${s}/pause-duration`,{pause_duration:t}),za=async(s,t)=>Ee(`/cookies/${s}/settings`,t),Ua=async s=>pe("/password-login",s),Wa=async(s,t)=>ge(`/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),Va=async s=>Me(`/password-login/cancel/${s}`),Ga=async s=>pe(`/cookies/${s}/refresh-profile`,{}),Ja=async s=>ge("/ai-reply-settings",void 0,s),Tt=s=>{const t=String(s||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Qa=async(s,t,l=1,d=20,u)=>{const b={page:l,page_size:d};t&&t!=="all"&&(b.status=t),u!=null&&u.trim()&&(b.search=u.trim());const k=await ge("/api/orders",b),p=(k.orders||k.data||[]).map(R=>({...R,id:R.id||R.order_id,status:Tt(R.status||R.order_status),quantity:Number(R.quantity||1)}));return{success:!0,data:p,total:k.total||p.length,page:k.page||l,page_size:k.page_size||d,total_pages:k.total_pages||1}},Ka=async(s,t)=>Ee(`/api/orders/${s}`,t),Ya=async s=>Me(`/api/orders/${s}`),Xa=async(s,t)=>{const l=new FormData;return bs("/api/orders/refresh",l)},Za=async s=>pe(`/api/orders/${s}/refresh`),Ha=async(s,t)=>pe("/api/orders/manual-ship",{order_ids:s,ship_mode:t}),el=async s=>s instanceof FormData?bs("/api/orders/import",s):pe("/api/orders/import",s),sl=async()=>ge("/dashboard/stats"),ct=async(s=7)=>{let t;if(typeof s=="number"){const l=new Date,d=new Date;d.setDate(d.getDate()-s),t={start_date:ws(d),end_date:ws(l)}}else t=s;return ge("/analytics/orders",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()})},tl=async s=>{const t=await ge("/analytics/orders/valid",{start_date:s.start_date,end_date:s.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()}),d=(Array.isArray(t)?t:t.orders||[]).map(u=>({...u,id:u.id||u.order_id,status:Tt(u.status||u.order_status),quantity:Number(u.quantity||1)}));return{orders:d,total:Array.isArray(t)?d.length:Number(t.total??d.length),truncated:Array.isArray(t)?!1:t.truncated===!0}},al=s=>{let t=s.api_config;if(typeof t=="string"&&t.trim())try{t=JSON.parse(t)}catch{t=void 0}return{...s,api_config:t||void 0}},Ot=s=>({...s,api_config:s.api_config?JSON.stringify(s.api_config):""}),Ue=async()=>{const s=await ge("/cards");return(Array.isArray(s)?s:s.cards||[]).map(al)},ll=async s=>pe("/cards",Ot(s)),dt=async(s,t)=>Ee(`/cards/${s}`,Ot(t)),rl=async s=>Me(`/cards/${s}`),nl=async s=>{const t=new FormData;return t.append("file",s),bs("/cards/batch",t)},il=async(s,t)=>pe(`/cards/${s}/append-data`,{content:t}),Ls=s=>s===!0||s===1||s==="1",ds=async()=>{const s=await ge("/items");return(Array.isArray(s)?s:s.items||[]).map(l=>({...l,id:l.id||`${l.cookie_id}-${l.item_id}`,is_multi_spec:Ls(l.is_multi_spec),is_multi_qty_ship:Ls(l.is_multi_qty_ship??l.multi_quantity_delivery),multi_quantity_delivery:Ls(l.multi_quantity_delivery??l.is_multi_qty_ship)}))},ol=async s=>pe("/items/get-all-from-account",{cookie_id:s}),cl=async(s,t)=>Me(`/items/${s}/${t}`),dl=async(s,t)=>pe(`/items/${s}`,t),xl=async s=>{const t=new FormData;t.set("cookie_id",s.cookie_id),t.set("title",s.title),t.set("description",s.description),t.set("price",s.price),t.set("original_price",s.original_price||""),t.set("quantity",String(s.quantity)),t.set("postage_mode",s.postage_mode),t.set("postage",s.postage||"");for(const l of s.images)t.append("images",l);return bs("/items/publish",t)},ml=async s=>{const t=new FormData;return t.set("file",s.file),s.imagesZip&&t.set("images_zip",s.imagesZip),s.defaultCookieId&&t.set("default_cookie_id",s.defaultCookieId),bs("/items/publish-batches/preview",t)},ul=async s=>pe("/items/publish-batches",{preview_id:s}),as=async s=>ge(`/items/publish-batches/${s}`),xt=async(s=20)=>{const t=await ge("/items/publish-batches",{limit:s});return Array.isArray(t)?t:t.batches||[]},pl=async s=>Me(`/items/publish-batches/${s}`),hl=async s=>pe(`/items/publish-batches/${s}/cancel`,{}),gl=async s=>pe(`/items/publish-batches/${s}/retry-failed`,{}),bl=async(s,t,l)=>Ee(`/items/${s}/${t}`,l),ks=async()=>{const s=await ge("/automation-rules");return(Array.isArray(s)?s:s.data||s.rules||[]).map(l=>{var d,u;return{id:String(l.id),name:l.name||"",trigger_type:l.trigger_type||"order_paid",item_keyword:l.item_title||l.item_id||"",cookie_id:l.cookie_id||"",item_id:l.item_id||"",item_title:l.item_title||"",card_group_id:Number(((d=(l.actions||[]).find(b=>b.action_type==="send_card"))==null?void 0:d.card_id)||0),card_group_name:((u=(l.actions||[]).find(b=>b.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:l.priority||100,enabled:l.enabled||!1,config_json:l.config_json||"{}",actions:(l.actions||[]).map(b=>({id:b.id?String(b.id):void 0,action_type:b.action_type,card_id:Number(b.card_id||0),card_name:b.card_name||"",delivery_count:Number(b.delivery_count||1),message_template:b.message_template||"",delay_seconds:Number(b.delay_seconds||0),config_json:b.config_json||"{}",enabled:b.enabled!==!1,sort_order:Number(b.sort_order||0)})),variants:(l.actions||[]).filter(b=>b.action_type==="send_card").map(b=>{let k={};try{k=JSON.parse(b.config_json||"{}")}catch{}return{id:b.id?String(b.id):void 0,spec_name:k.spec_name||"",spec_value:k.spec_value||"",card_id:Number(b.card_id||0),card_name:b.card_name||"",delivery_count:Number(b.delivery_count||1),enabled:b.enabled!==!1,delay_override:k.delay_override===!0,delay_seconds:Number(b.delay_seconds||0),config_json:b.config_json||"{}"}})}})},yl=(s,t)=>{if(s!=="order_paid")return t.map((u,b)=>({...u,sort_order:u.sort_order||b+1}));const l=t.filter(u=>u.action_type==="send_card").map((u,b)=>({...u,sort_order:b+1})),d=t.filter(u=>u.action_type!=="send_card"&&u.action_type!=="confirm_shipment");return[...l,...d.map((u,b)=>({...u,sort_order:l.length+b+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:l.length+d.length+1}]},mt=async s=>{const t=s.trigger_type||"order_paid",d=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[t]||"自动化规则",s.item_title||s.item_id||s.cookie_id||""].filter(Boolean).join(" - "),u=(s.actions||[]).filter(p=>p.action_type!=="send_card"&&p.action_type!=="confirm_shipment"),b=s.variants&&s.variants.length>0?[...s.variants.map((p,R)=>({action_type:"send_card",card_id:p.card_id,delivery_count:p.delivery_count||1,enabled:p.enabled!==!1,sort_order:R+1,delay_seconds:p.delay_seconds||0,config_json:JSON.stringify({spec_name:p.spec_name||"",spec_value:p.spec_value||"",delay_override:p.delay_override===!0})})),...u]:s.actions&&s.actions.length>0?s.actions:[{action_type:"send_card",card_id:s.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],k=yl(t,b),O={cookie_id:s.cookie_id||"",item_id:s.item_id||"",name:(s.name||"").trim()||d||"自动化规则",trigger_type:t,enabled:s.enabled??!0,priority:s.priority||100,config_json:s.config_json||"{}",actions:k.map((p,R)=>({action_type:p.action_type,card_id:p.card_id||0,delivery_count:p.delivery_count||1,message_template:p.message_template||"",delay_seconds:p.delay_seconds||0,config_json:p.config_json||"{}",enabled:p.enabled!==!1,sort_order:p.sort_order||R+1}))};return s.id?Ee(`/automation-rules/${s.id}`,O):pe("/automation-rules",O)},fl=async s=>Me(`/automation-rules/${s}`),jl=async()=>{const s=await ge("/automation-issues");return{runs:Array.isArray(s==null?void 0:s.runs)?s.runs:[],pending_tasks:Array.isArray(s==null?void 0:s.pending_tasks)?s.pending_tasks:[]}},Nl=async(s,t)=>pe(`/automation-runs/${s}/resolve`,{resolution:t}),vl=async(s,t)=>pe(`/automation-pending-tasks/${s}/resolve`,{resolution:t}),_l=s=>({id:String((s==null?void 0:s.id)||""),keyword:(s==null?void 0:s.keyword)||"",reply:(s==null?void 0:s.reply)||"",item_id:(s==null?void 0:s.item_id)||"",type:(s==null?void 0:s.type)==="image"?"image":"text",image_url:(s==null?void 0:s.image_url)||""}),wl=async s=>{const t=await ge(`/keywords-with-type/${s}`);return Array.isArray(t)?t.map(_l):[]},kl=async s=>s?(await wl(s)).map(l=>({id:l.id,keyword:l.keyword||"",reply_content:l.reply||"",match_type:"fuzzy",enabled:!0,item_id:l.item_id||"",type:l.type==="image"?"image":"text",image_url:l.image_url||""})):[],Cl=async(s,t)=>{const l=s.type||"text",d={keyword:s.keyword||"",reply:l==="text"&&s.reply_content||"",item_id:s.item_id||"",type:l,image_url:l==="image"&&s.image_url||""};return s.id?Ee(`/keywords-with-type/${t}/${s.id}`,d):pe(`/keywords-with-item-id/${t}`,d)},Sl=async(s,t)=>Me(`/keywords-with-type/${t}/${s}`),qt=async()=>{const s=await ge("/system-settings");return Ra(s.data||s)},Mt=async s=>{const t=Object.fromEntries(Object.entries(s).filter(([,l])=>l!=null));return Ee("/system-settings",t)},Al=async(s,t)=>ge(`/ai-reply-settings/${s}`,void 0,t),Il=async(s,t)=>{const l={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return Ee(`/ai-reply-settings/${s}`,l)},Rl=async(s,t="")=>(await pe("/ai-models",{base_url:s,api_key:t})).models||[],$l=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},Bt=s=>{const t=Array.from(new Set((s||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},zt=async s=>({success:!0,data:(await ge("/notification-channels",void 0,s)||[]).map(d=>{let u;try{u=typeof d.config=="string"?JSON.parse(d.config):d.config}catch{u={}}return{id:String(d.id),name:d.name,type:d.type==="ding_talk"?"dingtalk":d.type==="lark"?"feishu":d.type,config:u,event_types:$l(d.event_types),enabled:d.enabled,created_at:d.created_at,updated_at:d.updated_at}})}),Ll=async s=>pe("/notification-channels",{...s,config:JSON.stringify(s.config),event_types:Bt(s.event_types)}),ut=async(s,t)=>{const l={...t};return"config"in t&&(l.config=JSON.stringify(t.config)),"event_types"in t&&(l.event_types=Bt(t.event_types)),Ee(`/notification-channels/${s}`,l)},Pl=async s=>Me(`/notification-channels/${s}`),El=async(s,t)=>{const l=await ge(`/message-notifications/${s}`,void 0,t);return(l==null?void 0:l.channel_ids)||[]},Dl=async s=>pe(`/notification-channels/${s}/test`,{}),pt=async()=>ge("/api/default-replies"),Fl=async s=>{const t=await ge(`/api/default-reply/${s}`);return{cookie_id:s,enabled:t.enabled||!1,reply_content:t.reply_content||"",reply_once:t.reply_once||!1,reply_image_url:t.reply_image_url||""}},Tl=async(s,t)=>Ee(`/api/default-reply/${s}`,{enabled:t.enabled??!1,reply_content:t.reply_content||"",reply_once:t.reply_once??!1,reply_image_url:t.reply_image_url||""}),Ol=async s=>Me(`/api/default-reply/${s}`),ql=async s=>pe(`/api/default-reply/${s}/clear-records`,{}),Ml=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},js=({title:s,value:t,icon:l,colorClass:d,trend:u})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${d} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${d} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(l,{className:`w-6 h-6 ${d.replace("bg-","text-")}`})}),u&&e.jsxs("span",{className:"text-xs font-bold text-white bg-[#0094f7] px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(Ht,{className:"w-3 h-3"})," ",u]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:t}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:s})]})]}),Ps=()=>{var ie,H;const[s,t]=n.useState(null),[l,d]=n.useState(null),[u,b]=n.useState(""),[k,O]=n.useState("7days"),[p,R]=n.useState(""),[f,Q]=n.useState(""),[se,U]=n.useState(null),[J,S]=n.useState(""),[K,de]=n.useState([]),[le,ne]=n.useState(0),[q,B]=n.useState(!1),[D,Z]=n.useState(!1),[W,A]=n.useState([]),[Y,L]=n.useState({}),te=n.useRef(0),T=["#0094f7","#3B82F6","#10B981","#F59E0B","#8B5CF6"],h=async c=>{let C;try{C=ot(c,new Date,p,f)}catch(fe){b(fe instanceof Error?fe.message:"日期范围无效");return}const{startDate:oe,endDate:be}=C,ye={start_date:oe,end_date:be},Se=Ia(C),ve=++te.current;Z(!0),b("");try{const[fe,De,ue]=await Promise.all([ct(ye),ct({start_date:Se.startDate,end_date:Se.endDate}),tl(ye)]);if(ve!==te.current)return;d(fe),U(De),de(ue.orders),ne(ue.total),B(ue.truncated)}catch(fe){ve===te.current&&b(fe instanceof Error?fe.message:"经营数据加载失败")}finally{ve===te.current&&Z(!1)}},$=()=>{if(!l||!se)return null;const c=l.revenue_stats.total_amount,C=se.revenue_stats.total_amount;if(C===0)return c>0?"+100%":"0%";const oe=(c-C)/C*100;return`${oe>=0?"+":""}${oe.toFixed(1)}%`};if(n.useEffect(()=>{let c=!1;return Promise.all([sl(),ds()]).then(([C,oe])=>{if(c)return;t(C),A(oe);const be={};oe.forEach(ye=>{be[ye.item_id]=ye.item_title||ye.item_id}),L(be)}).catch(C=>{c||b(C instanceof Error?C.message:"概览加载失败")}),()=>{c=!0}},[]),n.useEffect(()=>{k!=="custom"&&h(k)},[k]),u&&(!s||!l))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(os,{className:"w-8 h-8"}),e.jsx("span",{children:u}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:()=>window.location.reload(),children:"重新加载"})]});if(!s||!l)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(Xs,{className:"w-8 h-8 animate-spin text-[#0094f7]"})});const z=((ie=l.daily_stats)==null?void 0:ie.map(c=>({name:c.date.slice(5),amount:c.amount,orders:c.order_count,avgAmount:c.order_count>0?(c.amount/c.order_count).toFixed(2):0})))||[],X=l.item_stats||[],m=l.revenue_stats.total_orders||0,_=l.revenue_stats.total_amount||0,N=X.length>0?X.map(c=>({name:(Y[c.item_id]||c.item_id).length>12?(Y[c.item_id]||c.item_id).substring(0,12)+"...":Y[c.item_id]||c.item_id,sales:c.order_count})).sort((c,C)=>C.sales-c.sales).slice(0,10):[],y=Math.max(...N.map(c=>c.sales),1),P=X.length>0?X.map(c=>({name:(Y[c.item_id]||c.item_id).length>10?(Y[c.item_id]||c.item_id).substring(0,10)+"...":Y[c.item_id]||c.item_id,value:c.order_count,percent:m>0?c.order_count/m*100:0})).sort((c,C)=>C.value-c.value).slice(0,6).map((c,C)=>({...c,color:T[C%T.length]})):[],M=X.length>0?X.map(c=>({name:(Y[c.item_id]||c.item_id).length>12?(Y[c.item_id]||c.item_id).substring(0,12)+"...":Y[c.item_id]||c.item_id,value:c.total_amount,orderCount:c.order_count,percentage:_>0?c.total_amount/_*100:0})).sort((c,C)=>C.value-c.value).slice(0,5).map((c,C)=>({...c,color:T[C%T.length],percentage:c.percentage.toFixed(1)})):[],i=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}],E=((H=i.find(c=>c.key===k))==null?void 0:H.label)||"所选范围";let w;try{w=ot(k,new Date,p,f)}catch{w={startDate:p,endDate:f}}const G=J.trim().toLowerCase(),me=K.filter(c=>{var C,oe,be,ye;return((C=c.order_id)==null?void 0:C.toLowerCase().includes(G))||((oe=c.item_id)==null?void 0:oe.toLowerCase().includes(G))||((be=c.item_title)==null?void 0:be.toLowerCase().includes(G))||((ye=c.buyer_id)==null?void 0:ye.toLowerCase().includes(G))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[i.map(c=>e.jsx("button",{onClick:()=>O(c.key),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${k===c.key?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:c.label},c.key)),k==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:p,onChange:c=>R(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:f,onChange:c=>Q(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),e.jsx("button",{onClick:()=>{try{b(""),h("custom")}catch(c){b(c instanceof Error?c.message:"日期范围无效")}},className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(js,{title:"累计营收 (CNY)",value:`¥${l.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:Zt,colorClass:"bg-blue-400",trend:$()||void 0}),e.jsx(js,{title:"活跃账号 / 总数",value:`${s.active_cookies} / ${s.total_cookies}`,icon:wt,colorClass:"bg-blue-500"}),e.jsx(js,{title:"订单数",value:l.revenue_stats.total_orders.toLocaleString(),icon:Zs,colorClass:"bg-blue-500"}),e.jsx(js,{title:"库存卡密余量",value:s.available_card_stock,icon:At,colorClass:"bg-purple-500"})]}),e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[E,"的销售额走势"]})]}),e.jsx("div",{className:"h-[350px] w-full",children:z.length===0||l.revenue_stats.total_amount===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(Zs,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):z.length<=2?e.jsx(fs,{width:"100%",height:"100%",children:e.jsxs(fa,{data:z,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(lt,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#374151",fontSize:14,fontWeight:600},dy:10}),e.jsx(rt,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},tickFormatter:c=>`¥${c}`}),e.jsx(Is,{contentStyle:{backgroundColor:"#fff",borderRadius:"8px",border:"1px solid #e5e7eb",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1)",padding:"12px 16px"},labelStyle:{color:"#6b7280",fontWeight:500},itemStyle:{color:"#0094f7",fontWeight:600},cursor:{fill:"rgba(0, 148, 247, 0.08)"},formatter:c=>[`¥${Number(c).toFixed(2)}`,"营收"]}),e.jsx(ja,{dataKey:"amount",fill:"#0094f7",maxBarSize:72,radius:[12,12,0,0],stroke:"#000000",strokeWidth:0,children:z.map((c,C)=>e.jsx(Rs,{fill:["#0094f7","#FCD34D","#0071e3"][C%3]},`cell-${C}`))})]})}):e.jsx(fs,{width:"100%",height:"100%",children:e.jsxs(Na,{data:z,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#0094f7",stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:"#0094f7",stopOpacity:0})]})}),e.jsx(lt,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},dy:15}),e.jsx(rt,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500}}),e.jsx(va,{vertical:!1,stroke:"#F3F4F6",strokeDasharray:"3 3"}),e.jsx(Is,{contentStyle:{backgroundColor:"#fff",borderRadius:"8px",border:"1px solid #e5e7eb",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1)",padding:"12px 16px"},labelStyle:{color:"#6b7280",fontWeight:500},itemStyle:{color:"#0094f7",fontWeight:600},cursor:{stroke:"#0094f7",strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(_a,{type:"monotone",dataKey:"amount",stroke:"#0094f7",strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:"#fff",stroke:"#0094f7",strokeWidth:2}})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:N.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:N.map((c,C)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${C<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:C+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:c.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[c.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[#0094f7]",style:{width:`${Math.max(8,c.sales/y*100)}%`}})})]},`${c.name}-${C}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"h-[280px]",children:P.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx(fs,{width:"100%",height:"100%",children:e.jsxs(nt,{children:[e.jsx(it,{data:P,cx:"50%",cy:"50%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",label:({name:c,payload:C})=>`${c} ${Number((C==null?void 0:C.percent)||0).toFixed(1)}%`,labelLine:!1,children:P.map((c,C)=>e.jsx(Rs,{fill:c.color},`cell-${C}`))}),e.jsx(wa,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:c=>e.jsx("span",{style:{color:"#6B7280",fontWeight:500},children:c})})]})})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-[#FAFAFA]",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),q&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",K.length," / ",le," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:J,onChange:c=>S(c.target.value),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:D?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(Xs,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):me.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(gs,{className:"w-7 h-7 text-gray-300"})}),G?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",K.length," 单参与统计,但没有订单号、商品、买家匹配“",J,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",w.startDate," 至 ",w.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",l.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:me.map(c=>e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(gs,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:c.item_title||c.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:c.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",c.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:c.buyer_id}),c.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:c.created_at})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",c.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4",children:e.jsx(Ml,{status:c.status||c.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${c.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(It,{className:"w-4 h-4"})})})]},c.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),M.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-[300px] relative",children:e.jsx(fs,{width:"100%",height:"100%",children:e.jsxs(nt,{children:[e.jsx(it,{data:M,cx:"50%",cy:"50%",innerRadius:60,outerRadius:100,paddingAngle:2,dataKey:"value",label:({name:c,payload:C})=>`${c} ${(C==null?void 0:C.percentage)||"0.0"}%`,children:M.map((c,C)=>e.jsx(Rs,{fill:c.color||T[C%T.length]},`cell-${C}`))}),e.jsx(Is,{contentStyle:{backgroundColor:"#fff",border:"1px solid #e5e7eb",borderRadius:"6px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)"},formatter:c=>`¥${Number(c||0).toLocaleString()}`})]})})}),e.jsx("div",{className:"space-y-3 mt-4",children:M.map(c=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:c.color||T[M.indexOf(c)%T.length]}}),e.jsx("span",{className:"text-gray-600 font-medium",children:c.name})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",c.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[c.percentage,"%"]})]})]},c.name))})]})]})]})]})},Bl=(s,t)=>{const l=t.pause_duration||0;return s!==l},zl=(s,t)=>{const l=t.username!==(s.username||""),d=t.show_browser!==(s.show_browser||!1),u=t.login_password!=="",b=t.clear_password===!0;if(!l&&!d&&!u&&!b)return null;const k={username:t.username,show_browser:t.show_browser};return b?k.clear_password=!0:u&&(k.login_password=t.login_password),k},Ul=(s,t)=>s&&t,Wl=(s,t)=>{if(!s||!t)return!1;const l=Date.parse(s),d=Date.parse(t);return Number.isFinite(l)&&Number.isFinite(d)&&ds.map(l=>{const d=t[l.id];return!d||Wl(l.runtime_updated_at,d.updated_at)?l:{...l,runtime_state:d.state,runtime_message:d.message||"",runtime_connected:d.connected,runtime_updated_at:d.updated_at}}),Gl=new Set(["expired","cancelled","error","not_found"]),Ns=()=>{let s=0;return{next:()=>(s+=1,s),cancel:()=>{s+=1},isCurrent:t=>t===s}},Jl=(s={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let t=null,l=null,d=-1,u=0;const b=()=>{u+=1,l==null||l.abort(),l=null,t!==null&&(s.clearInterval(t),t=null)};return{start:(O,p,R,f=2e3)=>{b();const Q=u;l=new AbortController;const se=l.signal;t=s.setInterval(()=>{d===Q||Q!==u||(d=Q,(async()=>{var U,J;try{const S=await p(O,se);if(S.status==="success"){b(),await R.onSuccess(S);return}if(S.status==="scanned"){(U=R.onScanned)==null||U.call(R,S);return}if(S.status==="verification_required"){(J=R.onVerificationRequired)==null||J.call(R,S);return}S.status&&Gl.has(S.status)&&(b(),R.onTerminalError(S))}catch(S){if(se.aborted||Q!==u)return;b(),R.onPollError(S)}finally{d===Q&&(d=-1)}})())},f)},stop:b,isActive:()=>t!==null}},Ql=({faceQrUrl:s,verificationScreenshot:t})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(ea,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:s?e.jsx("img",{src:s,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):t?e.jsx("img",{src:t,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(Le,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),ht=({src:s,alt:t,className:l=""})=>e.jsx("img",{src:s,alt:t,className:`block aspect-square h-auto w-full object-contain ${l}`.trim()}),Kl=()=>{const[s,t]=n.useState([]),[l,d]=n.useState(!0),[u,b]=n.useState(""),[k,O]=n.useState(""),[p,R]=n.useState(!1),[f,Q]=n.useState(""),[se,U]=n.useState("pending"),[J,S]=n.useState(""),[K,de]=n.useState(""),[le,ne]=n.useState(null),[q,B]=n.useState(null),[D,Z]=n.useState(null),[W,A]=n.useState([]),[Y,L]=n.useState([]),[te,T]=n.useState(!1),[h,$]=n.useState(!1),[z,X]=n.useState(!1),[m,_]=n.useState(""),[N,y]=n.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),[P,M]=n.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[i,E]=n.useState(!1),[w,G]=n.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),me=n.useRef(null),ie=n.useRef(null),H=n.useRef(null),c=n.useRef(null),C=n.useRef(null),oe=n.useRef(null),be=n.useRef(null),ye=n.useRef(null),Se=n.useRef(null),ve=n.useRef(null),fe=n.useRef(null),De=n.useRef(null),ue=n.useRef(0);me.current===null&&(me.current=Jl()),ie.current===null&&(ie.current=Ns()),H.current===null&&(H.current=Ns()),c.current===null&&(c.current=Ns()),C.current===null&&(C.current=Ns());const Ae=()=>{fe.current!==null&&(window.clearTimeout(fe.current),fe.current=null)},Re=()=>{De.current!==null&&(window.clearTimeout(De.current),De.current=null)},Fe=()=>{var o;(o=me.current)==null||o.stop()},Ke=()=>{var o,j;(o=Se.current)==null||o.abort(),(j=ie.current)==null||j.cancel(),Fe(),Ae(),R(!1)},Ye=()=>{Ae(),fe.current=window.setTimeout(()=>{fe.current=null,R(!1),x()},1e3)},x=async()=>{var F,ae,re,_e,$e;const o=H.current.next();(F=oe.current)==null||F.abort();const j=new AbortController;oe.current=j,d(!0);try{const we={signal:j.signal},[Pe,Xe]=await Promise.allSettled([Vs(we),Ja(we)]);if(!((ae=H.current)!=null&&ae.isCurrent(o)))return;if(Pe.status==="rejected")throw Pe.reason;const Oe=Pe.value,xs=Xe.status==="fulfilled"?Xe.value:{};Xe.status==="rejected"&&console.error("Failed to load AI settings:",Xe.reason);const Jt=Oe.map(ts=>{var Gs,Js,Qs,Ks,Ys;return{...ts,ai_enabled:((Gs=xs[ts.id])==null?void 0:Gs.ai_enabled)??!1,max_discount_percent:((Js=xs[ts.id])==null?void 0:Js.max_discount_percent)??10,max_discount_amount:((Qs=xs[ts.id])==null?void 0:Qs.max_discount_amount)??100,max_bargain_rounds:((Ks=xs[ts.id])==null?void 0:Ks.max_bargain_rounds)??3,custom_prompts:((Ys=xs[ts.id])==null?void 0:Ys.custom_prompts)??""}});(re=H.current)!=null&&re.isCurrent(o)&&t(Jt)}catch(we){(_e=H.current)!=null&&_e.isCurrent(o)&&!j.signal.aborted&&console.error("Failed to load accounts:",we)}finally{($e=H.current)!=null&&$e.isCurrent(o)&&d(!1)}};n.useEffect(()=>{let o=!1,j=null;const F=new AbortController,ae=async()=>{try{const re=await Da({signal:F.signal,timeoutMs:1e4});o||t(_e=>Vl(_e,re))}catch(re){o||console.error("Failed to load account runtime statuses:",re)}finally{o||(j=window.setTimeout(()=>void ae(),2e3))}};return x().finally(()=>{o||ae()}),()=>{o=!0,F.abort(),j!==null&&window.clearTimeout(j)}},[]),n.useEffect(()=>()=>{var o,j,F,ae,re,_e,$e,we,Pe;Fe(),(o=ie.current)==null||o.cancel(),(j=H.current)==null||j.cancel(),(F=c.current)==null||F.cancel(),(ae=C.current)==null||ae.cancel(),(re=oe.current)==null||re.abort(),(_e=be.current)==null||_e.abort(),($e=ye.current)==null||$e.abort(),(we=Se.current)==null||we.abort(),(Pe=ve.current)==null||Pe.abort(),Ae(),ue.current+=1,Re()},[]);const V=o=>{if(!o.enabled||o.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(o.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},he=async(o,j)=>{await qa(o,!j),x()},Ce=async o=>{confirm("确认删除该账号吗?")&&(await Ma(o),x())},Be=async o=>{O(o.id);try{const j=await Ga(o.id);j!=null&&j.profile_error&&alert("资料刷新失败:"+j.profile_error),await x()}catch(j){console.error("刷新账号资料失败:",j),alert((j==null?void 0:j.message)||"刷新账号资料失败,请先重新授权该账号")}finally{O("")}},Te=async o=>{var _e,$e;const j=c.current.next();(_e=be.current)==null||_e.abort();const F=new AbortController;be.current=F,$(!0),T(!1),X(!1),_("");const[ae,re]=await Promise.allSettled([zt({signal:F.signal}),El(o,{signal:F.signal})]);($e=c.current)!=null&&$e.isCurrent(j)&&(ae.status==="fulfilled"?A(ae.value.data||[]):(A([]),_("通知渠道列表加载失败,请重试")),re.status==="fulfilled"?(L(re.value||[]),T(!0)):(L([]),_("通知绑定加载失败;本次保存不会修改现有绑定")),$(!1))},r=async o=>{var j;ue.current+=1,(j=ve.current)==null||j.abort(),Re(),G({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),Z(o),y({remark:o.remark||o.note||"",cookie:o.cookie||o.value||"",auto_confirm:o.auto_confirm||!1,pause_duration:o.pause_duration||0,username:o.username||"",login_password:o.login_password||"",show_browser:o.show_browser||!1,showLoginPassword:!1,clear_password:!1}),B("edit"),await Te(o.id)},I=async o=>{var ae,re,_e,$e;const j=C.current.next();(ae=ye.current)==null||ae.abort();const F=new AbortController;ye.current=F,Z(o),B("ai-settings"),E(!0);try{const we=await Al(o.id,{signal:F.signal});if(!((re=C.current)!=null&&re.isCurrent(j)))return;M({ai_enabled:we.ai_enabled??!1,max_discount_percent:we.max_discount_percent??10,max_discount_amount:we.max_discount_amount??100,max_bargain_rounds:we.max_bargain_rounds??3,custom_prompts:we.custom_prompts??""})}catch(we){(_e=C.current)!=null&&_e.isCurrent(j)&&console.error("Failed to load AI settings:",we)}finally{($e=C.current)!=null&&$e.isCurrent(j)&&E(!1)}},ce=async()=>{if(D){E(!0);try{const o={};N.remark!==(D.remark||D.note||"")&&(o.remark=N.remark),N.cookie&&N.cookie!==(D.cookie||D.value||"")&&(o.cookie=N.cookie),N.auto_confirm!==D.auto_confirm&&(o.auto_confirm=N.auto_confirm),Bl(N.pause_duration,D)&&(o.pause_duration=N.pause_duration);const j=zl(D,N);j&&Object.assign(o,j),Ul(te,z)&&(o.channel_ids=Y),Object.keys(o).length>0&&await za(D.id,o),B(null),x()}catch(o){console.error("更新账号失败:",o),alert("更新失败,请重试")}finally{E(!1)}}},Qe=async()=>{if(!(!D||N.pause_duration<=0)){E(!0);try{const o=await Ba(D.id,N.pause_duration);Z({...D,pause_duration:N.pause_duration,paused:(o==null?void 0:o.paused)===!0,paused_until:Number((o==null?void 0:o.paused_until)||0)}),await x()}catch(o){alert(o instanceof Error?o.message:"重新暂停失败")}finally{E(!1)}}},ze=async()=>{if(D){E(!0);try{await Il(D.id,P),B(null),x()}catch(o){console.error("更新AI设置失败:",o),alert("更新失败,请重试")}finally{E(!1)}}},Ie=async(o,j)=>{var ae;(ae=ve.current)==null||ae.abort();const F=new AbortController;ve.current=F;try{const re=await Wa(o,F.signal);if(j!==ue.current)return;if(re.status==="success"){Re(),G({sessionId:o,status:"success",message:re.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}),y(_e=>({..._e,login_password:"",showLoginPassword:!1})),await x();return}if(re.status==="processing"||re.status==="verification_required"){G({sessionId:o,status:re.status,message:re.message||(re.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:re.qr_code_url||""}),Re(),De.current=window.setTimeout(()=>void Ie(o,j),1500);return}Re(),G({sessionId:o,status:"failed",message:re.error||re.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""})}catch(re){if(j!==ue.current)return;Re(),G({sessionId:o,status:"failed",message:re instanceof Error?re.message:"查询密码登录状态失败",qrCodeUrl:""})}},ss=async()=>{var F;if(!D)return;const o=N.username.trim();if(!o||!N.login_password){alert("请先填写登录账号和本次登录密码");return}Re(),(F=ve.current)==null||F.abort();const j=++ue.current;G({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const ae=await Ua({account_id:D.id,account:o,password:N.login_password,show_browser:N.show_browser});if(j!==ue.current)return;if(!ae.success||!ae.session_id)throw new Error(ae.message||"无法启动密码登录");G({sessionId:ae.session_id,status:"processing",message:ae.message||"登录处理中",qrCodeUrl:""}),await Ie(ae.session_id,j)}catch(ae){if(j!==ue.current)return;G({sessionId:"",status:"failed",message:ae instanceof Error?ae.message:"启动密码登录失败",qrCodeUrl:""})}},a=async()=>{var j;const o=w.sessionId;if(ue.current+=1,(j=ve.current)==null||j.abort(),Re(),o)try{await Va(o)}catch(F){console.error("取消密码登录失败",F)}G({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},g=async()=>{var o,j;(o=c.current)==null||o.cancel(),(j=be.current)==null||j.abort(),(w.status==="processing"||w.status==="verification_required")&&await a(),B(null)},v=()=>{var o,j;(o=C.current)==null||o.cancel(),(j=ye.current)==null||j.abort(),B(null)},ee=async(o,j)=>{const F=await Oa(o,j==null?void 0:j.id);if(!F.success||!F.account_id)throw new Error(F.message||"保存扫码授权失败");return F.account_id},xe=async o=>{var re,_e,$e,we;Fe(),(re=Se.current)==null||re.abort();const j=new AbortController;Se.current=j;const F=ie.current.next();Ae();const ae=o||null;ne(ae),R(!0),U("loading"),Q(""),S(""),de("");try{const Pe=await Fa({signal:j.signal});if(!((_e=ie.current)!=null&&_e.isCurrent(F)))return;if(Pe.success&&Pe.qr_code_url&&Pe.session_id){const Xe=Pe.session_id;Q(Pe.qr_code_url),U("waiting"),($e=me.current)==null||$e.start(Xe,Ta,{onSuccess:async()=>{try{if(!await ee(Xe,ae)){U("error");return}}catch(Oe){console.error("保存扫码授权失败",Oe),U("error");return}U("success"),Ye()},onScanned:()=>{U("waiting")},onTerminalError:()=>{U("error")},onPollError:Oe=>{console.error("轮询扫码状态失败",Oe),U("error")},onVerificationRequired:Oe=>{U("verification"),Oe.face_qr_url&&de(Oe.face_qr_url),Oe.verification_screenshot&&S(Oe.verification_screenshot)}})}}catch{if(!((we=ie.current)!=null&&we.isCurrent(F)))return;U("error")}};if(l)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(Le,{className:"w-8 h-8 text-[#0094f7] animate-spin"})});const je=s.filter(o=>{const j=u.trim().toLowerCase();return j?[o.id,o.nickname,o.remark,o.note,o.username,o.runtime_message].some(F=>(F||"").toLowerCase().includes(j)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:u,onChange:o=>b(o.target.value),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:()=>xe(),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Ss,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",je.length," / ",s.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[je.map(o=>{const j=V(o),F=o.runtime_state==="auth_expired"||o.runtime_state==="verification_required";return e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300",children:[e.jsxs("div",{className:"flex items-center gap-5 sm:gap-8 min-w-0",children:[e.jsxs("div",{className:"relative",children:[o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(Os,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${j.dot}`,children:o.runtime_state==="online"&&e.jsx(We,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:o.nickname||o.remark||`账号 ${o.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${j.badge}`,children:j.label}),o.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(rs,{className:"w-3 h-3"})," AI"]}),o.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:o.profile_error,children:[e.jsx(os,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"text-sm text-gray-500 font-medium mb-3 space-y-1",children:[e.jsx("p",{children:o.remark||o.note||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",o.id]})]}),o.runtime_message&&o.runtime_state!=="online"&&o.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${F?"text-red-700":"text-amber-700"}`,children:[e.jsx(os,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:o.runtime_message}),F&&e.jsxs("button",{type:"button",onClick:()=>xe(o),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(Ss,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),e.jsxs("div",{className:"flex gap-2",children:[o.auto_confirm&&e.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[e.jsx(We,{className:"w-3 h-3"})," 自动确认发货"]}),o.paused&&e.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[e.jsx(Hs,{className:"w-3 h-3"})," 暂停处理中"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 self-end lg:self-auto flex-shrink-0",children:[e.jsx("button",{onClick:()=>Be(o),disabled:k===o.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(qe,{className:`w-5 h-5 ${k===o.id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>xe(o),className:`p-3 rounded-xl transition-colors ${F?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(Ss,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>r(o),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Rt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>I(o),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(rs,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>he(o.id,o.enabled),className:`p-3 rounded-xl transition-colors ${o.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:o.enabled?"停用账号":"启用账号",children:e.jsx(sa,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Ce(o.id),className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500",children:e.jsx(Ve,{className:"w-5 h-5"})})]})]},o.id)}),s.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Os,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),s.length>0&&je.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),p&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:Ke,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:le?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:le?`请用闲鱼APP扫码,为「${le.nickname||le.remark||le.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-[#F7F8FA] rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${se==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[se==="loading"&&e.jsx(Le,{className:"w-10 h-10 text-[#0094f7] animate-spin"}),se==="waiting"&&e.jsx(ht,{src:f,alt:"闲鱼登录二维码",className:"p-2"}),se==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(We,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),se==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:"请关闭窗口后重新发起扫码登录。"})]}),se==="verification"&&e.jsx(Ql,{faceQrUrl:K,verificationScreenshot:J})]}),se!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),q==="edit"&&D&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:D.nickname||D.remark||D.id})]}),e.jsx("button",{onClick:()=>void g(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:D.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:N.remark,onChange:o=>y({...N,remark:o.target.value}),placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:N.cookie,onChange:o=>y({...N,cookie:o.target.value}),placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",N.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(We,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:()=>y({...N,auto_confirm:!N.auto_confirm}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${N.auto_confirm?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${N.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(Hs,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:N.pause_duration,onChange:o=>y({...N,pause_duration:parseInt(o.target.value)||0}),placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),N.pause_duration>0&&!D.paused&&N.pause_duration===(D.pause_duration||0)&&e.jsx("button",{type:"button",disabled:i,onClick:()=>void Qe(),className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(ta,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:N.username,onChange:o=>y({...N,username:o.target.value}),placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:N.showLoginPassword?"text":"password",value:N.login_password,onChange:o=>y({...N,login_password:o.target.value,clear_password:!1}),placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:()=>y({...N,showLoginPassword:!N.showLoginPassword}),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:N.showLoginPassword?e.jsx(ns,{className:"w-5 h-5"}):e.jsx(es,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:N.clear_password,onChange:o=>y({...N,clear_password:o.target.checked,login_password:o.target.checked?"":N.login_password}),className:"w-4 h-4 accent-[#0094f7]"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:()=>y({...N,show_browser:!N.show_browser}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${N.show_browser?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${N.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),w.status==="processing"||w.status==="verification_required"?e.jsx("button",{type:"button",onClick:a,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:ss,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),w.message&&e.jsx("div",{className:`text-sm font-medium ${w.status==="failed"?"text-red-700":w.status==="success"?"text-green-700":"text-blue-800"}`,children:w.message}),w.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),w.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(ht,{src:w.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(W.length>0||h||m)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(is,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),h&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Le,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),m&&!h&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:()=>Te(D.id),children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:W.map(o=>{const j=Y.includes(Number(o.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:()=>{te&&(L(F=>j?F.filter(ae=>ae!==Number(o.id)):[...F,Number(o.id)]),X(!0))},disabled:!te,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${j?"bg-[#0094f7] border-[#0094f7]":"bg-white border-gray-300"}`,children:j&&e.jsx(We,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:o.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[o.type,o.enabled?"":" · 已停用"]})]})]},o.id)})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>void g(),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:i,children:"取消"}),e.jsxs("button",{onClick:ce,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:i,children:[i?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Je,{className:"w-4 h-4"}),i?"保存中...":"保存"]})]})})]})}),document.body),q==="ai-settings"&&D&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(rs,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:D.nickname||D.remark||D.id})]}),e.jsx("button",{onClick:v,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(rs,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:()=>M({...P,ai_enabled:!P.ai_enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${P.ai_enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${P.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:P.max_discount_percent,onChange:o=>M({...P,max_discount_percent:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:P.max_discount_amount,onChange:o=>M({...P,max_discount_amount:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:P.max_bargain_rounds,onChange:o=>M({...P,max_bargain_rounds:parseInt(o.target.value)||1}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:P.custom_prompts,onChange:o=>M({...P,custom_prompts:o.target.value}),placeholder:`输入自定义的AI回复规则或风格指引... - -例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(zs,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:v,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:i,children:"取消"}),e.jsxs("button",{onClick:ze,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:i,children:[i?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Je,{className:"w-4 h-4"}),i?"保存中...":"保存"]})]})})]})}),document.body)]})},Yl=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),Xl=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],gt=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},Zl=()=>{const[s,t]=n.useState([]),[l,d]=n.useState([]),[u,b]=n.useState({}),[k,O]=n.useState("all"),[p,R]=n.useState(""),[f,Q]=n.useState(""),se=n.useRef(0),[U,J]=n.useState(1),[S,K]=n.useState(1),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState(!1),[Z,W]=n.useState(!1),[A,Y]=n.useState(null),[L,te]=n.useState(null),[T,h]=n.useState({}),[$,z]=n.useState(!1),[X,m]=n.useState(""),[_,N]=n.useState(!1),[y,P]=n.useState(null),[M,i]=n.useState(null),[E,w]=n.useState(null),[G,me]=n.useState(!1),[ie,H]=n.useState(null),[c,C]=n.useState(null),oe=async()=>{const x=++se.current;le(!0);try{const V=await Qa(void 0,k,U,20,f);if(x!==se.current)return;t(V.data),K(V.total_pages)}catch(V){console.error("加载订单失败:",V)}finally{x===se.current&&le(!1)}},be=(x,V)=>{if(V&&V.trim())return V;if(u[x])return u[x];const he=l.find(Ce=>{if(V&&Ce.item_title){const Be=V.toLowerCase(),Te=Ce.item_title.toLowerCase();return Te.includes(Be)||Be.includes(Te)}return!1});return he!=null&&he.item_title?he.item_title:"未知商品"},ye=x=>{const V={};x.forEach(he=>{he.item_id&&(V[he.item_id]=he.item_title||he.item_id)}),b(V)};n.useEffect(()=>{const x=window.setTimeout(()=>{J(1),Q(p.trim())},300);return()=>window.clearTimeout(x)},[p]),n.useEffect(()=>{oe()},[k,U,f]),n.useEffect(()=>{ds().then(x=>{d(x),ye(x)}).catch(x=>{console.error("加载商品列表失败:",x)})},[]);const Se=async()=>{le(!0);try{const x=await Xa();await oe(),x!=null&&x.message&&alert(x.message)}catch(x){console.error("同步订单失败:",x),alert((x==null?void 0:x.message)||"同步失败,请重试")}finally{le(!1)}},ve=x=>{m(x),P(null),z(!0)},fe=async x=>{var V;N(!0),P(null);try{const he=await Ha([X],x),Ce=(V=he==null?void 0:he.results)==null?void 0:V[0];Ce!=null&&Ce.success?(P({success:!0,message:Ce.message}),oe()):P({success:!1,message:(Ce==null?void 0:Ce.message)||"发货失败"})}catch(he){P({success:!1,message:(he==null?void 0:he.message)||"请求失败"})}finally{N(!1)}},De=x=>{Y(x),q(!0)},ue=x=>{te({...x}),D(!0)},Ae=async()=>{if(!(!L||!L.order_id))try{const x={};L.status!==void 0&&(x.order_status=L.status),L.buyer_id!==void 0&&(x.buyer_id=L.buyer_id),L.amount!==void 0&&(x.amount=L.amount),L.receiver_name!==void 0&&(x.receiver_name=L.receiver_name),L.receiver_phone!==void 0&&(x.receiver_phone=L.receiver_phone),L.receiver_address!==void 0&&(x.receiver_address=L.receiver_address),L.item_id!==void 0&&(x.item_id=L.item_id),L.quantity!==void 0&&(x.quantity=L.quantity),L.item_title!==void 0&&(x.item_title=L.item_title),await Ka(L.order_id,x),D(!1),te(null),oe()}catch(x){console.error("更新订单失败:",x),alert("更新失败,请重试")}},Re=async()=>{if(M){me(!0);try{const x=new FormData;x.append("file",M);const V=Yl(await el(x));w(V),i(null),await oe(),V.failed_count===0&&(W(!1),w(null),alert(`订单导入成功,共 ${V.success_count} 条`))}catch(x){alert((x==null?void 0:x.message)||"导入失败,请检查文件格式")}finally{me(!1)}}},Fe=()=>{G||(W(!1),i(null),w(null))},Ke=async x=>{H(x);try{const V=await Za(x);V.success?await oe():alert(V.message||"同步失败")}catch(V){console.error("同步订单失败:",V),alert((V==null?void 0:V.message)||"同步失败,请重试")}finally{H(null)}},Ye=async x=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){C(x);try{await Ya(x),s.length===1&&U>1?J(V=>V-1):await oe()}catch(V){console.error("删除订单失败:",V),alert((V==null?void 0:V.message)||"删除失败,请重试"),await oe()}finally{C(null)}}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:oe,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(qe,{className:`w-5 h-5 ${de?"animate-spin":""}`})}),e.jsxs("button",{onClick:()=>{w(null),W(!0)},className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(Ge,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:Se,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(et,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-[#FAFAFA]",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:[{k:"all",v:"全部"},{k:"processing",v:"处理中"},{k:"shipped",v:"已发货"},{k:"pending_ship",v:"待发货"},{k:"completed",v:"已完成"},{k:"cancelled",v:"已取消"},{k:"refunding",v:"退款中"}].map(x=>e.jsx("button",{onClick:()=>{O(x.k),J(1),R("")},className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${k===x.k?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:x.v},x.k))}),e.jsxs("div",{className:"relative w-full md:w-auto group",children:[e.jsx(aa,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0094f7] transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:x=>{R(x.target.value),J(1)},className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(x=>e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:x.item_image?e.jsx("img",{src:x.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(gs,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:be(x.item_id,x.item_title)}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",x.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",x.quantity," • ",x.created_at]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:x.buyer_id}),x.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:x.receiver_name})]}),x.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:x.receiver_phone})]}),x.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:x.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:x.amount?`¥${x.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(gt,{status:x.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[x.status==="pending_ship"&&e.jsx("button",{onClick:()=>ve(x.order_id),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${x.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(It,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>De(x),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(es,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>ue(x),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(cs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Ke(x.order_id),disabled:ie===x.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(qe,{className:`w-4 h-4 ${ie===x.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>Ye(x.order_id),disabled:c===x.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(Ve,{className:"w-4 h-4"})})]})]},x.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",U," 页 / 共 ",S," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:U<=1,onClick:()=>J(x=>x-1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(la,{className:"w-5 h-5"})}),e.jsx("button",{disabled:U>=S,onClick:()=>J(x=>x+1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(ra,{className:"w-5 h-5"})})]})]})]}),ne&&A&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:()=>q(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:A.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(gt,{status:A.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:A.amount?`¥${A.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:A.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:A.created_at})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[A.item_image&&e.jsx("img",{src:A.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:be(A.item_id,A.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",A.item_id]}),A.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",A.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:A.buyer_id})]}),A.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:A.receiver_name})]}),A.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:A.receiver_phone})]}),A.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:A.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>q(!1),className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),A.status==="pending_ship"&&e.jsx("button",{onClick:()=>{q(!1),ve(A.order_id)},className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),Z&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:Fe,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:x=>{var V;return i(((V=x.target.files)==null?void 0:V[0])||null)},className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),M&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:M.name})]})}),E&&E.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",E.success_count," 条,失败 ",E.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:Xl(E).map((x,V)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:x.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:x.message||"导入失败"})]},`${x.order_id}-${V}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Fe,disabled:G,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:Re,disabled:!M||G,className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:G?"正在导入…":"导入订单"})]})})]})}),document.body),$&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),e.jsx("button",{onClick:()=>{z(!1),P(null)},className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:()=>fe("status_only"),disabled:_,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(et,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:()=>fe("full_delivery"),disabled:_,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-[#0094f7] hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(gs,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),_&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(qe,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),y&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${y.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[y.success?"✓ ":"✗ ",y.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:()=>{z(!1),P(null)},className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:y!=null&&y.success?"完成":"取消"})})]})}),document.body),B&&L&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:()=>D(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:L.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:L.status,onChange:x=>te({...L,status:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:L.buyer_id,onChange:x=>te({...L,buyer_id:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:L.amount,onChange:x=>te({...L,amount:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:L.receiver_name||"",onChange:x=>te({...L,receiver_name:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:L.receiver_phone||"",onChange:x=>te({...L,receiver_phone:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:L.receiver_address||"",onChange:x=>te({...L,receiver_address:x.target.value}),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:L.item_title||"",onChange:x=>te({...L,item_title:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>D(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Ae,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},bt=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),Hl=()=>{const[s,t]=n.useState([]),[l,d]=n.useState(!1),[u,b]=n.useState(!1),[k,O]=n.useState(null),[p,R]=n.useState({}),[f,Q]=n.useState(bt),[se,U]=n.useState(!1),[J,S]=n.useState("create"),[K,de]=n.useState(null),[le,ne]=n.useState(null),[q,B]=n.useState(!1),[D,Z]=n.useState(""),[W,A]=n.useState(""),[Y,L]=n.useState(null);n.useEffect(()=>{Ue().then(t)},[]);const te=({type:i})=>{switch(i){case"text":return e.jsx(st,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(tt,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(ca,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Fs,{className:"w-5 h-5 text-gray-500"})}},T=i=>{var E,w,G,me,ie;O(i),R({id:i.id,name:i.name||"",type:i.type||"text",api_url:((E=i.api_config)==null?void 0:E.url)||"",api_method:((w=i.api_config)==null?void 0:w.method)||"GET",api_timeout:((G=i.api_config)==null?void 0:G.timeout)||10,api_headers:((me=i.api_config)==null?void 0:me.headers)||"",api_params:((ie=i.api_config)==null?void 0:ie.params)||"",text_content:i.text_content||"",data_content:i.data_content||"",image_url:i.image_url||"",delay_seconds:i.delay_seconds||0,description:i.description||"",enabled:i.enabled}),d(!0)},h=async()=>{var i,E,w,G,me,ie,H,c;if(k){if(!((i=p.name)!=null&&i.trim())){alert("请输入卡密名称");return}if(!p.type){alert("请选择卡密类型");return}try{const C={name:p.name.trim(),type:p.type,description:(E=p.description)==null?void 0:E.trim(),delay_seconds:p.delay_seconds||0,enabled:p.enabled??!0};p.type==="api"?C.api_config={url:((w=p.api_url)==null?void 0:w.trim())||"",method:p.api_method,timeout:p.api_timeout||10,headers:((G=p.api_headers)==null?void 0:G.trim())||void 0,params:((me=p.api_params)==null?void 0:me.trim())||void 0}:p.type==="text"?C.text_content=((ie=p.text_content)==null?void 0:ie.trim())||"":p.type==="data"?C.data_content=((H=p.data_content)==null?void 0:H.trim())||"":p.type==="image"&&(C.image_url=((c=p.image_url)==null?void 0:c.trim())||""),await dt(k.id,C),d(!1),Ue().then(t)}catch(C){console.error("更新卡密失败:",C),alert("更新失败,请重试")}}},$=async i=>{if(confirm("确认删除该卡密吗?"))try{await rl(i),Ue().then(t)}catch(E){console.error("删除卡密失败:",E),alert("删除失败,请重试")}},z=async()=>{if(!f.name.trim()){alert("请输入卡密名称");return}if(!f.content.trim()){alert(f.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const i={name:f.name.trim(),type:f.type,description:f.description.trim(),enabled:f.enabled,delay_seconds:f.delay_seconds};f.type==="text"&&(i.text_content=f.content.trim()),f.type==="data"&&(i.data_content=f.content.trim()),f.type==="image"&&(i.image_url=f.content.trim()),f.type==="api"&&(i.api_config={url:f.content.trim(),method:f.api_method,timeout:f.api_timeout,headers:f.api_headers.trim()||void 0,params:f.api_params.trim()||void 0}),await ll(i),b(!1),Q(bt()),Ue().then(t)}catch(i){console.error("添加卡密失败:",i),alert("添加失败,请重试")}},X=async i=>{try{await dt(i.id,{...i,enabled:!i.enabled}),Ue().then(t)}catch(E){console.error("切换状态失败:",E)}},m=async i=>{try{await navigator.clipboard.writeText(String(i)),alert(`已复制卡密组ID:${i}`)}catch{prompt("复制卡密组ID",String(i))}},_=s.filter(i=>i.type==="data"),N=()=>{const w=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 -VIP-MONTH-002 -VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(H=>H.map(c=>`"${String(c).replace(/"/g,'""')}"`).join(",")).join(` -`),G=new Blob(["\uFEFF"+w],{type:"text/csv;charset=utf-8"}),me=URL.createObjectURL(G),ie=document.createElement("a");ie.href=me,ie.download="卡密组批量导入模板.csv",document.body.appendChild(ie),ie.click(),ie.remove(),URL.revokeObjectURL(me)},y=async()=>{if(K){B(!0),ne(null);try{const i=await nl(K);if(ne(i),i.created>0){const E=await Ue();t(E)}}catch(i){ne({error:(i==null?void 0:i.message)||"上传失败"})}finally{B(!1)}}},P=async()=>{if(!(!D||!W.trim())){B(!0),L(null);try{const i=await il(D,W);L({added:i.added}),A("");const E=await Ue();t(E)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{B(!1)}}},M=()=>{var i;S("create"),de(null),ne(null),Z((i=_[0])!=null&&i.id?String(_[0].id):""),A(""),L(null),U(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:M,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(hs,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>b(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Ge,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-8 py-5 w-[18%]",children:"卡密名称"}),e.jsx("th",{className:"px-6 py-5 w-[12%]",children:"卡密组ID"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"类型"}),e.jsx("th",{className:"px-6 py-5 w-[22%]",children:"内容/库存"}),e.jsx("th",{className:"px-6 py-5 w-[18%]",children:"描述"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"状态"}),e.jsx("th",{className:"px-6 py-5 w-[10%] text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(i=>{let E="";return i.type==="data"&&i.data_content?E=`库存: ${i.data_content.split(` -`).filter(G=>G.trim()).length} 条`:i.type==="text"&&i.text_content?E=i.text_content.substring(0,20)+(i.text_content.length>20?"...":""):i.type==="api"&&i.api_config?E=i.api_config.url:i.type==="image"&&i.image_url&&(E="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-8 py-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors",children:e.jsx(te,{type:i.type})}),e.jsx("span",{className:"font-bold text-gray-900",children:i.name})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("button",{onClick:()=>m(i.id),className:"inline-flex items-center gap-2 rounded-xl bg-gray-100 px-3 py-2 font-mono text-xs font-extrabold text-gray-700 hover:bg-gray-200 transition-colors",title:"复制卡密组ID,用于批量铺货表格",children:[i.id,e.jsx(na,{className:"w-3.5 h-3.5"})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-600 font-mono block truncate",title:E,children:E})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-500 block max-w-[200px] truncate",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("button",{onClick:()=>X(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>T(i),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(cs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>$(i.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:e.jsx(Ve,{className:"w-5 h-5"})})]})})]},i.id)})})]})}),s.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(At,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),l&&k&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>d(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:p.name||"",onChange:i=>R({...p,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:p.type||"text",onChange:i=>R({...p,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(k==null?void 0:k.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),p.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:p.api_url||"",onChange:i=>R({...p,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:p.api_method||"GET",onChange:i=>R({...p,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"超时时间(秒)"}),e.jsx("input",{type:"number",value:p.api_timeout||10,onChange:i=>R({...p,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:p.api_headers||"",onChange:i=>R({...p,api_headers:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"Authorization": "Bearer token"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:p.api_params||"",onChange:i=>R({...p,api_params:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"type": "card", "count": 1}'})]})]}),p.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:p.text_content||"",onChange:i=>R({...p,text_content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),p.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:p.data_content||"",onChange:i=>R({...p,data_content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个: -卡号1:密码1 -卡号2:密码2 -或者 -兑换码1 -兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:p.data_content?p.data_content.split(` -`).filter(i=>i.trim()).length:0})," 条"]})]})]}),p.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:p.image_url||"",onChange:i=>R({...p,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),p.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:p.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:p.delay_seconds||0,onChange:i=>R({...p,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:p.description||"",onChange:i=>R({...p,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>R({...p,enabled:!p.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${p.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${p.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>d(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:h,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),u&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>b(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:f.name,onChange:i=>Q({...f,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Fs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(st,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(tt,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:f.type==="data"?"库存内容(一行一个)":f.type==="text"?"固定回复内容":f.type==="image"?"图片 URL":"API 地址"}),f.type==="api"?e.jsx("input",{type:"url",value:f.content,onChange:i=>Q({...f,content:i.target.value}),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):f.type==="image"?e.jsx("input",{type:"url",value:f.content,onChange:i=>Q({...f,content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}):e.jsx("textarea",{value:f.content,onChange:i=>Q({...f,content:i.target.value}),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${f.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:f.type==="data"?`CODE-123456 -CODE-789012 -...`:"请输入每次发货时发送的固定文字"}),f.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:f.content.split(` -`).filter(i=>i.trim()).length})," 条"]})]}),f.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:f.api_method,onChange:i=>Q({...f,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:f.api_timeout,onChange:i=>Q({...f,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:f.api_headers,onChange:i=>Q({...f,api_headers:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:f.api_params,onChange:i=>Q({...f,api_params:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:f.description,onChange:i=>Q({...f,description:i.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:f.delay_seconds,onChange:i=>Q({...f,delay_seconds:parseInt(i.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>b(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:z,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),se&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>U(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>S("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${J==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(ia,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>S("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${J==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(hs,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),J==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:N,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(oa,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx(hs,{className:"w-4 h-4"}),K?K.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:i=>{var E;return de(((E=i.target.files)==null?void 0:E[0])||null)}})]})]}),le&&!le.error&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",le.total," 行 · 成功 ",le.created," · 失败 ",le.failed]}),le.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:le.rows.filter(i=>!i.success).map(i=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",i.row_no," 行「",i.name,"」:",i.error]},i.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:_.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:D,onChange:i=>Z(i.target.value),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:_.map(i=>e.jsxs("option",{value:String(i.id),children:[i.name,"(ID: ",i.id,")"]},i.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{value:W,onChange:i=>A(i.target.value),placeholder:`VIP-001 -VIP-002 -VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),Y&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",Y.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>U(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),J==="create"?e.jsxs("button",{onClick:y,disabled:!K||q,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[q?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(hs,{className:"w-4 h-4"}),q?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:P,disabled:!D||!W.trim()||q||_.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[q?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Ge,{className:"w-4 h-4"}),q?"处理中...":"追加卡密"]})]})]})}),document.body)]})},er=s=>s.find(t=>t.status==="running"||t.status==="canceling"),sr=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},tr=({onConfigureDelivery:s})=>{const[t,l]=n.useState([]),[d,u]=n.useState([]),[b,k]=n.useState([]),[O,p]=n.useState(""),[R,f]=n.useState(!1),[Q,se]=n.useState(!1),[U,J]=n.useState(!1),[S,K]=n.useState(!1),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState(!1),[Z,W]=n.useState("upload"),[A,Y]=n.useState(null),[L,te]=n.useState(null),[T,h]=n.useState(null),[$,z]=n.useState(null),[X,m]=n.useState(null),_=n.useRef(!1),[N,y]=n.useState(null),[P,M]=n.useState({}),[i,E]=n.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[w,G]=n.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[me,ie]=n.useState([]);n.useEffect(()=>{if(!ne||w.images.length===0){ie([]);return}const r=w.images.map((I,ce)=>({key:I.name+ce,url:URL.createObjectURL(I)}));return ie(r),()=>{r.forEach(I=>URL.revokeObjectURL(I.url))}},[ne,w.images]);const H=async()=>{const r=await ds();l(r)},c=async()=>{u(await ks())};n.useEffect(()=>{Promise.all([Vs(),ds(),ks(),xt(20)]).then(([r,I,ce,Qe])=>{k(r),l(I),u(ce);const ze=Qe.find(Ie=>["running","canceling"].includes(Ie.status))||Qe.find(Ie=>Ie.status!=="preview");m(ze||null)}).catch(r=>console.error("加载商品配置失败:",r))},[]),n.useEffect(()=>{if(!B||!($!=null&&$.id)||!["running","canceling"].includes($.status))return;const r=window.setInterval(async()=>{if(!_.current){_.current=!0;try{const I=await as($.id);z(I),m(I),["running","canceling"].includes(I.status)||(W("done"),await H(),await c())}catch(I){console.error("刷新批量铺货进度失败:",I)}finally{_.current=!1}}},3e3);return()=>{window.clearInterval(r)}},[B,$==null?void 0:$.id,$==null?void 0:$.status]);const C=async()=>{if(!O)return alert("请先选择账号");f(!0);try{const r=await ol(O);await H(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{f(!1)}},oe=r=>{y(r),M({...r}),K(!0)},be=async()=>{if(N)try{await bl(N.cookie_id,N.item_id,{item_title:P.item_title||"",item_description:P.item_description||"",item_category:P.item_category||"",item_price:P.item_price||"",item_detail:P.item_detail||N.item_detail||""}),await H(),await c(),K(!1),y(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},ye=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await cl(r.cookie_id,r.item_id),l(I=>I.filter(ce=>!(ce.cookie_id===r.cookie_id&&ce.item_id===r.item_id)))}catch(I){console.error("删除商品失败:",I),alert("删除失败,请重试")}},Se=async()=>{try{if(!i.cookie_id||!i.item_id){alert("请选择账号并填写商品ID");return}await dl(i.cookie_id,{item_id:i.item_id,item_title:i.item_title,item_price:i.item_price,item_detail:i.item_image?JSON.stringify({item_image:i.item_image}):""}),await H(),le(!1),E({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},ve=async()=>{if(!w.cookie_id)return alert("请选择发布账号");if(!w.title.trim())return alert("请填写商品标题");if(!w.price.trim())return alert("请填写商品价格");if(!w.quantity||Number(w.quantity)<=0)return alert("库存数量必须大于 0");if(w.images.length===0)return alert("至少上传 1 张商品图片");if(w.postage_mode==="fixed"&&!w.postage.trim())return alert("请填写一口价邮费");se(!0);try{const r=await xl(w);if(await H(),q(!1),G({cookie_id:O||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),r!=null&&r.item_id){const I={id:r.item_id,cookie_id:w.cookie_id,item_id:r.item_id,item_title:r.item_title||w.title,item_price:r.item_price||w.price,item_image:r.item_image};s(I),alert("商品发布成功,ID: "+r.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(r){console.error("发布商品失败:",r);const I=r==null?void 0:r.payload;if((I==null?void 0:I.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((r==null?void 0:r.message)||"发布失败,请重试")}finally{se(!1)}},fe=async()=>{W("upload"),h(null),z(null),Y(null),te(null),D(!0),J(!0);try{const r=await xt(20),I=er(r);if(I!=null&&I.id){const ce=await as(I.id);m(ce),z(ce),W(["running","canceling"].includes(ce.status)?"running":"done")}}catch(r){console.error("恢复最近批量铺货任务失败:",r)}finally{J(!1)}},De=async()=>{if(X!=null&&X.id){J(!0),D(!0);try{const r=await as(X.id);z(r),W(["running","canceling"].includes(r.status)?"running":"done")}catch(r){console.error("加载最近批量铺货结果失败:",r)}finally{J(!1)}}},ue=async()=>{if(!A)return alert("请先上传商品表格");if(!O)return alert("请先选择默认发布账号");J(!0);try{const r=await ml({file:A,imagesZip:L,defaultCookieId:O});h(r),z(null),W("preview")}catch(r){console.error("批量铺货预检失败:",r),alert((r==null?void 0:r.message)||"预检失败,请检查表格和图片 zip")}finally{J(!1)}},Ae=async()=>{if(T!=null&&T.preview_id){if(T.valid<=0)return alert("没有可发布的商品行");J(!0);try{const r=await ul(T.preview_id),I=await as(r.batch_id||T.preview_id);z(I),m(I),W(I.status==="running"?"running":"done")}catch(r){console.error("启动批量铺货失败:",r),alert((r==null?void 0:r.message)||"启动发布任务失败")}finally{J(!1)}}},Re=async()=>{if($!=null&&$.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){J(!0);try{const r=await hl($.id),I=await as($.id);z(I),W((r==null?void 0:r.status)==="canceling"||I.status==="canceling"?"running":"done")}catch(r){alert((r==null?void 0:r.message)||"取消失败")}finally{J(!1)}}},Fe=async()=>{const r=T==null?void 0:T.preview_id;if(r&&Z==="preview")try{await pl(r)}catch(I){console.error("清理批量铺货预检失败:",I)}h(null),W("upload")},Ke=async()=>{await Fe(),D(!1)},Ye=async()=>{if($!=null&&$.id){J(!0);try{await gl($.id),z(await as($.id)),W("running")}catch(r){alert((r==null?void 0:r.message)||"重试失败")}finally{J(!1)}}},x=()=>{const ce=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","否","","否","","否","","",""]]].map(ss=>ss.map(a=>`"${String(a).replace(/"/g,'""')}"`).join(",")).join(` -`),Qe=new Blob(["\uFEFF"+ce],{type:"text/csv;charset=utf-8"}),ze=URL.createObjectURL(Qe),Ie=document.createElement("a");Ie.href=ze,Ie.download="批量铺货模板.csv",document.body.appendChild(Ie),Ie.click(),Ie.remove(),URL.revokeObjectURL(ze)},V=()=>{E(r=>({...r,cookie_id:O||r.cookie_id})),le(!0)},he=()=>{G(r=>({...r,cookie_id:O||r.cookie_id})),q(!0)},Ce=r=>d.filter(I=>I.cookie_id===r.cookie_id&&I.item_id===r.item_id).length>0?d.filter(I=>I.cookie_id===r.cookie_id&&I.item_id===r.item_id):d.filter(I=>I.cookie_id===r.cookie_id&&!I.item_id),Be=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},Te=r=>{switch(r){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("select",{className:"ios-input px-4 py-3 rounded-xl text-sm",value:O,onChange:r=>p(r.target.value),children:[e.jsx("option",{value:"",children:"选择账号以同步"}),b.map(r=>e.jsx("option",{value:r.id,children:r.nickname},r.id))]}),e.jsxs("button",{onClick:C,disabled:R||!O,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${R?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:V,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Ge,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:he,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(As,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void fe(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(ys,{className:"w-4 h-4"}),X&&["running","canceling"].includes(X.status)?"继续批量任务":"批量铺货"]}),X&&!["running","canceling"].includes(X.status)&&e.jsx("button",{onClick:()=>void De(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[t.map(r=>{const I=Ce(r),ce=I.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:()=>oe(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:e.jsx(cs,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>ye(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(Ve,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[r.item_image?e.jsx("img",{src:r.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Ct,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:sr(r.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:r.item_title}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",r.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${ce?"text-emerald-600":"text-amber-600"}`,children:[ce?e.jsx($t,{className:"w-3 h-3"}):e.jsx(da,{className:"w-3 h-3"}),ce?`${I.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>s(r),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${ce?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xa,{className:"w-3.5 h-3.5"}),ce?"查看发货规则":"关联发货规则"]}),e.jsx(qs,{className:"w-3.5 h-3.5"})]})})]},`${r.cookie_id}-${r.item_id}`)}),t.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(kt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),"暂无商品数据,请选择账号进行同步"]})]}),S&&N&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"560px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"编辑商品"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["ID: ",N.item_id]})]}),e.jsx("button",{onClick:()=>K(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"商品标题",value:P.item_title||"",onChange:r=>M({...P,item_title:r.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:P.item_price||"",onChange:r=>M({...P,item_price:r.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:P.item_category||"",onChange:r=>M({...P,item_category:r.target.value})}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:P.item_description||"",onChange:r=>M({...P,item_description:r.target.value})})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:be,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),de&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"720px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"添加商品"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"手动建立商品与自动发货规则的关联"})]}),e.jsx("button",{onClick:()=>le(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"所属账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:i.cookie_id,onChange:r=>E({...i,cookie_id:r.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),b.map(r=>e.jsx("option",{value:r.id,children:r.nickname||r.remark||r.id},r.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品 ID"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入闲鱼商品 ID",value:i.item_id,onChange:r=>E({...i,item_id:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品价格"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 99.00",value:i.item_price,onChange:r=>E({...i,item_price:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入商品标题",value:i.item_title,onChange:r=>E({...i,item_title:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"图片 URL"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://...",value:i.item_image,onChange:r=>E({...i,item_image:r.target.value})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:Se,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),ne&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"820px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"发布商品到闲鱼"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。"})]}),e.jsx("button",{onClick:()=>q(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 leading-6",children:"发布时必须填写库存。若账号没有库存发布能力,后端会返回明确的“库存权限不足”错误,不会误报为普通发布失败。"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:w.cookie_id,onChange:r=>G({...w,cookie_id:r.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),b.map(r=>e.jsx("option",{value:r.id,children:r.nickname||r.remark||r.id},r.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:会员月卡自动发货",value:w.title,onChange:r=>G({...w,title:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"库存数量"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",type:"number",min:"1",placeholder:"必须大于 0",value:w.quantity,onChange:r=>G({...w,quantity:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品描述"}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述会用于自动识别类目;留空时使用标题",value:w.description,onChange:r=>G({...w,description:r.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"售价"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"99.00",value:w.price,onChange:r=>G({...w,price:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"原价(可选)"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"129.00",value:w.original_price,onChange:r=>G({...w,original_price:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"运费方式"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:w.postage_mode,onChange:r=>G({...w,postage_mode:r.target.value}),children:[e.jsx("option",{value:"free",children:"包邮"}),e.jsx("option",{value:"distance",children:"按距离计费"}),e.jsx("option",{value:"fixed",children:"一口价邮费"}),e.jsx("option",{value:"none",children:"无需邮寄"})]})]})]}),w.postage_mode==="fixed"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"一口价邮费"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 8.00",value:w.postage,onChange:r=>G({...w,postage:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品图片(1-9 张)"}),e.jsxs("label",{className:"flex min-h-[120px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50/50 transition-colors",children:[e.jsx(ys,{className:"w-8 h-8 text-emerald-600 mb-2"}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"选择图片"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:w.images.length?"已选择 "+w.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:r=>G({...w,images:Array.from(r.target.files||[]).slice(0,9)})})]}),me.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:me.map(r=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:r.url,alt:"",className:"w-full h-full object-cover"})},r.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:Q,onClick:ve,className:"w-full bg-emerald-600 hover:bg-emerald-700 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(As,{className:"w-4 h-4"}),Q?"正在发布...":"发布到闲鱼"]})})]})}),document.body),B&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"980px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量铺货"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。"})]}),e.jsx("button",{onClick:()=>void Ke(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]].map(([r,I])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${Z===r?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:I},r))}),Z==="upload"&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900 leading-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:"先下载模板,再按字段填写。"}),e.jsxs("div",{children:["图片字段写 zip 内相对路径,多个图片用英文分号分隔,例如 ",e.jsx("span",{className:"font-mono font-bold",children:"images/a.jpg;images/b.jpg"}),"。也支持直接填写图片 URL。"]})]}),e.jsx("button",{type:"button",onClick:x,className:"shrink-0 rounded-xl bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700",children:"下载CSV模板"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"默认发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:O,onChange:r=>p(r.target.value),children:[e.jsx("option",{value:"",children:"选择账号"}),b.map(r=>e.jsx("option",{value:r.id,children:r.nickname||r.remark||r.id},r.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors",children:[e.jsx(ys,{className:"w-9 h-9 text-blue-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传商品表格"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:A?A.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:r=>{var I;return Y(((I=r.target.files)==null?void 0:I[0])||null)}})]}),e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors",children:[e.jsx(ys,{className:"w-9 h-9 text-emerald-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传图片 zip(可选)"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:L?L.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:r=>{var I;return te(((I=r.target.files)==null?void 0:I[0])||null)}})]})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"字段说明"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。"})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950",children:[e.jsx("div",{className:"text-sm font-extrabold",children:"“付款后发送的卡密”怎么填"}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101"}),e.jsx("p",{className:"mt-1 leading-5",children:"从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:2"}),e.jsx("p",{className:"mt-1 leading-5",children:"每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:1:0;102:2:3"}),e.jsx("p",{className:"mt-1 leading-5",children:"先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。"})]})]}),e.jsxs("p",{className:"mt-3 leading-5 text-blue-800",children:["每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 ",e.jsx("code",{className:"font-bold",children:";"})," 隔开。"]})]}),e.jsx("div",{className:"overflow-x-auto rounded-xl border border-gray-100 bg-white",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"字段"}),e.jsx("th",{className:"px-3 py-2",children:"什么时候填写"}),e.jsx("th",{className:"px-3 py-2",children:"填写方法"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 text-gray-700",children:[["账号ID","没有在上方选择默认账号时填写","填写账号 ID;已经选择默认账号时可以留空"],["标题","每个商品都要填","填写买家能看到的商品标题"],["描述","可以留空","留空时会使用商品标题作为描述"],["价格","每个商品都要填","只填数字,例如 19.90"],["原价","可以留空","需要展示划线原价时填写,例如 29.90"],["库存","可以留空","留空按 1 件处理;填写时必须大于 0"],["邮费模式","可以留空","留空表示包邮;包邮填 free,固定邮费填 fixed"],["邮费","邮费模式填 fixed 时填写","只填数字,例如 8.00"],["图片","每个商品都要填","填写 zip 内图片路径或图片网址;多张图片用英文分号隔开"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([r,I,ce])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:r}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${I==="每个商品都要填"?"text-red-600":I==="可以留空"?"text-gray-500":"text-amber-700"}`,children:I}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:ce})]},r))})]})})]})]}),Z==="preview"&&T&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总行数"}),e.jsx("div",{className:"text-2xl font-extrabold text-gray-900 mt-1",children:T.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"可发布"}),e.jsx("div",{className:"text-2xl font-extrabold text-emerald-700 mt-1",children:T.valid})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"有问题"}),e.jsx("div",{className:"text-2xl font-extrabold text-red-700 mt-1",children:T.invalid})]})]}),e.jsx("div",{className:"max-h-[380px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"价格/库存"}),e.jsx("th",{className:"px-4 py-3",children:"图片"}),e.jsx("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:T.rows.map(r=>{var I,ce;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:r.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${r.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:r.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:r.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",r.price||"-"," / ",r.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((I=r.images)==null?void 0:I.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((ce=r.errors)==null?void 0:ce.join(";"))||"-"})]},r.row_no)})})]})})]}),(Z==="running"||Z==="done")&&$&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:`rounded-2xl p-4 border ${Te($.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:Be($.status)})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总数"}),e.jsx("div",{className:"text-xl font-extrabold text-gray-900 mt-1",children:$.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"成功"}),e.jsx("div",{className:"text-xl font-extrabold text-emerald-700 mt-1",children:$.success})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"失败"}),e.jsx("div",{className:"text-xl font-extrabold text-red-700 mt-1",children:$.failed})]}),e.jsxs("div",{className:"rounded-2xl bg-blue-50 p-4 border border-blue-100",children:[e.jsx("div",{className:"text-xs font-bold text-blue-700",children:"等待"}),e.jsx("div",{className:"text-xl font-extrabold text-blue-700 mt-1",children:$.pending})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"商品ID"}),e.jsx("th",{className:"px-4 py-3",children:"错误原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:$.rows.map(r=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:r.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${Te(r.status)}`,children:Be(r.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:r.title}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:r.item_url?e.jsx("a",{href:r.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:r.item_id}):r.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:r.error_message||"-"})]},r.id))})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[Z==="upload"&&e.jsxs("button",{disabled:U||!A||!O,onClick:ue,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${U?"animate-spin":""}`}),U?"正在预检...":"开始预检"]}),Z==="preview"&&T&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:U,onClick:()=>void Fe(),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"返回修改"}),e.jsxs("button",{disabled:U||T.valid<=0,onClick:Ae,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(As,{className:"w-4 h-4"}),U?"启动中...":`确认发布 ${T.valid} 个商品`]})]}),(Z==="running"||Z==="done")&&$&&e.jsxs("div",{className:"flex gap-3 w-full",children:[$.status==="running"?e.jsx("button",{disabled:U,onClick:Re,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):$.status==="canceling"?e.jsx("button",{disabled:!0,className:"flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold",children:"正在保存远端结果并安全取消…"}):e.jsx("button",{onClick:()=>window.open(`/items/publish-batches/${$.id}/result.csv`,"_blank"),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"下载结果"}),$.retryable>0&&!["running","canceling"].includes($.status)&&e.jsxs("button",{disabled:U,onClick:Ye,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(qe,{className:`w-4 h-4 ${U?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes($.status)&&e.jsx("button",{onClick:()=>{D(!1),H(),c()},className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"完成"})]})]})]})}),document.body)]})},yt="https://dashscope.aliyuncs.com/compatible-mode/v1",ar=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],lr=new Set(["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),rr=()=>{const[s,t]=n.useState(null),[l,d]=n.useState(!1),[u,b]=n.useState(""),[k,O]=n.useState(!1),[p,R]=n.useState([]),[f,Q]=n.useState(!1),[se,U]=n.useState(""),[J,S]=n.useState(!1),K=n.useRef(null),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState(!1),[Z,W]=n.useState(!1),[A,Y]=n.useState(!1),[L,te]=n.useState(null),[T,h]=n.useState({new_username:"",current_password:"",new_password:"",confirm_password:""});n.useEffect(()=>{z(),Ft().then(y=>{y.username&&h(P=>({...P,new_username:y.username||""}))}).catch(()=>{})},[]),n.useEffect(()=>{const y=P=>{var M;(M=K.current)!=null&&M.contains(P.target)||S(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[]);const $=async(y,P=!1)=>{const M=y||s,i=(M==null?void 0:M.ai_api_url)||(M==null?void 0:M.ai_base_url)||yt;Q(!0),U("");try{const E=await Rl(i,(M==null?void 0:M.ai_api_key)||"");R(E),S(P&&E.length>0),!(M!=null&&M.ai_model)&&E.length>0&&t(w=>w&&{...w,ai_model:E[0]})}catch(E){R([]),S(!1),U(E.message||"读取模型失败")}finally{Q(!1)}},z=()=>{d(!0),b(""),qt().then(y=>{t(y),$(y)}).catch(y=>{t(null),b(y.message||"加载配置失败")}).finally(()=>d(!1))},X=async()=>{if(s){O(!0);try{const y=Object.fromEntries(Object.entries(s).filter(([P,M])=>!lr.has(P)&&M!==void 0&&M!==null));await Mt(y),alert("系统配置已保存")}catch(y){alert("保存失败:"+y.message)}finally{O(!1)}}},m=async y=>{y.preventDefault(),te(null);const P=T.new_username.trim();if(P.length<3){te({type:"error",text:"用户名至少需要 3 个字符"});return}if(!T.current_password){te({type:"error",text:"请输入当前密码确认身份"});return}if(T.new_password&&T.new_password.length<8){te({type:"error",text:"新密码至少需要 8 个字符"});return}if(T.new_password!==T.confirm_password){te({type:"error",text:"两次输入的新密码不一致"});return}Y(!0);try{const M=await Pa({current_password:T.current_password,new_username:P,new_password:T.new_password||void 0});if(!M.success){te({type:"error",text:M.message||"登录凭据更新失败"});return}te({type:"success",text:M.message||"登录凭据已更新"}),window.setTimeout(()=>window.location.reload(),1400)}catch(M){te({type:"error",text:M.message||"登录凭据更新失败"})}finally{Y(!1)}};if(!s)return e.jsx("div",{className:"p-8 text-center text-gray-400",children:u||(l?"加载配置中...":"暂无配置")});const _=s.ai_model||"",N=p;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(zs,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:z,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(qe,{className:"w-4 h-4"}),"刷新"]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(ma,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:y=>t({...s,log_level:y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:ar.map(y=>e.jsx("option",{value:y.value,children:y.label},y.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:y=>t({...s,log_format:y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:y=>t({...s,renewal_log_retention_days:parseInt(y.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-[#0094f7] text-white",children:e.jsx(St,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||yt,onChange:y=>t({...s,ai_api_url:y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:de?"text":"password",value:s.ai_api_key||"",onChange:y=>t({...s,ai_api_key:y.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:"sk-..."}),e.jsx("button",{type:"button",onClick:()=>le(!de),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:de?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:K,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:_,onFocus:()=>p.length>0&&S(!0),onChange:y=>{t({...s,ai_model:y.target.value}),p.length>0&&S(!0)},onKeyDown:y=>{y.key==="Escape"&&S(!1),y.key==="ArrowDown"&&p.length>0&&S(!0)},className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:()=>p.length>0&&S(y=>!y),disabled:p.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(ua,{className:`w-4 h-4 transition-transform ${J?"rotate-180":""}`})}),J&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:N.length>0?N.map(y=>e.jsxs("button",{type:"button",onClick:()=>{t({...s,ai_model:y}),S(!1)},className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-[#0094f7] flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:y}),y===_&&e.jsx(We,{className:"w-4 h-4 shrink-0 text-[#0094f7]"})]},y)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:()=>$(void 0,!0),disabled:f,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(qe,{className:`w-4 h-4 ${f?"animate-spin":""}`}),"读取模型"]})]}),se?e.jsx("p",{className:"text-xs text-red-500",children:se}):e.jsx("p",{className:"text-xs text-gray-500",children:p.length>0?`已从当前 API 地址读取到 ${p.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(Ms,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:y=>t({...s,"captcha.remote_service_url":y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:ne?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:y=>t({...s,"captcha.remote_secret_key":y.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off"}),e.jsx("button",{type:"button",onClick:()=>q(!ne),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:ne?"隐藏秘钥":"显示秘钥",children:ne?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:y=>t({...s,"captcha.remote_pass_cookies":y.target.checked}),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(at,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:m,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(pa,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:T.new_username,onChange:y=>h({...T,new_username:y.target.value}),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:B?"text":"password",value:T.current_password,onChange:y=>h({...T,current_password:y.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:()=>D(!B),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:B?"隐藏密码":"显示密码",children:B?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:Z?"text":"password",value:T.new_password,onChange:y=>h({...T,new_password:y.target.value}),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:()=>W(!Z),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:Z?"隐藏密码":"显示密码",children:Z?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:Z?"text":"password",value:T.confirm_password,onChange:y=>h({...T,confirm_password:y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),L&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${L.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(Ms,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:L.text})]}),e.jsxs("button",{type:"submit",disabled:A||!T.new_username||!T.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(at,{className:"w-4 h-4"}),A?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:X,disabled:k,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(Je,{className:"w-6 h-6"}),k?"保存中...":"保存所有配置"]})})]})},Es=(s,t)=>s.allowed_resolutions.includes(t),nr=(s,t)=>({runs:s.runs.filter(l=>!t||l.cookie_id===t),pending_tasks:s.pending_tasks.filter(l=>!t||l.cookie_id===t)}),ir=s=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[s]||"自动化异常",or=async s=>{const t=s.loadIssues().then(s.onIssues).catch(s.onIssuesError),l=await s.loadRules();s.onRules(l),await t},cr=(s,t,l,d,u,b)=>s!==t||l!==d?!1:(b(u),!0),He={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:gs},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:ha},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:Lt}},Ds=["order_paid","buyer_reviewed","review_missing_timeout"],dr="亲,商品使用满意的话,麻烦给个评价,谢谢~",ms=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),Ut=s=>{if(!s)return{};try{const t=JSON.parse(s);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}},Ze=(s,t={})=>{const l=Ut(s);return JSON.stringify({after_shipped_hours:Number(l.after_shipped_hours||72),repeat_interval_hours:Number(l.repeat_interval_hours||24),max_attempts:Number(l.max_attempts||1),...t})},us=(s,t)=>{var d;const l=((d=He[s])==null?void 0:d.label)||"自动化规则";return t?`${l} - ${t}`:l},ft=s=>{const t=(s||"").trim();return t?Object.values(He).some(l=>t===l.label||t.startsWith(`${l.label} -`)):!0},ps=(s,t=0)=>{if(s==="review_missing_timeout")return[{action_type:"send_text",message_template:dr,enabled:!0,sort_order:1}];const l={action_type:"send_card",card_id:t,delivery_count:1,enabled:!0,sort_order:1};return s==="order_paid"?[l,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[l]},xr=s=>{var l,d;if(s.trigger_type==="review_missing_timeout")return((d=(l=s.actions)==null?void 0:l.find(u=>u.action_type==="send_text"))==null?void 0:d.message_template)||"发送求评价文案";const t=(s.actions||[]).filter(u=>u.action_type==="send_card");return t.length?t.map(u=>u.card_name||`卡密 ${u.card_id}`).join(" / "):"未配置卡密库存"},jt=(s,t=!1)=>{const l={blue:t?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:t?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:t?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return l[s]||l.blue},mr=s=>s?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",vs=s=>(s==null?void 0:s.nickname)||(s==null?void 0:s.remark)||(s==null?void 0:s.id)||"未知账号",ur=s=>s===!0||s===1||s==="1",pr=({initialDeliveryTarget:s,onDeliveryTargetHandled:t})=>{var ze,Ie,ss;const[l,d]=n.useState("automation"),[u,b]=n.useState([]),[k,O]=n.useState({runs:[],pending_tasks:[]}),[p,R]=n.useState([]),[f,Q]=n.useState({}),[se,U]=n.useState([]),[J,S]=n.useState([]),[K,de]=n.useState([]),[le,ne]=n.useState(!1),[q,B]=n.useState(""),D=n.useRef(0),Z=n.useRef("");Z.current=q;const[W,A]=n.useState(!1),[Y,L]=n.useState(!1),[te,T]=n.useState(!1),[h,$]=n.useState(null),[z,X]=n.useState(null),[m,_]=n.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""});se.find(a=>a.id===q);const N=n.useCallback(async()=>{const[a,g,v,ee]=await Promise.all([Vs(),Ue(),ds(),pt()]);U(a),S(g),de(v),Q(ee),B(xe=>{var je;return xe||((je=a[0])==null?void 0:je.id)||""})},[]),y=n.useCallback(async()=>{await or({loadRules:ks,loadIssues:jl,onRules:b,onIssues:O,onIssuesError:a=>console.warn("加载自动化异常列表失败,不阻断规则展示",a)})},[]),P=n.useCallback(async()=>{const a=q;if(a!==Z.current)return;const g=++D.current;if(R([]),!a)return;const v=await kl(a);cr(g,D.current,a,Z.current,v,R)},[q]),M=n.useCallback(async()=>{Q(await pt())},[]),i=n.useCallback(async()=>{ne(!0);try{l==="automation"?await y():l==="reply"?await P():await M()}finally{ne(!1)}},[l,y,M,P]);n.useEffect(()=>{N().catch(a=>console.error("加载规则参考数据失败",a))},[N]),n.useEffect(()=>{i().catch(a=>console.error("刷新规则页面失败",a))},[i]);const E=n.useMemo(()=>u.filter(a=>!q||a.cookie_id===q),[u,q]),w=n.useMemo(()=>nr(k,q),[k,q]),G=n.useMemo(()=>se.filter(a=>!q||a.id===q),[se,q]),me=n.useMemo(()=>{var g;const a={order_paid:[],buyer_reviewed:[],review_missing_timeout:[]};for(const v of E)(g=a[v.trigger_type])==null||g.push(v);return a},[E]),ie=n.useMemo(()=>{const a=(h==null?void 0:h.cookie_id)||q;return K.filter(g=>g.cookie_id===a)},[h==null?void 0:h.cookie_id,K,q]),H=n.useMemo(()=>{if(!(!(h!=null&&h.cookie_id)||!(h!=null&&h.item_id)))return K.find(a=>a.cookie_id===h.cookie_id&&a.item_id===h.item_id)},[h==null?void 0:h.cookie_id,h==null?void 0:h.item_id,K]),c=ur(H==null?void 0:H.is_multi_spec),C=(h==null?void 0:h.trigger_type)||"order_paid",oe=He[C],be=Ut(h==null?void 0:h.config_json),ye=n.useCallback((a="order_paid",g=q,v="")=>{const ee=K.find(je=>je.cookie_id===g&&je.item_id===v),xe=(ee==null?void 0:ee.item_title)||v;return{name:us(a,xe),trigger_type:a,cookie_id:g,item_id:v,item_title:(ee==null?void 0:ee.item_title)||"",item_keyword:xe,card_group_id:0,priority:100,enabled:!0,config_json:a==="review_missing_timeout"?Ze():"{}",actions:ps(a),variants:a==="review_missing_timeout"?[]:[ms()]}},[K,q]),Se=n.useCallback(a=>{var v,ee;const g=a.trigger_type||"order_paid";$({...a,trigger_type:g,config_json:g==="review_missing_timeout"?Ze(a.config_json):a.config_json||"{}",actions:(v=a.actions)!=null&&v.length?a.actions.map(xe=>({...xe})):ps(g,a.card_group_id),variants:(ee=a.variants)!=null&&ee.length?a.variants.map(xe=>({...xe})):g==="review_missing_timeout"?[]:[ms()]}),A(!0)},[]);n.useEffect(()=>{if(!s)return;let a=!1;return(async()=>{d("automation"),B(s.cookieId),ne(!0);try{const[v,ee,xe]=await Promise.all([ks(),ds(),Ue().catch(o=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",o),[]))]);if(a)return;b(v),de(ee),S(xe);const je=v.find(o=>o.cookie_id===s.cookieId&&o.item_id===s.itemId&&o.trigger_type==="order_paid");if(je)Se(je);else{const o=ee.find(j=>j.cookie_id===s.cookieId&&j.item_id===s.itemId);$({...ye("order_paid",s.cookieId,s.itemId),item_title:(o==null?void 0:o.item_title)||"",item_keyword:(o==null?void 0:o.item_title)||s.itemId,name:us("order_paid",(o==null?void 0:o.item_title)||s.itemId)}),A(!0)}}catch(v){console.error("打开商品自动化规则失败",v),alert("无法加载该商品的自动化规则")}finally{a||(ne(!1),t==null||t())}})(),()=>{a=!0}},[ye,s,t,Se]);const ve=(a="order_paid")=>{if(!q){alert("请先选择账号");return}$(ye(a)),A(!0)},fe=a=>{var ee,xe,je,o,j;if(!h)return;const g=((xe=(ee=h.variants)==null?void 0:ee.find(F=>F.card_id))==null?void 0:xe.card_id)||((o=(je=h.actions)==null?void 0:je.find(F=>F.action_type==="send_card"))==null?void 0:o.card_id)||h.card_group_id||0,v=(H==null?void 0:H.item_title)||h.item_title||h.item_id||"";$({...h,trigger_type:a,name:ft(h.name)?us(a,v):h.name,card_group_id:g,config_json:a==="review_missing_timeout"?Ze(h.config_json):"{}",actions:ps(a,g),variants:a==="review_missing_timeout"?[]:(j=h.variants)!=null&&j.length?h.variants:[{...ms(),card_id:g}]})},De=a=>{if(!h)return;const g=K.find(ee=>ee.cookie_id===(h.cookie_id||q)&&ee.item_id===a),v=(g==null?void 0:g.item_title)||a;$({...h,item_id:a,item_title:(g==null?void 0:g.item_title)||"",item_keyword:v,name:ft(h.name)?us(C,v):h.name})},ue=(ze=h==null?void 0:h.variants)!=null&&ze.length?h.variants:[ms()],Ae=(a,g)=>{var ee;if(!h)return;const v=ue.map((xe,je)=>je===a?{...xe,...g}:xe);$({...h,variants:v,card_group_id:((ee=v[0])==null?void 0:ee.card_id)||0})},Re=()=>{if(!h)return;const a=ue[ue.length-1];$({...h,variants:[...ue,{...ms(),spec_name:c&&(a==null?void 0:a.spec_name)||"",spec_value:c&&(a==null?void 0:a.spec_value)||""}]})},Fe=async()=>{var ee,xe,je,o,j;if(!h)return;const a=h.trigger_type||"order_paid";if(!h.cookie_id){alert("请选择账号");return}const g=(ee=h.variants)!=null&&ee.length?h.variants:[];if(a!=="review_missing_timeout"){if(!g.length||g.some(F=>!F.card_id)){alert(a==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");return}if(c&&g.some(F=>!F.spec_name.trim()||!F.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}}if(a==="review_missing_timeout"&&!(((je=(xe=h.actions)==null?void 0:xe.find(ae=>ae.action_type==="send_text"))==null?void 0:je.message_template)||"").trim()){alert("请填写求评价文案");return}const v=a==="review_missing_timeout"?[]:g.map(F=>({...F,spec_name:c?F.spec_name.trim():"",spec_value:c?F.spec_value.trim():"",delivery_count:Math.max(1,Number(F.delivery_count)||1),enabled:F.enabled!==!1}));try{await mt({...h,trigger_type:a,name:(h.name||"").trim()||us(a,(H==null?void 0:H.item_title)||h.item_id||""),config_json:a==="review_missing_timeout"?Ze(h.config_json):h.config_json||"{}",actions:(o=h.actions)!=null&&o.length?h.actions:ps(a,((j=v[0])==null?void 0:j.card_id)||h.card_group_id||0),variants:v}),A(!1),await Promise.all([y(),N()]),alert("保存成功")}catch(F){console.error("保存自动化规则失败:",F),alert("保存失败:"+F.message)}},Ke=async a=>{if(confirm("确定删除该自动化规则吗?"))try{await fl(a),await y(),alert("删除成功")}catch(g){alert("删除失败:"+g.message)}},Ye=async a=>{try{await mt({...a,enabled:!a.enabled}),await y()}catch(g){alert("操作失败:"+g.message)}},x=async(a,g)=>{if(confirm(g==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":g==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Nl(a,g),await y()}catch(ee){alert("处理失败:"+ee.message)}},V=async(a,g)=>{if(confirm(g==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await vl(a,g),await y()}catch(v){alert("处理失败:"+v.message)}},he=()=>{if(!q){alert("请先选择账号");return}X({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),L(!0)},Ce=async()=>{var g,v,ee;if(!z||!q)return;const a=z.type==="image"?!!((g=z.image_url)!=null&&g.trim()):!!((v=z.reply_content)!=null&&v.trim());if(!((ee=z.keyword)!=null&&ee.trim())||!a){alert("请填写关键词和回复内容");return}try{await Cl({...z,match_type:"fuzzy",enabled:!0},q),L(!1),await P(),alert("保存成功")}catch(xe){alert("保存失败:"+xe.message)}},Be=async a=>{if(!(!q||!confirm("确定删除该回复规则吗?")))try{await Sl(a,q),await P(),alert("删除成功")}catch(g){alert("删除失败:"+g.message)}},Te=async(a=q)=>{if(!a){alert("请先选择账号");return}try{const g=await Fl(a);_({cookie_id:a,enabled:g.enabled,reply_content:g.reply_content,reply_once:g.reply_once,reply_image_url:g.reply_image_url||""})}catch{_({cookie_id:a,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}T(!0)},r=async()=>{if(!m.cookie_id){alert("请先选择账号");return}if(m.enabled&&!m.reply_content.trim()&&!m.reply_image_url.trim()){alert("启用默认回复时,请填写回复内容或图片 URL");return}try{await Tl(m.cookie_id,{enabled:m.enabled,reply_content:m.reply_content,reply_once:m.reply_once,reply_image_url:m.reply_image_url}),T(!1),await M(),alert("保存成功")}catch(a){alert("保存失败:"+a.message)}},I=async a=>{if(confirm("确定删除该账号默认回复吗?"))try{await Ol(a),await M(),alert("删除成功")}catch(g){alert("删除失败:"+g.message)}},ce=async a=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await ql(a),alert("清空成功")}catch(g){alert("清空失败:"+g.message)}},Qe=l==="automation"?"新建自动化":l==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("select",{value:q,onChange:a=>B(a.target.value),className:"ios-input px-4 py-3 rounded-2xl text-sm min-w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),se.map(a=>e.jsx("option",{value:a.id,children:vs(a)},a.id))]}),e.jsxs("button",{onClick:i,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 transition-colors",children:[e.jsx(qe,{className:`w-4 h-4 ${le?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:l==="automation"?()=>ve("order_paid"):l==="reply"?he:()=>void Te(),disabled:!q,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Ge,{className:"w-4 h-4"}),Qe]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:Ts},{id:"reply",label:"关键词回复",icon:_s},{id:"default",label:"账号默认回复",icon:rs}].map(a=>{const g=a.icon;return e.jsxs("button",{onClick:()=>d(a.id),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${l===a.id?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(g,{className:"w-4 h-4"}),a.label]},a.id)})}),l==="automation"&&(w.runs.length>0||w.pending_tasks.length>0)&&e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(os,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[w.runs.map(a=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",a.cookie_id," · 订单 ",a.order_id||"-"," · 已记录发送 ",a.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:ir(a.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:a.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Es(a,"continue")&&e.jsx("button",{onClick:()=>void x(a.id,"continue"),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Es(a,"retry")&&e.jsx("button",{onClick:()=>void x(a.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Es(a,"cancel")&&e.jsx("button",{onClick:()=>void x(a.id,"cancel"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${a.id}`)),w.pending_tasks.map(a=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",a.cookie_id," · 延迟任务重试已达 ",a.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:a.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>void V(a.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:()=>void V(a.id,"dismiss"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${a.id}`))]})]}),l==="automation"&&e.jsxs("div",{className:"grid grid-cols-1 2xl:grid-cols-[360px_1fr] gap-6",children:[e.jsxs("aside",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:Ds.map(a=>{const g=He[a],v=g.icon;return e.jsx("button",{type:"button",onClick:()=>ve(a),className:`w-full text-left rounded-2xl border p-4 transition-colors ${jt(g.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(v,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:g.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:g.description})]})]})},a)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-4",children:"规则概览"}),e.jsx("div",{className:"space-y-3",children:Ds.map(a=>{const g=He[a],v=g.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(v,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:g.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:me[a].length})]},a)})})]})]}),e.jsx("section",{className:"space-y-4",children:E.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(Ts,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"从左侧选择一个模板开始配置。"})]}):E.map(a=>{const g=He[a.trigger_type],v=g.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${jt(g.accent,!0)}`,children:e.jsx(v,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:a.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${mr(a.enabled)}`,children:a.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:g.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:a.item_title||a.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:xr(a)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:()=>Se(a),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:()=>Ye(a),className:`px-4 py-2 rounded-xl text-sm font-bold ${a.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:a.enabled?"禁用":"启用"}),e.jsx("button",{onClick:()=>Ke(a.id),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ve,{className:"w-4 h-4"})})]})]})},a.id)})})]}),l==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(os,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[p.map(a=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",a.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:a.type==="image"&&a.image_url?a.image_url:a.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:()=>{X({...a}),L(!0)},className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(cs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Be(a.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ve,{className:"w-5 h-5"})})]})]},a.id)),p.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),l==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(os,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[G.map(a=>{const g=f[a.id],v=!!(g!=null&&g.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${v?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${v?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(rs,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:vs(a)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${v?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:v?"已启用":"未启用"}),(g==null?void 0:g.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:v?g.reply_content||g.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:()=>void Te(a.id),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(cs,{className:"w-4 h-4"})}),v&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>void ce(a.id),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:()=>void I(a.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ve,{className:"w-5 h-5"})})]})]})]},a.id)}),G.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),W&&h&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:h.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:oe.description})]}),e.jsx("button",{onClick:()=>A(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:Ds.map(a=>{const g=He[a],v=g.icon,ee=C===a;return e.jsx("button",{type:"button",onClick:()=>fe(a),className:`w-full rounded-2xl p-4 text-left border transition-all ${ee?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(v,{className:`w-5 h-5 mt-0.5 ${ee?"text-[#0094f7]":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:g.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${ee?"text-gray-500":"text-gray-400"}`,children:g.description})]})]})},a)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:oe.flow.map((a,g)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:g+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:a})]},a))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-[#F7F8FA]",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx($t,{className:"w-5 h-5 text-[#0094f7]"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:h.name||"",onChange:a=>$({...h,name:a.target.value}),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:h.cookie_id||"",onChange:a=>$({...h,cookie_id:a.target.value,item_id:"",item_title:"",item_keyword:""}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),se.map(a=>e.jsx("option",{value:a.id,children:vs(a)},a.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:h.item_id||"",onChange:a=>De(a.target.value),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),ie.map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]})]}),H&&C!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:H.item_title||H.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${c?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:c?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),C!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ga,{className:"w-5 h-5 text-[#0094f7]"}),e.jsx("h4",{className:"font-black text-gray-900",children:C==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:c?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:Re,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Ge,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:ue.map((a,g)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${c?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:a.spec_name,onChange:v=>Ae(g,{spec_name:v.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:a.spec_value,onChange:v=>Ae(g,{spec_value:v.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:a.card_id||"",onChange:v=>Ae(g,{card_id:Number(v.target.value)}),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),J.filter(v=>v.enabled&&v.type!=="api").map(v=>e.jsx("option",{value:v.id,children:v.name},v.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:a.delivery_count,onChange:v=>Ae(g,{delivery_count:Math.max(1,Number(v.target.value)||1)}),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:a.delay_override===!0,onChange:v=>Ae(g,{delay_override:v.target.checked}),className:"accent-[#0094f7]"}),"覆盖卡密默认延时"]}),a.delay_override&&e.jsx("input",{type:"number",min:"0",max:"86400",value:a.delay_seconds||0,onChange:v=>Ae(g,{delay_seconds:Math.max(0,Number(v.target.value)||0)}),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:a.delay_override?`本动作延时 ${a.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:ue.length===1,onClick:()=>$({...h,variants:ue.filter((v,ee)=>ee!==g)}),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(Ve,{className:"w-4 h-4"})})]},a.id||g))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Lt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.after_shipped_hours||72),onChange:a=>$({...h,config_json:Ze(h.config_json,{after_shipped_hours:Math.max(1,Number(a.target.value)||72)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.repeat_interval_hours||24),onChange:a=>$({...h,config_json:Ze(h.config_json,{repeat_interval_hours:Math.max(1,Number(a.target.value)||24)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(be.max_attempts||1),onChange:a=>$({...h,config_json:Ze(h.config_json,{max_attempts:Math.max(1,Number(a.target.value)||1)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((ss=(Ie=h.actions)==null?void 0:Ie.find(a=>a.action_type==="send_text"))==null?void 0:ss.message_template)||"",onChange:a=>{var g;return $({...h,actions:((g=h.actions)!=null&&g.length?h.actions:ps("review_missing_timeout")).map(v=>v.action_type==="send_text"?{...v,message_template:a.target.value}:v)})},className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:h.priority||100,onChange:a=>$({...h,priority:Number(a.target.value)||100}),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:h.enabled!==!1,onChange:a=>$({...h,enabled:a.target.checked}),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:()=>A(!1),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:Fe,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Y&&z&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:z.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:()=>L(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:z.item_id||"",onChange:a=>X({...z,item_id:a.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),K.filter(a=>!q||a.cookie_id===q).map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:z.type||"text",onChange:a=>{const g=a.target.value;X({...z,type:g,reply_content:g==="text"?z.reply_content:"",image_url:g==="image"?z.image_url:""})},className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:z.keyword||"",onChange:a=>X({...z,keyword:a.target.value}),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),z.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:z.image_url||"",onChange:a=>X({...z,image_url:a.target.value}),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:z.reply_content||"",onChange:a=>X({...z,reply_content:a.target.value}),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:()=>L(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Ce,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Us,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),te&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:()=>T(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:m.cookie_id,onChange:a=>_({...m,cookie_id:a.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),se.map(a=>e.jsx("option",{value:a.id,children:vs(a)},a.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:()=>_({...m,enabled:!m.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${m.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${m.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:m.reply_content,onChange:a=>_({...m,reply_content:a.target.value}),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:m.reply_image_url,onChange:a=>_({...m,reply_image_url:a.target.value}),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:m.reply_once,onChange:a=>_({...m,reply_once:a.target.checked}),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:()=>T(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:r,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})},hr=s=>{const t=String(s.smtp_from||"").trim(),l=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t);return{...s,smtp_from_name:s.smtp_from_name||(l?"":t),smtp_from_address:s.smtp_from_address||(l?t:s.smtp_user||""),smtp_use_tls:Nt(s.smtp_use_tls,!0),smtp_use_ssl:Nt(s.smtp_use_ssl,!1)}},Nt=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ls={bark:{label:"Bark",icon:is,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容","URL 路径里 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:_s,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:_s,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:_s,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:ba,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:Us,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:Pt,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0},{key:"smtp_server",label:"覆盖 SMTP 服务器",placeholder:"smtp.qq.com",help:"留空时使用上方系统级 SMTP 配置"},{key:"smtp_port",label:"覆盖 SMTP 端口",placeholder:"587",type:"number",help:"留空时使用系统级 SMTP 端口"},{key:"smtp_user",label:"覆盖发件邮箱",placeholder:"you@qq.com",help:"留空时使用系统级发件邮箱"},{key:"smtp_password",label:"覆盖密码 / 授权码",type:"password",help:"留空时使用系统级授权码"}],guide:{steps:["先在页面上方保存系统级 SMTP 服务器、端口、发件邮箱和授权码","邮件渠道只需要填写收件邮箱","如果某个渠道要使用不同发件邮箱,再填写下面的覆盖 SMTP 字段"],note:"收件邮箱会写入 to_email;SMTP 字段留空时后端会复用系统级 SMTP 配置。"}}},Wt=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],gr=s=>!s||s.length===0?"全部事件":s.map(l=>{var d;return((d=Wt.find(u=>u.value===l))==null?void 0:d.label)||l}).join("、"),br=({isAdmin:s=!1})=>{const[t,l]=n.useState([]),[d,u]=n.useState(!0),[b,k]=n.useState(!1),[O,p]=n.useState(null),[R,f]=n.useState(!1),[Q,se]=n.useState(""),[U,J]=n.useState(null),[S,K]=n.useState({}),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Z=async()=>{u(!0);try{const m=await zt();l(m.data||[])}catch(m){console.error("加载通知渠道失败",m)}finally{u(!1)}},W=async()=>{try{const m=await qt();K(hr(m||{}))}catch(m){console.error("加载 SMTP 配置失败",m)}},A=async()=>{le(!0);try{await Mt({smtp_server:S.smtp_server||"",smtp_port:S.smtp_port||587,smtp_user:S.smtp_user||"",smtp_password:S.smtp_password||"",smtp_from_name:S.smtp_from_name||"",smtp_from_address:S.smtp_from_address||S.smtp_user||"",smtp_use_tls:S.smtp_use_tls!==!1,smtp_use_ssl:S.smtp_use_ssl===!0}),Y("success","SMTP 配置已保存")}catch(m){Y("error",(m==null?void 0:m.message)||"保存失败")}finally{le(!1)}};n.useEffect(()=>{Z(),s?W():K({})},[s]);const Y=(m,_)=>{J({type:m,text:_}),window.setTimeout(()=>J(null),3e3)},L=()=>{p(null),D({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),k(!0)},te=m=>{p(m),D({name:m.name,type:m.type,enabled:m.enabled,config:{...m.config||{}},event_types:m.event_types||[]}),k(!0)},T=async()=>{const m=ls[B.type];for(const _ of m.fields)if(_.required&&!String(B.config[_.key]||"").trim()){Y("error",`请填写 ${_.label}`);return}if(!B.name.trim()){Y("error","请填写渠道名称");return}f(!0);try{const _={name:B.name.trim(),type:B.type,config:B.config,event_types:B.event_types,enabled:B.enabled};O?await ut(O.id,_):await Ll(_),k(!1),await Z(),Y("success",O?"已更新":"已创建")}catch(_){console.error("保存失败",_),Y("error",(_==null?void 0:_.message)||"保存失败")}finally{f(!1)}},h=async m=>{if(confirm(`确认删除渠道「${m.name}」吗?已绑定该渠道的账号会自动解绑。`))try{await Pl(m.id),await Z(),Y("success","已删除")}catch(_){Y("error",(_==null?void 0:_.message)||"删除失败")}},$=async m=>{try{await ut(m.id,{enabled:!m.enabled}),l(_=>_.map(N=>N.id===m.id?{...N,enabled:!N.enabled}:N))}catch(_){Y("error",(_==null?void 0:_.message)||"切换失败")}},z=async m=>{se(m.id);try{await Dl(m.id),Y("success","测试通知已发送,请检查对应渠道")}catch(_){Y("error",(_==null?void 0:_.message)||"发送失败")}finally{se("")}},X=ls[B.type];return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:Z,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(qe,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:L,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(is,{className:"w-5 h-5 text-[#0094f7] mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),d?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Le,{className:"w-8 h-8 text-[#0094f7] animate-spin"})}):t.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(is,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:t.map(m=>{const _=ls[m.type]||ls.webhook,N=_.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(N,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:m.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:_.label}),!m.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:_.fields.map(y=>{var P;return(P=m.config)==null?void 0:P[y.key]}).filter(Boolean).map((y,P)=>e.jsx("span",{className:"mr-3",children:String(y).length>40?String(y).slice(0,40)+"…":String(y)},P))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",gr(m.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:()=>$(m),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${m.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:m.enabled?"启用中":"已停用"}),e.jsxs("button",{onClick:()=>z(m),disabled:Q===m.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-[#0094f7] hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[Q===m.id?e.jsx(Le,{className:"w-3 h-3 animate-spin"}):e.jsx(Us,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{onClick:()=>te(m),className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(Rt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>h(m),className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(Ve,{className:"w-4 h-4"})})]})]},m.id)})}),s&&e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(Pt,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 服务器"}),e.jsx("input",{type:"text",value:S.smtp_server||"",onChange:m=>K({...S,smtp_server:m.target.value}),placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:S.smtp_port||587,onChange:m=>K({...S,smtp_port:parseInt(m.target.value)||587}),placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{type:"email",value:S.smtp_user||"",onChange:m=>K({...S,smtp_user:m.target.value}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:ne?"text":"password",value:S.smtp_password||"",onChange:m=>K({...S,smtp_password:m.target.value}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>q(!ne),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:ne?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{type:"text",value:S.smtp_from_name||"",onChange:m=>K({...S,smtp_from_name:m.target.value}),placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{type:"email",value:S.smtp_from_address||S.smtp_user||"",onChange:m=>K({...S,smtp_from_address:m.target.value}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:S.smtp_use_tls!==!1,onChange:m=>K({...S,smtp_use_tls:m.target.checked,smtp_use_ssl:m.target.checked?!1:S.smtp_use_ssl})}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:S.smtp_use_ssl===!0,onChange:m=>K({...S,smtp_use_ssl:m.target.checked,smtp_use_tls:m.target.checked?!1:S.smtp_use_tls})}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:A,disabled:de,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[de?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Je,{className:"w-4 h-4"}),de?"保存中...":"保存 SMTP 配置"]})]}),b&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:O?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:()=>k(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:B.name,onChange:m=>D({...B,name:m.target.value}),placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys(ls).map(m=>{const _=ls[m],N=_.icon,y=B.type===m;return e.jsxs("button",{type:"button",onClick:()=>D({...B,type:m,config:{}}),className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${y?"border-[#0094f7] bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(N,{className:`w-5 h-5 ${y?"text-[#0094f7]":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${y?"text-[#0094f7]":"text-gray-600"}`,children:_.label})]},m)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",X.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:X.guide.steps.map((m,_)=>e.jsx("li",{children:m},_))}),X.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:X.guide.urlFormat})]}),X.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",X.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:X.fields.map(m=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[m.label,m.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{type:m.type==="password"?"password":m.type==="number"?"number":"text",value:String(B.config[m.key]||""),onChange:_=>D({...B,config:{...B.config,[m.key]:_.target.value}}),placeholder:m.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),m.help&&e.jsx("p",{className:"text-xs text-gray-500",children:m.help})]},m.key))}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:Wt.map(m=>{const _=B.event_types.includes(m.value);return e.jsxs("button",{type:"button",onClick:()=>{const N=_?B.event_types.filter(y=>y!==m.value):[...B.event_types,m.value];D({...B,event_types:N})},className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${_?"border-[#0094f7] bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${_?"bg-[#0094f7] border-[#0094f7]":"border-gray-300"}`,children:_&&e.jsx(We,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${_?"text-[#0094f7]":"text-gray-800"}`,children:m.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:m.description})]},m.value)})})]}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:()=>D({...B,enabled:!B.enabled}),className:`relative w-11 h-6 rounded-full transition-colors ${B.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${B.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>k(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:T,disabled:R,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[R?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(We,{className:"w-4 h-4"}),R?"保存中...":"保存"]})]})]})}),document.body),U&&e.jsxs("div",{className:"fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in",style:{background:U.type==="success"?"#10b981":"#ef4444",color:"white"},children:[U.type==="success"?e.jsx(We,{className:"w-4 h-4"}):e.jsx(Ne,{className:"w-4 h-4"}),U.text]})]})},Vt={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},vt=Object.fromEntries(Object.entries(Vt).map(([s,t])=>[t,s])),_t=()=>Vt[window.location.pathname]||"dashboard",yr=/Win/i.test(navigator.platform||navigator.userAgent),fr=()=>{const[s,t]=n.useState(!1),[l,d]=n.useState(!1),[u,b]=n.useState(_t),[k,O]=n.useState(!0),[p,R]=n.useState(!1),[f,Q]=n.useState(""),[se,U]=n.useState(""),[J,S]=n.useState(!1),[K,de]=n.useState(""),[le,ne]=n.useState(),q=W=>{const A=W==="settings"&&!l?"dashboard":W,Y=vt[A];Y&&Y!==window.location.pathname&&window.history.pushState({},"",Y),b(A)};n.useEffect(()=>{const W=()=>b(_t());return window.addEventListener("popstate",W),()=>window.removeEventListener("popstate",W)},[]),n.useEffect(()=>{Ft().then(A=>{if((A==null?void 0:A.initialized)===!1){R(!0),t(!1),d(!1);return}R(!1),A!=null&&A.authenticated?(t(!0),d(A.is_admin===!0)):d(!1)}).catch(()=>{t(!1),d(!1)}).finally(()=>O(!1));const W=()=>{t(!1),d(!1)};return window.addEventListener("auth:logout",W),()=>window.removeEventListener("auth:logout",W)},[]),n.useEffect(()=>{!k&&s&&!l&&u==="settings"&&(window.history.replaceState({},"",vt.dashboard),b("dashboard"))},[k,s,l,u]);const B=async W=>{W.preventDefault(),S(!0),de("");try{const A=await $a({username:f,password:se});A.success?(t(!0),d(A.is_admin===!0)):de(A.message||"登录失败")}catch(A){const Y=A instanceof Error?A.message:String(A);de(Y||"登录失败")}finally{S(!1)}},D=async()=>{try{await La()}catch(W){console.error("退出登录失败",W)}finally{t(!1),d(!1)}};if(k)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f5f5f7]",children:e.jsx(Le,{className:"w-8 h-8 text-[#0094f7] animate-spin"})});if(p)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 p-4",style:{filter:"drop-shadow(0 8px 20px rgba(0,148,247,0.3))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"系统尚未初始化"}),e.jsx("p",{className:"text-gray-600 font-medium",children:"为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 rounded-2xl bg-gray-50 border border-gray-100",children:[e.jsx("div",{className:"text-sm font-bold text-gray-900 mb-2",children:"请在服务器上执行:"}),e.jsx("pre",{className:"text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto",children:yr?'.\\xianyu-server.exe -init-admin -db data\\xianyu_data.db -admin-password "请设置密码"':"./xianyu-server -init-admin -db data/xianyu_data.db -admin-password '请设置密码'"}),e.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"完成后刷新页面即可进入登录。"})]}),e.jsxs("button",{type:"button",onClick:()=>window.location.reload(),className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group",children:["我已初始化,刷新 ",e.jsx(qs,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!s)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-lg border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 cursor-pointer group p-4",style:{filter:"drop-shadow(0 8px 20px rgba(0,148,247,0.3))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full group-hover:scale-110 transition-transform"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),e.jsxs("form",{onSubmit:B,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(Os,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"text",placeholder:"管理员账号",value:f,onChange:W=>Q(W.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ya,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"密码",value:se,onChange:W=>U(W.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),K&&e.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[e.jsx(Ms,{className:"w-4 h-4"})," ",K]}),e.jsx("button",{type:"submit",disabled:J,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:J?e.jsx(Le,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["立即登录 ",e.jsx(qs,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:e.jsx("div",{className:"mt-6 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const Z=()=>{switch(u){case"dashboard":return e.jsx(Ps,{});case"accounts":return e.jsx(Kl,{});case"orders":return e.jsx(Zl,{});case"cards":return e.jsx(Hl,{});case"items":return e.jsx(tr,{onConfigureDelivery:W=>{ne({cookieId:W.cookie_id,itemId:W.item_id,requestId:Date.now()}),q("rules")}});case"rules":return e.jsx(pr,{initialDeliveryTarget:le,onDeliveryTargetHandled:()=>ne(void 0)});case"notifications":return e.jsx(br,{isAdmin:l});case"settings":return l?e.jsx(rr,{}):e.jsx(Ps,{});default:return e.jsx(Ps,{})}};return e.jsxs("div",{className:"flex min-h-screen bg-[#F4F5F7] text-[#111]",children:[e.jsx(ka,{activeTab:u,isAdmin:l,onNavigate:q,onLogout:D}),e.jsxs("main",{className:"flex-1 ml-64 p-8 md:p-12 overflow-y-auto h-screen relative scroll-smooth",children:[e.jsx("div",{className:"fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"}),e.jsx("div",{className:"max-w-[1400px] mx-auto pb-10",children:Z()})]})]})},Gt=document.getElementById("root");if(!Gt)throw new Error("Could not find root element to mount to");const jr=Qt.createRoot(Gt);jr.render(e.jsx(Kt.StrictMode,{children:e.jsx(fr,{})})); diff --git a/internal/webui/static/assets/index-D0gOrWMZ.css b/internal/webui/static/assets/index-D0gOrWMZ.css deleted file mode 100644 index 0a75a3a..0000000 --- a/internal/webui/static/assets/index-D0gOrWMZ.css +++ /dev/null @@ -1 +0,0 @@ -*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{right:-.25rem}.-right-6{right:-1.5rem}.-top-6{top:-1.5rem}.bottom-10{bottom:2.5rem}.bottom-8{bottom:2rem}.bottom-\[-10\%\]{bottom:-10%}.left-0{left:0}.left-0\.5{left:.125rem}.left-1{left:.25rem}.left-1\.5{left:.375rem}.left-1\/2{left:50%}.left-4{left:1rem}.left-5{left:1.25rem}.left-\[-10\%\]{left:-10%}.right-0{right:0}.right-10{right:2.5rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-\[-10\%\]{right:-10%}.top-0{top:0}.top-0\.5{top:.125rem}.top-1{top:.25rem}.top-1\.5{top:.375rem}.top-1\/2{top:50%}.top-2{top:.5rem}.top-4{top:1rem}.top-\[-10\%\]{top:-10%}.top-\[calc\(100\%\+6px\)\]{top:calc(100% + 6px)}.-z-10{z-index:-10}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-\[10000\]{z-index:10000}.col-span-2{grid-column:span 2 / span 2}.col-span-full{grid-column:1 / -1}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-10{margin-bottom:2.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-2\.5{margin-bottom:.625rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-64{margin-left:16rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.mt-auto{margin-top:auto}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.contents{display:contents}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-24{height:6rem}.h-28{height:7rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-80{height:20rem}.h-9{height:2.25rem}.h-\[280px\]{height:280px}.h-\[300px\]{height:300px}.h-\[350px\]{height:350px}.h-\[48px\]{height:48px}.h-\[60\%\]{height:60%}.h-\[800px\]{height:800px}.h-auto{height:auto}.h-full{height:100%}.h-screen{height:100vh}.max-h-44{max-height:11rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-\[380px\]{max-height:380px}.max-h-\[400px\]{max-height:400px}.max-h-\[420px\]{max-height:420px}.max-h-\[min\(64vh\,28rem\)\]{max-height:min(64vh,28rem)}.min-h-0{min-height:0px}.min-h-36{min-height:9rem}.min-h-64{min-height:16rem}.min-h-\[120px\]{min-height:120px}.min-h-\[150px\]{min-height:150px}.min-h-\[400px\]{min-height:400px}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-28{width:7rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[10\%\]{width:10%}.w-\[12\%\]{width:12%}.w-\[18\%\]{width:18%}.w-\[22\%\]{width:22%}.w-\[60\%\]{width:60%}.w-\[800px\]{width:800px}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.min-w-0{min-width:0px}.min-w-64{min-width:16rem}.min-w-\[210px\]{min-width:210px}.min-w-\[260px\]{min-width:260px}.max-w-64{max-width:16rem}.max-w-6xl{max-width:72rem}.max-w-72{max-width:18rem}.max-w-\[12rem\]{max-width:12rem}.max-w-\[1400px\]{max-width:1400px}.max-w-\[15rem\]{max-width:15rem}.max-w-\[200px\]{max-width:200px}.max-w-\[240px\]{max-width:240px}.max-w-\[260px\]{max-width:260px}.max-w-\[280px\]{max-width:280px}.max-w-\[340px\]{max-width:340px}.max-w-\[80px\]{max-width:80px}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.flex-1{flex:1 1 0%}.flex-shrink-0,.shrink-0{flex-shrink:0}.table-fixed{table-layout:fixed}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-5{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-6{--tw-translate-x: 1.5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-7{--tw-translate-x: 1.75rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\[1\.02\]{--tw-scale-x: 1.02;--tw-scale-y: 1.02;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.cursor-pointer{cursor:pointer}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-5{gap:1.25rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-100>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(243 244 246 / var(--tw-divide-opacity, 1))}.divide-gray-50>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(249 250 251 / var(--tw-divide-opacity, 1))}.self-end{align-self:flex-end}.self-center{align-self:center}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overscroll-contain{overscroll-behavior:contain}.scroll-smooth{scroll-behavior:smooth}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:6px}.rounded-2xl,.rounded-3xl{border-radius:10px}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:7px}.rounded-md{border-radius:6px}.rounded-xl{border-radius:8px}.border{border-width:1px}.border-0{border-width:0px}.border-2{border-width:2px}.border-4{border-width:4px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[\#0094f7\]{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.border-amber-100{--tw-border-opacity: 1;border-color:rgb(254 243 199 / var(--tw-border-opacity, 1))}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-emerald-100{--tw-border-opacity: 1;border-color:rgb(209 250 229 / var(--tw-border-opacity, 1))}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-50{--tw-border-opacity: 1;border-color:rgb(249 250 251 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-purple-100{--tw-border-opacity: 1;border-color:rgb(243 232 255 / var(--tw-border-opacity, 1))}.border-red-100{--tw-border-opacity: 1;border-color:rgb(254 226 226 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\/10{border-color:#ffffff1a}.bg-\[\#0094f7\]{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F4F5F7\]{--tw-bg-opacity: 1;background-color:rgb(244 245 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F7F8FA\]{--tw-bg-opacity: 1;background-color:rgb(247 248 250 / var(--tw-bg-opacity, 1))}.bg-\[\#FAFAFA\]{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.bg-\[\#f5f5f7\]{--tw-bg-opacity: 1;background-color:rgb(245 245 247 / var(--tw-bg-opacity, 1))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-100\/70{background-color:#fef3c7b3}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-50\/60{background-color:#fffbeb99}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-100\/70{background-color:#dbeafeb3}.bg-blue-200\/30{background-color:#bfdbfe4d}.bg-blue-200\/40{background-color:#bfdbfe66}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-50\/50{background-color:#eff6ff80}.bg-blue-50\/60{background-color:#eff6ff99}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-50\/60{background-color:#ecfdf599}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-100\/50{background-color:#f3f4f680}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-200\/50{background-color:#e5e7eb80}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-pink-50{--tw-bg-opacity: 1;background-color:rgb(253 242 248 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-50{--tw-bg-opacity: 1;background-color:rgb(250 245 255 / var(--tw-bg-opacity, 1))}.bg-purple-50\/50{background-color:#faf5ff80}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-slate-900{--tw-bg-opacity: 1;background-color:rgb(15 23 42 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/5{background-color:#ffffff0d}.bg-white\/80{background-color:#fffc}.bg-white\/90{background-color:#ffffffe6}.bg-white\/95{background-color:#fffffff2}.bg-opacity-10{--tw-bg-opacity: .1}.bg-gradient-to-bl{background-image:linear-gradient(to bottom left,var(--tw-gradient-stops))}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-0{padding:0}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-16{padding:4rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-20{padding:5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-20{padding-top:5rem;padding-bottom:5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-10{padding-bottom:2.5rem}.pb-24{padding-bottom:6rem}.pl-10{padding-left:2.5rem}.pl-11{padding-left:2.75rem}.pl-14{padding-left:3.5rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-5{padding-left:1.25rem}.pl-6{padding-left:1.5rem}.pr-10{padding-right:2.5rem}.pr-11{padding-right:2.75rem}.pr-12{padding-right:3rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pt-1{padding-top:.25rem}.pt-4{padding-top:1rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-black{font-weight:900}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-4{line-height:1rem}.leading-5{line-height:1.25rem}.leading-6{line-height:1.5rem}.leading-relaxed{line-height:1.625}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.text-\[\#111\]{--tw-text-opacity: 1;color:rgb(17 17 17 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-800\/80{color:#92400ecc}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity, 1))}.text-amber-900\/90{color:#78350fe6}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-blue-900{--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}.text-blue-950{--tw-text-opacity: 1;color:rgb(23 37 84 / var(--tw-text-opacity, 1))}.text-emerald-600{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-pink-600{--tw-text-opacity: 1;color:rgb(219 39 119 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity, 1))}.text-slate-400{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.text-slate-950{--tw-text-opacity: 1;color:rgb(2 6 23 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-white\/30{color:#ffffff4d}.accent-\[\#0094f7\]{accent-color:#0094f7}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-30{opacity:.3}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_20px_60px_-15px_rgba\(0\,0\,0\,0\.05\)\]{--tw-shadow: 0 20px 60px -15px rgba(0,0,0,.05);--tw-shadow-colored: 0 20px 60px -15px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[4px_0_24px_rgba\(0\,0\,0\,0\.02\)\]{--tw-shadow: 4px 0 24px rgba(0,0,0,.02);--tw-shadow-colored: 4px 0 24px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-blue-100{--tw-shadow-color: #dbeafe;--tw-shadow: var(--tw-shadow-colored)}.shadow-blue-200{--tw-shadow-color: #bfdbfe;--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-100{--tw-shadow-color: #d1fae5;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200{--tw-shadow-color: #e5e7eb;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200\/70{--tw-shadow-color: rgb(229 231 235 / .7);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-4{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-white{--tw-ring-opacity: 1;--tw-ring-color: rgb(255 255 255 / var(--tw-ring-opacity, 1))}.blur-2xl{--tw-blur: blur(40px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-\[120px\]{--tw-blur: blur(120px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow{--tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / .1)) drop-shadow(0 1px 1px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-3xl{--tw-backdrop-blur: blur(64px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.squircle{-webkit-mask-image:url(/static/assets/squircle-rb6SKa34.svg);mask-image:url(/static/assets/squircle-rb6SKa34.svg);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;border-radius:0}*{box-sizing:border-box;margin:0;padding:0}html,body,#root{height:100%;width:100%}body{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;background-color:#f4f5f7;color:#fff;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.ios-card{background:#fff;border-radius:8px;border:1px solid rgba(0,0,0,.02);box-shadow:0 8px 24px #0000000a;transition:transform .2s ease,box-shadow .2s ease}.ios-card:hover{box-shadow:0 12px 32px #0000000f}.ios-input{background:#f7f8fa;border:1px solid transparent;transition:all .3s cubic-bezier(.25,.8,.25,1);color:#111;font-weight:500}.ios-input:focus{background:#fff;border-color:#0094f7;box-shadow:0 0 0 4px #0094f74d;outline:none}.ios-input::-moz-placeholder{color:#9ca3af;font-weight:400}.ios-input::placeholder{color:#9ca3af;font-weight:400}.ios-btn-primary{background:#0094f7;color:#fff;font-weight:700;border:none;transition:all .2s cubic-bezier(.25,.8,.25,1);cursor:pointer}.ios-btn-primary:hover:not(:disabled){background:#0071e3;transform:translateY(-1px);box-shadow:0 8px 20px #0094f74d}.ios-btn-primary:active:not(:disabled){transform:translateY(1px);box-shadow:0 2px 8px #0094f733}.ios-btn-primary:disabled{background:#f0f0f0;color:#aaa;box-shadow:none;transform:none;cursor:not-allowed}.ios-btn-secondary{background:#f7f8fa;color:#fff;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-secondary:hover{background:#e5e7eb;border-color:#d1d5db}.ios-btn-danger{background:#fee2e2;color:#dc2626;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-danger:hover{background:#fecaca;border-color:#fca5a5}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#0000001a;border-radius:10px}::-webkit-scrollbar-thumb:hover{background:#0003}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .5s cubic-bezier(.16,1,.3,1) forwards}@keyframes slideUp{0%{opacity:0;transform:translateY(30px) scale(.95)}to{opacity:1;transform:translateY(0) scale(1)}}.animate-slide-up{animation:slideUp .3s cubic-bezier(.16,1,.3,1) forwards}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}::-moz-selection{background:#0094f7;color:#fff}::selection{background:#0094f7;color:#fff}.text-brand{color:#0094f7}.bg-brand{background-color:#0094f7}.border-brand{border-color:#0094f7}.status-badge{display:inline-flex;align-items:center;padding:4px 12px;border-radius:9999px;font-size:12px;font-weight:600}.status-badge-success{background-color:#d1fae5;color:#065f46}.status-badge-warning{background-color:#fef3c7;color:#92400e}.status-badge-error{background-color:#fee2e2;color:#991b1b}.status-badge-info{background-color:#dbeafe;color:#1e40af}.loading-skeleton{background:linear-gradient(90deg,#f3f4f6,#e5e7eb,#f3f4f6);background-size:200% 100%;animation:loading 1.5s ease-in-out infinite}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;align-items:center;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto;display:flex;flex-direction:column;background-color:#fff;border-radius:10px;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}.modal-header{flex-shrink:0;padding:2rem 2rem 1.5rem;border-bottom:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-body{flex:1 1 auto;overflow-y:auto;overflow-x:hidden;padding:2rem}.modal-footer{flex-shrink:0;padding:1.5rem 2rem 2rem;border-top:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-container-lg{max-width:64rem}.modal-overlay-centered{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-overlay-centered .modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto 0;display:flex;flex-direction:column;background-color:#fff;border-radius:10px;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}@media(max-width:768px){.ios-card{border-radius:6px}.ios-input{font-size:16px}.modal-container{max-width:calc(100% - 2rem);max-height:90vh;border-radius:8px}.modal-header,.modal-body,.modal-footer{padding-left:1.5rem;padding-right:1.5rem}}.hover\:translate-y-\[-4px\]:hover{--tw-translate-y: -4px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-\[\#0094f7\]:hover{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.hover\:border-amber-300:hover{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.hover\:border-blue-300:hover{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.hover\:border-emerald-300:hover{--tw-border-opacity: 1;border-color:rgb(110 231 183 / var(--tw-border-opacity, 1))}.hover\:border-gray-300:hover{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.hover\:border-gray-400:hover{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.hover\:bg-\[\#0071e3\]:hover{--tw-bg-opacity: 1;background-color:rgb(0 113 227 / var(--tw-bg-opacity, 1))}.hover\:bg-\[\#0094f7\]:hover{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.hover\:bg-\[\#FFFDE7\]\/50:hover{background-color:#fffde780}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-black:hover{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-100:hover{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50:hover{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50\/50:hover{background-color:#ecfdf580}.hover\:bg-emerald-700:hover{--tw-bg-opacity: 1;background-color:rgb(4 120 87 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-100:hover{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.hover\:bg-green-50:hover{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.hover\:bg-purple-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/10:hover{background-color:#ffffff1a}.hover\:text-\[\#0094f7\]:hover{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.hover\:text-black:hover{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-green-600:hover{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-400:focus{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-0:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-\[\#0094f7\]:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(0 148 247 / var(--tw-ring-opacity, 1))}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-25:disabled{opacity:.25}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.disabled\:opacity-70:disabled{opacity:.7}.group:focus-within .group-focus-within\:text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.group:focus-within .group-focus-within\:text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-125{--tw-scale-x: 1.25;--tw-scale-y: 1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.group:hover .group-hover\:text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:opacity-100{opacity:1}@media(min-width:640px){.sm\:w-72{width:18rem}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.sm\:grid-cols-\[1fr_180px\]{grid-template-columns:1fr 180px}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-8{gap:2rem}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:col-span-3{grid-column:span 3 / span 3}.md\:col-span-full{grid-column:1 / -1}.md\:w-auto{width:auto}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.md\:grid-cols-\[1\.4fr_110px_40px\]{grid-template-columns:1.4fr 110px 40px}.md\:grid-cols-\[180px_1fr\]{grid-template-columns:180px 1fr}.md\:grid-cols-\[1fr_1fr_1\.4fr_110px_40px\]{grid-template-columns:1fr 1fr 1.4fr 110px 40px}.md\:flex-row{flex-direction:row}.md\:items-end{align-items:flex-end}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:border-l{border-left-width:1px}.md\:border-t-0{border-top-width:0px}.md\:p-12{padding:3rem}.md\:pl-6{padding-left:1.5rem}.md\:pt-0{padding-top:0}}@media(min-width:1024px){.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-\[320px_1fr\]{grid-template-columns:320px 1fr}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}.lg\:self-auto{align-self:auto}}@media(min-width:1280px){.xl\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.xl\:flex-row{flex-direction:row}.xl\:items-end{align-items:flex-end}.xl\:justify-between{justify-content:space-between}}@media(min-width:1536px){.\32xl\:grid-cols-\[360px_1fr\]{grid-template-columns:360px 1fr}} diff --git a/internal/webui/static/assets/index-DWScSBc3.js b/internal/webui/static/assets/index-DWScSBc3.js new file mode 100644 index 0000000..e7ed37e --- /dev/null +++ b/internal/webui/static/assets/index-DWScSBc3.js @@ -0,0 +1,19 @@ +import{j as e,r as n,b as Se,c as ra,d as na}from"./react-vendor-DZnRGM0-.js";import{L as ia,U as Pt,S as Tt,C as zs,B as Et,Z as Us,a as xs,b as Ys,c as Ft,d as oa,e as ms,A as rt,D as ca,f as nt,P as Dt,g as Ns,E as Mt,T as da,h as xa,i as Te,Q as Ps,j as ns,k as Ge,l as ds,m as it,R as qe,n as Ot,o as ma,p as Je,X as we,K as ua,q as rs,r as es,s as Ke,t as Qe,u as ot,v as qt,w as us,x as pa,y as ha,z as js,F as ga,G as ba,H as ct,I as dt,J as fa,M as ya,N as ja,O as Na,V as Ts,W as _s,Y as Bt,_ as va,$ as _a,a0 as Ws,a1 as wa,a2 as ka,a3 as Vs,a4 as xt,a5 as Ca,a6 as Ls,a7 as zt,a8 as Sa,a9 as La,aa as Zs,ab as Ut,ac as Aa,ad as Ia}from"./icons-vendor-RenKjhri.js";import{R as ws,B as $a,X as mt,Y as ut,T as Es,a as Ra,C as Fs,A as Pa,b as Ta,c as Ea,P as pt,d as ht,L as Fa}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const h of document.querySelectorAll('link[rel="modulepreload"]'))c(h);new MutationObserver(h=>{for(const f of h)if(f.type==="childList")for(const L of f.addedNodes)L.tagName==="LINK"&&L.rel==="modulepreload"&&c(L)}).observe(document,{childList:!0,subtree:!0});function l(h){const f={};return h.integrity&&(f.integrity=h.integrity),h.referrerPolicy&&(f.referrerPolicy=h.referrerPolicy),h.crossOrigin==="use-credentials"?f.credentials="include":h.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function c(h){if(h.ep)return;h.ep=!0;const f=l(h);fetch(h.href,f)}})();const Da=({className:s="w-full h-full text-white"})=>e.jsx("svg",{className:s,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),Gs=({sizeClass:s="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${s} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),e.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:e.jsx(Da,{className:t})})]})]}),Ma=({activeTab:s,isAdmin:t=!1,onNavigate:l,onLogout:c})=>{const h=[{id:"dashboard",icon:ia,label:"仪表盘"},{id:"accounts",icon:Pt,label:"账号管理"},{id:"orders",icon:Tt,label:"订单管理"},{id:"cards",icon:zs,label:"卡密库存"},{id:"items",icon:Et,label:"商品列表"},{id:"rules",icon:Us,label:"自动化规则"},{id:"notifications",icon:xs,label:"通知设置"},...t?[{id:"settings",icon:Ys,label:"系统与AI"}]:[]];return e.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[e.jsx("div",{className:"shrink-0",children:e.jsx(Gs,{sizeClass:"w-10 h-10"})}),e.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",e.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),e.jsx("nav",{className:"space-y-2",children:h.map(f=>{const L=f.icon,F=s===f.id;return e.jsxs("button",{onClick:()=>l(f.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${F?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[e.jsx(L,{className:`w-5 h-5 transition-colors ${F?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:f.label}),F&&e.jsx(Ft,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},f.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:c,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[e.jsx(oa,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},Oa=3e4,qa=10*6e4;let Ds=!1;const Wt=()=>{Ds||typeof window>"u"||(Ds=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{Ds=!1}))},Ba=s=>{if(!s)return"";const t=new URLSearchParams;for(const[c,h]of Object.entries(s))h!=null&&t.set(c,String(h));const l=t.toString();return l?`?${l}`:""},$s=async(s,t,l={})=>{var I;const c=Ba(l.params),h=`${t}${c}`,f=Vt(l.signal,l.timeoutMs??Oa);let L;try{L=await fetch(h,{method:s,credentials:"include",signal:f.signal,headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)})}catch(j){throw f.signal.aborted?new Error((I=l.signal)!=null&&I.aborted?"请求已取消":"请求超时,请稍后重试"):j}finally{f.cleanup()}const g=(L.headers.get("content-type")||"").includes("application/json");if(!L.ok){L.status===401&&!l.skipAuthLogout&&Wt();const j=g?await L.json().catch(()=>{}):await L.text().catch(()=>{}),G=typeof j=="string"?j:(j==null?void 0:j.detail)||(j==null?void 0:j.message)||(j==null?void 0:j.msg);throw new Error(G||`请求失败: ${L.status}`)}return g?await L.json():await L.text()},ge=async(s,t,l)=>$s("GET",s,{params:t,...l}),be=async(s,t,l)=>$s("POST",s,{body:t,...l}),Ee=async(s,t,l)=>$s("PUT",s,{body:t,...l}),Ue=async(s,t,l)=>$s("DELETE",s,{params:t,...l}),vs=async(s,t,l={})=>{var g;const c=Vt(l.signal,l.timeoutMs??qa);let h;try{h=await fetch(s,{method:"POST",credentials:"include",signal:c.signal,body:t})}catch(I){throw c.signal.aborted?new Error((g=l.signal)!=null&&g.aborted?"请求已取消":"上传超时,请稍后重试"):I}finally{c.cleanup()}const F=(h.headers.get("content-type")||"").includes("application/json")?await h.json().catch(()=>{}):await h.text().catch(()=>{});if(!h.ok){h.status===401&&Wt();const I=typeof F=="string"?F:(F==null?void 0:F.detail)||(F==null?void 0:F.message)||(F==null?void 0:F.msg),j=new Error(I||"请求失败: "+h.status);throw j.payload=F,j}return F},Vt=(s,t)=>{const l=new AbortController,c=()=>l.abort(s==null?void 0:s.reason);s!=null&&s.aborted?c():s==null||s.addEventListener("abort",c,{once:!0});const h=globalThis.setTimeout(()=>l.abort(new DOMException("timeout","TimeoutError")),Math.max(1,t));return{signal:l.signal,cleanup:()=>{globalThis.clearTimeout(h),s==null||s.removeEventListener("abort",c)}}},As=s=>{const t=s.getFullYear(),l=String(s.getMonth()+1).padStart(2,"0"),c=String(s.getDate()).padStart(2,"0");return`${t}-${l}-${c}`},Xs=(s,t)=>{const l=new Date(s);return l.setHours(12,0,0,0),l.setDate(l.getDate()+t),l},Js=(s,t)=>({startDate:As(Xs(s,-(t-1))),endDate:As(s)}),gt=(s,t=new Date,l="",c="")=>{if(s==="custom"&&l&&c){if(l>c)throw new Error("开始日期不能晚于结束日期");return{startDate:l,endDate:c}}return s==="yesterday"?Js(Xs(t,-1),1):Js(t,s==="3days"?3:s==="30days"?30:s==="today"?1:7)},za=s=>{const t=new Date(`${s.startDate}T12:00:00`),l=new Date(`${s.endDate}T12:00:00`),c=Math.round((l.getTime()-t.getTime())/864e5)+1,h=Xs(t,-1);return Js(h,c)},Ua=s=>{const t={...s};if("renewal_log_retention_days"in t){const l=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(l)?l:10}return t},Wa=async s=>be("/login",s,{skipAuthLogout:!0}),Gt=async()=>ge("/verify"),Va=async()=>be("/logout",{}),Ga=async s=>Ee("/account/credentials",s),Ja=(s,t)=>{const l=s.avatar_url||"";if(!l)return"";try{const c=new URL(l,window.location.origin);return c.hostname.endsWith("alicdn.com")&&c.searchParams.set("_v",t),c.toString()}catch{return l}},Rs=async s=>{const t=await ge("/cookies/details",void 0,s),l=Date.now().toString();return t.map(c=>({id:c.id,value:"",cookie:"",enabled:c.enabled,auto_confirm:c.auto_confirm,remark:c.remark,note:c.remark,pause_duration:c.pause_duration,paused_until:Number(c.paused_until||0),paused:c.paused===!0,username:c.username||"",login_password:"",show_browser:c.show_browser===!0||c.show_browser===1||c.show_browser==="1"||c.show_browser==="true",nickname:c.nickname||c.remark||`账号 ${c.id.substring(0,6)}`,avatar_url:Ja(c,l),profile_error:c.profile_error||"",ai_enabled:!1}))},Qa=async s=>ge("/cookies/runtime-status",void 0,s),Ka=async s=>be("/qr-login/generate",void 0,s),Ya=async(s,t)=>ge(`/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),Za=async(s,t)=>be(`/qr-login/complete-verification/${s}`,{target_account_id:t||""}),Xa=async(s,t)=>Ee(`/cookies/${s}/status`,{enabled:t}),Ha=async s=>Ue(`/cookies/${s}`),el=async(s,t)=>Ee(`/cookies/${s}/pause-duration`,{pause_duration:t}),sl=async(s,t)=>Ee(`/cookies/${s}/settings`,t),tl=async s=>ge(`/cookies/${s}/long-login`),al=async(s,t)=>Ee(`/cookies/${s}/long-login`,{enabled:t}),ll=async s=>be("/password-login",s),rl=async(s,t)=>ge(`/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),nl=async s=>Ue(`/password-login/cancel/${s}`),il=async s=>be(`/cookies/${s}/refresh-profile`,{}),ol=async s=>ge("/ai-reply-settings",void 0,s),Jt=s=>{const t=String(s||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},cl=async(s,t,l=1,c=20,h)=>{const f={page:l,page_size:c};s&&(f.cookie_id=s),t&&t!=="all"&&(f.status=t),h!=null&&h.trim()&&(f.search=h.trim());const L=await ge("/api/orders",f),g=(L.orders||L.data||[]).map(I=>({...I,id:I.id||I.order_id,status:Jt(I.status||I.order_status),quantity:Number(I.quantity||1)}));return{success:!0,data:g,total:L.total||g.length,page:L.page||l,page_size:L.page_size||c,total_pages:L.total_pages||1}},dl=async(s,t)=>Ee(`/api/orders/${s}`,t),xl=async s=>Ue(`/api/orders/${s}`),ml=async(s,t)=>{const l=new FormData;return s&&l.append("cookie_id",s),t&&l.append("status",t),vs("/api/orders/refresh",l)},ul=async s=>be(`/api/orders/${s}/refresh`),pl=async(s,t)=>be("/api/orders/manual-ship",{order_ids:s,ship_mode:t}),hl=async s=>s instanceof FormData?vs("/api/orders/import",s):be("/api/orders/import",s),gl=async()=>ge("/dashboard/stats"),bt=async(s=7)=>{let t;if(typeof s=="number"){const l=new Date,c=new Date;c.setDate(c.getDate()-s),t={start_date:As(c),end_date:As(l)}}else t=s;return ge("/analytics/orders",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()})},bl=async s=>{const t=await ge("/analytics/orders/valid",{start_date:s.start_date,end_date:s.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()}),c=(Array.isArray(t)?t:t.orders||[]).map(h=>({...h,id:h.id||h.order_id,status:Jt(h.status||h.order_status),quantity:Number(h.quantity||1)}));return{orders:c,total:Array.isArray(t)?c.length:Number(t.total??c.length),truncated:Array.isArray(t)?!1:t.truncated===!0}},fl=s=>{let t=s.api_config;if(typeof t=="string"&&t.trim())try{t=JSON.parse(t)}catch{t=void 0}return{...s,api_config:t||void 0}},Qt=s=>({...s,api_config:s.api_config?JSON.stringify(s.api_config):""}),Ve=async()=>{const s=await ge("/cards");return(Array.isArray(s)?s:s.cards||[]).map(fl)},yl=async s=>be("/cards",Qt(s)),ft=async(s,t)=>Ee(`/cards/${s}`,Qt(t)),jl=async s=>Ue(`/cards/${s}`),Nl=async s=>{const t=new FormData;return t.append("file",s),vs("/cards/batch",t)},vl=async(s,t)=>be(`/cards/${s}/append-data`,{content:t}),Ms=s=>s===!0||s===1||s==="1",ps=async s=>{const t=await ge("/items",void 0);return(Array.isArray(t)?t:t.items||[]).map(c=>({...c,id:c.id||`${c.cookie_id}-${c.item_id}`,is_multi_spec:Ms(c.is_multi_spec),is_multi_qty_ship:Ms(c.is_multi_qty_ship??c.multi_quantity_delivery),multi_quantity_delivery:Ms(c.multi_quantity_delivery??c.is_multi_qty_ship)}))},_l=async s=>be("/items/get-all-from-account",{cookie_id:s}),wl=async(s,t)=>Ue(`/items/${s}/${t}`),kl=async(s,t)=>be(`/items/${s}`,t),Cl=async s=>{const t=new FormData;t.set("cookie_id",s.cookie_id),t.set("title",s.title),t.set("description",s.description),t.set("price",s.price),t.set("original_price",s.original_price||""),t.set("quantity",String(s.quantity)),t.set("postage_mode",s.postage_mode),t.set("postage",s.postage||"");for(const l of s.images)t.append("images",l);return vs("/items/publish",t)},Sl=async s=>{const t=new FormData;return t.set("file",s.file),s.imagesZip&&t.set("images_zip",s.imagesZip),s.defaultCookieId&&t.set("default_cookie_id",s.defaultCookieId),vs("/items/publish-batches/preview",t)},Ll=async s=>be("/items/publish-batches",{preview_id:s}),os=async s=>ge(`/items/publish-batches/${s}`),yt=async(s=20)=>{const t=await ge("/items/publish-batches",{limit:s});return Array.isArray(t)?t:t.batches||[]},Al=async s=>Ue(`/items/publish-batches/${s}`),Il=async s=>be(`/items/publish-batches/${s}/cancel`,{}),$l=async s=>be(`/items/publish-batches/${s}/retry-failed`,{}),Rl=async(s,t,l)=>Ee(`/items/${s}/${t}`,l),Is=async()=>{const s=await ge("/automation-rules");return(Array.isArray(s)?s:s.data||s.rules||[]).map(l=>{var c,h;return{id:String(l.id),name:l.name||"",trigger_type:l.trigger_type||"order_paid",item_keyword:l.item_title||l.item_id||"",cookie_id:l.cookie_id||"",item_id:l.item_id||"",item_title:l.item_title||"",card_group_id:Number(((c=(l.actions||[]).find(f=>f.action_type==="send_card"))==null?void 0:c.card_id)||0),card_group_name:((h=(l.actions||[]).find(f=>f.action_type==="send_card"))==null?void 0:h.card_name)||"",priority:l.priority||100,enabled:l.enabled||!1,config_json:l.config_json||"{}",actions:(l.actions||[]).map(f=>({id:f.id?String(f.id):void 0,action_type:f.action_type,card_id:Number(f.card_id||0),card_name:f.card_name||"",delivery_count:Number(f.delivery_count||1),message_template:f.message_template||"",delay_seconds:Number(f.delay_seconds||0),config_json:f.config_json||"{}",enabled:f.enabled!==!1,sort_order:Number(f.sort_order||0)})),variants:(l.actions||[]).filter(f=>f.action_type==="send_card").map(f=>{let L={};try{L=JSON.parse(f.config_json||"{}")}catch{}return{id:f.id?String(f.id):void 0,spec_name:L.spec_name||"",spec_value:L.spec_value||"",card_id:Number(f.card_id||0),card_name:f.card_name||"",delivery_count:Number(f.delivery_count||1),enabled:f.enabled!==!1,delay_override:L.delay_override===!0,delay_seconds:Number(f.delay_seconds||0),config_json:f.config_json||"{}"}})}})},Pl=(s,t)=>{if(s!=="order_paid")return t.map((h,f)=>({...h,sort_order:h.sort_order||f+1}));const l=t.filter(h=>h.action_type==="send_card").map((h,f)=>({...h,sort_order:f+1})),c=t.filter(h=>h.action_type!=="send_card"&&h.action_type!=="confirm_shipment");return[...l,...c.map((h,f)=>({...h,sort_order:l.length+f+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:l.length+c.length+1}]},jt=async s=>{const t=s.trigger_type||"order_paid",c=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[t]||"自动化规则",s.item_title||s.item_id||s.cookie_id||""].filter(Boolean).join(" - "),h=(s.actions||[]).filter(g=>g.action_type!=="send_card"&&g.action_type!=="confirm_shipment"),f=s.variants&&s.variants.length>0?[...s.variants.map((g,I)=>({action_type:"send_card",card_id:g.card_id,delivery_count:g.delivery_count||1,enabled:g.enabled!==!1,sort_order:I+1,delay_seconds:g.delay_seconds||0,config_json:JSON.stringify({spec_name:g.spec_name||"",spec_value:g.spec_value||"",delay_override:g.delay_override===!0})})),...h]:s.actions&&s.actions.length>0?s.actions:[{action_type:"send_card",card_id:s.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],L=Pl(t,f),F={cookie_id:s.cookie_id||"",item_id:s.item_id||"",name:(s.name||"").trim()||c||"自动化规则",trigger_type:t,enabled:s.enabled??!0,priority:s.priority||100,config_json:s.config_json||"{}",actions:L.map((g,I)=>({action_type:g.action_type,card_id:g.card_id||0,delivery_count:g.delivery_count||1,message_template:g.message_template||"",delay_seconds:g.delay_seconds||0,config_json:g.config_json||"{}",enabled:g.enabled!==!1,sort_order:g.sort_order||I+1}))};return s.id?Ee(`/automation-rules/${s.id}`,F):be("/automation-rules",F)},Tl=async s=>Ue(`/automation-rules/${s}`),El=async()=>{const s=await ge("/automation-issues");return{runs:Array.isArray(s==null?void 0:s.runs)?s.runs:[],pending_tasks:Array.isArray(s==null?void 0:s.pending_tasks)?s.pending_tasks:[]}},Fl=async(s,t)=>be(`/automation-runs/${s}/resolve`,{resolution:t}),Dl=async(s,t)=>be(`/automation-pending-tasks/${s}/resolve`,{resolution:t}),Ml=s=>({id:String((s==null?void 0:s.id)||""),keyword:(s==null?void 0:s.keyword)||"",reply:(s==null?void 0:s.reply)||"",item_id:(s==null?void 0:s.item_id)||"",type:(s==null?void 0:s.type)==="image"?"image":"text",image_url:(s==null?void 0:s.image_url)||""}),Ol=async s=>{const t=await ge(`/keywords-with-type/${s}`);return Array.isArray(t)?t.map(Ml):[]},ql=async s=>s?(await Ol(s)).map(l=>({id:l.id,keyword:l.keyword||"",reply_content:l.reply||"",match_type:"fuzzy",enabled:!0,item_id:l.item_id||"",type:l.type==="image"?"image":"text",image_url:l.image_url||""})):[],Bl=async(s,t)=>{const l=s.type||"text",c={keyword:s.keyword||"",reply:l==="text"&&s.reply_content||"",item_id:s.item_id||"",type:l,image_url:l==="image"&&s.image_url||""};return s.id?Ee(`/keywords-with-type/${t}/${s.id}`,c):be(`/keywords-with-item-id/${t}`,c)},zl=async(s,t)=>Ue(`/keywords-with-type/${t}/${s}`),Kt=async()=>{const s=await ge("/system-settings");return Ua(s.data||s)},Yt=async s=>{const t=Object.fromEntries(Object.entries(s).filter(([,l])=>l!=null));return Ee("/system-settings",t)},Ul=async(s,t)=>ge(`/ai-reply-settings/${s}`,void 0,t),Wl=async(s,t)=>{const l={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return Ee(`/ai-reply-settings/${s}`,l)},Vl=async(s,t="")=>(await be("/ai-models",{base_url:s,api_key:t})).models||[],Gl=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},Zt=s=>{const t=Array.from(new Set((s||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Xt=async s=>({success:!0,data:(await ge("/notification-channels",void 0,s)||[]).map(c=>{let h;try{h=typeof c.config=="string"?JSON.parse(c.config):c.config}catch{h={}}return{id:String(c.id),name:c.name,type:c.type==="ding_talk"?"dingtalk":c.type==="lark"?"feishu":c.type,config:h,event_types:Gl(c.event_types),enabled:c.enabled,created_at:c.created_at,updated_at:c.updated_at}})}),Jl=async s=>be("/notification-channels",{...s,config:JSON.stringify(s.config),event_types:Zt(s.event_types)}),Nt=async(s,t)=>{const l={...t};return"config"in t&&(l.config=JSON.stringify(t.config)),"event_types"in t&&(l.event_types=Zt(t.event_types)),Ee(`/notification-channels/${s}`,l)},Ql=async s=>Ue(`/notification-channels/${s}`),Kl=async(s,t)=>{const l=await ge(`/message-notifications/${s}`,void 0,t);return(l==null?void 0:l.channel_ids)||[]},Yl=async s=>be(`/notification-channels/${s}/test`,{}),vt=async()=>ge("/api/default-replies"),Zl=async s=>{const t=await ge(`/api/default-reply/${s}`);return{cookie_id:s,enabled:t.enabled||!1,reply_content:t.reply_content||"",reply_once:t.reply_once||!1,reply_image_url:t.reply_image_url||""}},Xl=async(s,t)=>Ee(`/api/default-reply/${s}`,{enabled:t.enabled??!1,reply_content:t.reply_content||"",reply_once:t.reply_once??!1,reply_image_url:t.reply_image_url||""}),Hl=async s=>Ue(`/api/default-reply/${s}`),er=async s=>be(`/api/default-reply/${s}/clear-records`,{}),gs=s=>String(s).padStart(2,"0"),Qs=s=>{if(s==null||s==="")return"-";const t=s instanceof Date?s:new Date(s);return Number.isNaN(t.getTime())?"-":[t.getFullYear(),gs(t.getMonth()+1),gs(t.getDate())].join("-")+" "+[gs(t.getHours()),gs(t.getMinutes()),gs(t.getSeconds())].join(":")},sr=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},ks=({title:s,value:t,icon:l,colorClass:c,trend:h})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${c} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${c} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(l,{className:`w-6 h-6 ${c.replace("bg-","text-")}`})}),h&&e.jsxs("span",{className:"text-xs font-bold text-white bg-[#0094f7] px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(da,{className:"w-3 h-3"})," ",h]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:t}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:s})]})]}),Os=()=>{var i,q;const[s,t]=n.useState(null),[l,c]=n.useState(null),[h,f]=n.useState(""),[L,F]=n.useState("7days"),[g,I]=n.useState(""),[j,G]=n.useState(""),[Y,X]=n.useState(null),[de,C]=n.useState(""),[M,oe]=n.useState([]),[ee,xe]=n.useState(0),[O,le]=n.useState(!1),[D,N]=n.useState(!1),[$,T]=n.useState([]),[J,ue]=n.useState({}),Q=n.useRef(0),A=["#0094f7","#3B82F6","#10B981","#F59E0B","#8B5CF6"],b=async d=>{let _;try{_=gt(d,new Date,g,j)}catch(_e){f(_e instanceof Error?_e.message:"日期范围无效");return}const{startDate:te,endDate:Z}=_,pe={start_date:te,end_date:Z},Ne=za(_),ce=++Q.current;N(!0),f("");try{const[_e,Re,ye]=await Promise.all([bt(pe),bt({start_date:Ne.startDate,end_date:Ne.endDate}),bl(pe)]);if(ce!==Q.current)return;c(_e),X(Re),oe(ye.orders),xe(ye.total),le(ye.truncated)}catch(_e){ce===Q.current&&f(_e instanceof Error?_e.message:"经营数据加载失败")}finally{ce===Q.current&&N(!1)}},v=()=>{if(!l||!Y)return null;const d=l.revenue_stats.total_amount,_=Y.revenue_stats.total_amount;if(_===0)return d>0?"+100%":"0%";const te=(d-_)/_*100;return`${te>=0?"+":""}${te.toFixed(1)}%`};if(n.useEffect(()=>{let d=!1;return Promise.all([gl(),ps()]).then(([_,te])=>{if(d)return;t(_),T(te);const Z={};te.forEach(pe=>{Z[pe.item_id]=pe.item_title||pe.item_id}),ue(Z)}).catch(_=>{d||f(_ instanceof Error?_.message:"概览加载失败")}),()=>{d=!0}},[]),n.useEffect(()=>{L!=="custom"&&b(L)},[L]),h&&(!s||!l))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(ms,{className:"w-8 h-8"}),e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:()=>window.location.reload(),children:"重新加载"})]});if(!s||!l)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(rt,{className:"w-8 h-8 animate-spin text-[#0094f7]"})});const B=((i=l.daily_stats)==null?void 0:i.map(d=>({name:d.date.slice(5),amount:d.amount,orders:d.order_count,avgAmount:d.order_count>0?(d.amount/d.order_count).toFixed(2):0})))||[],R=l.item_stats||[],K=l.revenue_stats.total_orders||0,H=l.revenue_stats.total_amount||0,m=R.length>0?R.map(d=>({name:(J[d.item_id]||d.item_id).length>12?(J[d.item_id]||d.item_id).substring(0,12)+"...":J[d.item_id]||d.item_id,sales:d.order_count})).sort((d,_)=>_.sales-d.sales).slice(0,10):[],p=Math.max(...m.map(d=>d.sales),1),y=R.length>0?R.map(d=>({name:(J[d.item_id]||d.item_id).length>10?(J[d.item_id]||d.item_id).substring(0,10)+"...":J[d.item_id]||d.item_id,value:d.order_count,percent:K>0?d.order_count/K*100:0})).sort((d,_)=>_.value-d.value).slice(0,6).map((d,_)=>({...d,color:A[_%A.length]})):[],S=R.length>0?R.map(d=>({name:(J[d.item_id]||d.item_id).length>12?(J[d.item_id]||d.item_id).substring(0,12)+"...":J[d.item_id]||d.item_id,value:d.total_amount,orderCount:d.order_count,percentage:H>0?d.total_amount/H*100:0})).sort((d,_)=>_.value-d.value).slice(0,5).map((d,_)=>({...d,color:A[_%A.length],percentage:d.percentage.toFixed(1)})):[],U=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}],se=((q=U.find(d=>d.key===L))==null?void 0:q.label)||"所选范围";let z;try{z=gt(L,new Date,g,j)}catch{z={startDate:g,endDate:j}}const re=de.trim().toLowerCase(),E=M.filter(d=>{var _,te,Z,pe;return((_=d.order_id)==null?void 0:_.toLowerCase().includes(re))||((te=d.item_id)==null?void 0:te.toLowerCase().includes(re))||((Z=d.item_title)==null?void 0:Z.toLowerCase().includes(re))||((pe=d.buyer_id)==null?void 0:pe.toLowerCase().includes(re))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[U.map(d=>e.jsx("button",{onClick:()=>F(d.key),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${L===d.key?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:d.label},d.key)),L==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:g,onChange:d=>I(d.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:j,onChange:d=>G(d.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),e.jsx("button",{onClick:()=>{try{f(""),b("custom")}catch(d){f(d instanceof Error?d.message:"日期范围无效")}},className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(ks,{title:"累计营收 (CNY)",value:`¥${l.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:ca,colorClass:"bg-blue-400",trend:v()||void 0}),e.jsx(ks,{title:"活跃账号 / 总数",value:`${s.active_cookies} / ${s.total_cookies}`,icon:Pt,colorClass:"bg-blue-500"}),e.jsx(ks,{title:"订单数",value:l.revenue_stats.total_orders.toLocaleString(),icon:nt,colorClass:"bg-blue-500"}),e.jsx(ks,{title:"库存卡密余量",value:s.available_card_stock,icon:Dt,colorClass:"bg-purple-500"})]}),e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[se,"的销售额走势"]})]}),e.jsx("div",{className:"h-[350px] w-full",children:B.length===0||l.revenue_stats.total_amount===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(nt,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):B.length<=2?e.jsx(ws,{width:"100%",height:"100%",children:e.jsxs($a,{data:B,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(mt,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#374151",fontSize:14,fontWeight:600},dy:10}),e.jsx(ut,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},tickFormatter:d=>`¥${d}`}),e.jsx(Es,{contentStyle:{backgroundColor:"#fff",borderRadius:"8px",border:"1px solid #e5e7eb",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1)",padding:"12px 16px"},labelStyle:{color:"#6b7280",fontWeight:500},itemStyle:{color:"#0094f7",fontWeight:600},cursor:{fill:"rgba(0, 148, 247, 0.08)"},formatter:d=>[`¥${Number(d).toFixed(2)}`,"营收"]}),e.jsx(Ra,{dataKey:"amount",fill:"#0094f7",maxBarSize:72,radius:[12,12,0,0],stroke:"#000000",strokeWidth:0,children:B.map((d,_)=>e.jsx(Fs,{fill:["#0094f7","#FCD34D","#0071e3"][_%3]},`cell-${_}`))})]})}):e.jsx(ws,{width:"100%",height:"100%",children:e.jsxs(Pa,{data:B,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#0094f7",stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:"#0094f7",stopOpacity:0})]})}),e.jsx(mt,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},dy:15}),e.jsx(ut,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500}}),e.jsx(Ta,{vertical:!1,stroke:"#F3F4F6",strokeDasharray:"3 3"}),e.jsx(Es,{contentStyle:{backgroundColor:"#fff",borderRadius:"8px",border:"1px solid #e5e7eb",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1)",padding:"12px 16px"},labelStyle:{color:"#6b7280",fontWeight:500},itemStyle:{color:"#0094f7",fontWeight:600},cursor:{stroke:"#0094f7",strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Ea,{type:"monotone",dataKey:"amount",stroke:"#0094f7",strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:"#fff",stroke:"#0094f7",strokeWidth:2}})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:m.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:m.map((d,_)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${_<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:_+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:d.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[d.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[#0094f7]",style:{width:`${Math.max(8,d.sales/p*100)}%`}})})]},`${d.name}-${_}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"h-[280px]",children:y.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx(ws,{width:"100%",height:"100%",children:e.jsxs(pt,{children:[e.jsx(ht,{data:y,cx:"50%",cy:"50%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",label:({name:d,payload:_})=>`${d} ${Number((_==null?void 0:_.percent)||0).toFixed(1)}%`,labelLine:!1,children:y.map((d,_)=>e.jsx(Fs,{fill:d.color},`cell-${_}`))}),e.jsx(Fa,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:d=>e.jsx("span",{style:{color:"#6B7280",fontWeight:500},children:d})})]})})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-[#FAFAFA]",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),O&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",M.length," / ",ee," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:de,onChange:d=>C(d.target.value),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:D?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(rt,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):E.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(Ns,{className:"w-7 h-7 text-gray-300"})}),re?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",M.length," 单参与统计,但没有订单号、商品、买家匹配“",de,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",z.startDate," 至 ",z.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",l.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:E.map(d=>e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(Ns,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:d.item_title||d.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:d.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",d.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:d.buyer_id}),d.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:Qs(d.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",d.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4",children:e.jsx(sr,{status:d.status||d.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${d.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(Mt,{className:"w-4 h-4"})})})]},d.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),S.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-[300px] relative",children:e.jsx(ws,{width:"100%",height:"100%",children:e.jsxs(pt,{children:[e.jsx(ht,{data:S,cx:"50%",cy:"50%",innerRadius:60,outerRadius:100,paddingAngle:2,dataKey:"value",label:({name:d,payload:_})=>`${d} ${(_==null?void 0:_.percentage)||"0.0"}%`,children:S.map((d,_)=>e.jsx(Fs,{fill:d.color||A[_%A.length]},`cell-${_}`))}),e.jsx(Es,{contentStyle:{backgroundColor:"#fff",border:"1px solid #e5e7eb",borderRadius:"6px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)"},formatter:d=>`¥${Number(d||0).toLocaleString()}`})]})})}),e.jsx("div",{className:"space-y-3 mt-4",children:S.map(d=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:d.color||A[S.indexOf(d)%A.length]}}),e.jsx("span",{className:"text-gray-600 font-medium",children:d.name})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",d.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[d.percentage,"%"]})]})]},d.name))})]})]})]})]})},tr=(s,t)=>{const l=t.pause_duration||0;return s!==l},ar=(s,t)=>{const l=t.username!==(s.username||""),c=t.show_browser!==(s.show_browser||!1),h=t.login_password!=="",f=t.clear_password===!0;if(!l&&!c&&!h&&!f)return null;const L={username:t.username,show_browser:t.show_browser};return f?L.clear_password=!0:h&&(L.login_password=t.login_password),L},lr=(s,t)=>s&&t,rr=(s,t)=>{if(!s||!t)return!1;const l=Date.parse(s),c=Date.parse(t);return Number.isFinite(l)&&Number.isFinite(c)&&cs.map(l=>{const c=t[l.id];return!c||rr(l.runtime_updated_at,c.updated_at)?l:{...l,runtime_state:c.state,runtime_message:c.message||"",runtime_connected:c.connected,runtime_updated_at:c.updated_at}}),ir=new Set(["expired","cancelled","error","not_found"]),Cs=()=>{let s=0;return{next:()=>(s+=1,s),cancel:()=>{s+=1},isCurrent:t=>t===s}},or=(s={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let t=null,l=null,c=-1,h=0;const f=()=>{h+=1,l==null||l.abort(),l=null,t!==null&&(s.clearInterval(t),t=null)};return{start:(F,g,I,j=2e3)=>{f();const G=h;l=new AbortController;const Y=l.signal;t=s.setInterval(()=>{c===G||G!==h||(c=G,(async()=>{var X,de;try{const C=await g(F,Y);if(C.status==="success"){f(),await I.onSuccess(C);return}if(C.status==="scanned"){(X=I.onScanned)==null||X.call(I,C);return}if(C.status==="verification_required"){(de=I.onVerificationRequired)==null||de.call(I,C);return}C.status&&ir.has(C.status)&&(f(),I.onTerminalError(C))}catch(C){if(Y.aborted||G!==h)return;f(),I.onPollError(C)}finally{c===G&&(c=-1)}})())},j)},stop:f,isActive:()=>t!==null}},cr=({faceQrUrl:s,verificationScreenshot:t})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(xa,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:s?e.jsx("img",{src:s,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):t?e.jsx("img",{src:t,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(Te,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),_t=({src:s,alt:t,className:l=""})=>e.jsx("img",{src:s,alt:t,className:`block aspect-square h-auto w-full object-contain ${l}`.trim()}),dr=()=>{const[s,t]=n.useState([]),[l,c]=n.useState(!0),[h,f]=n.useState(""),[L,F]=n.useState(""),[g,I]=n.useState(!1),[j,G]=n.useState(""),[Y,X]=n.useState("pending"),[de,C]=n.useState(""),[M,oe]=n.useState(""),[ee,xe]=n.useState(null),[O,le]=n.useState(null),[D,N]=n.useState(null),[$,T]=n.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[J,ue]=n.useState([]),[Q,A]=n.useState([]),[b,v]=n.useState(!1),[B,R]=n.useState(!1),[K,H]=n.useState(!1),[m,p]=n.useState(""),[y,S]=n.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),[U,se]=n.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[z,re]=n.useState(!1),[E,i]=n.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),q=n.useRef(null),d=n.useRef(null),_=n.useRef(null),te=n.useRef(null),Z=n.useRef(null),pe=n.useRef(null),Ne=n.useRef(null),ce=n.useRef(null),_e=n.useRef(null),Re=n.useRef(null),ye=n.useRef(null),Ae=n.useRef(null),Le=n.useRef(0);q.current===null&&(q.current=or()),d.current===null&&(d.current=Cs()),_.current===null&&(_.current=Cs()),te.current===null&&(te.current=Cs()),Z.current===null&&(Z.current=Cs());const Be=()=>{ye.current!==null&&(window.clearTimeout(ye.current),ye.current=null)},Ie=()=>{Ae.current!==null&&(window.clearTimeout(Ae.current),Ae.current=null)},Me=()=>{var o;(o=q.current)==null||o.stop()},We=()=>{var o,k;(o=_e.current)==null||o.abort(),(k=d.current)==null||k.cancel(),Me(),Be(),I(!1)},Ye=()=>{Be(),ye.current=window.setTimeout(()=>{ye.current=null,I(!1),$e()},1e3)},$e=async()=>{var V,ne,ie,ke,Pe;const o=_.current.next();(V=pe.current)==null||V.abort();const k=new AbortController;pe.current=k,c(!0);try{const Ce={signal:k.signal},[Fe,ts]=await Promise.allSettled([Rs(Ce),ol(Ce)]);if(!((ne=_.current)!=null&&ne.isCurrent(o)))return;if(Fe.status==="rejected")throw Fe.reason;const Oe=Fe.value,hs=ts.status==="fulfilled"?ts.value:{};ts.status==="rejected"&&console.error("Failed to load AI settings:",ts.reason);const la=Oe.map(is=>{var et,st,tt,at,lt;return{...is,ai_enabled:((et=hs[is.id])==null?void 0:et.ai_enabled)??!1,max_discount_percent:((st=hs[is.id])==null?void 0:st.max_discount_percent)??10,max_discount_amount:((tt=hs[is.id])==null?void 0:tt.max_discount_amount)??100,max_bargain_rounds:((at=hs[is.id])==null?void 0:at.max_bargain_rounds)??3,custom_prompts:((lt=hs[is.id])==null?void 0:lt.custom_prompts)??""}});(ie=_.current)!=null&&ie.isCurrent(o)&&t(la)}catch(Ce){(ke=_.current)!=null&&ke.isCurrent(o)&&!k.signal.aborted&&console.error("Failed to load accounts:",Ce)}finally{(Pe=_.current)!=null&&Pe.isCurrent(o)&&c(!1)}};n.useEffect(()=>{let o=!1,k=null;const V=new AbortController,ne=async()=>{try{const ie=await Qa({signal:V.signal,timeoutMs:1e4});o||t(ke=>nr(ke,ie))}catch(ie){o||console.error("Failed to load account runtime statuses:",ie)}finally{o||(k=window.setTimeout(()=>void ne(),2e3))}};return $e().finally(()=>{o||ne()}),()=>{o=!0,V.abort(),k!==null&&window.clearTimeout(k)}},[]),n.useEffect(()=>()=>{var o,k,V,ne,ie,ke,Pe,Ce,Fe;Me(),(o=d.current)==null||o.cancel(),(k=_.current)==null||k.cancel(),(V=te.current)==null||V.cancel(),(ne=Z.current)==null||ne.cancel(),(ie=pe.current)==null||ie.abort(),(ke=Ne.current)==null||ke.abort(),(Pe=ce.current)==null||Pe.abort(),(Ce=_e.current)==null||Ce.abort(),(Fe=Re.current)==null||Fe.abort(),Be(),Le.current+=1,Ie()},[]);const ss=o=>{if(!o.enabled||o.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(o.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},Ze=async(o,k)=>{await Xa(o,!k),$e()},Xe=async o=>{confirm("确认删除该账号吗?")&&(await Ha(o),$e())},He=async o=>{F(o.id);try{const k=await il(o.id);k!=null&&k.profile_error&&alert("资料刷新失败:"+k.profile_error),await $e()}catch(k){console.error("刷新账号资料失败:",k),alert((k==null?void 0:k.message)||"刷新账号资料失败,请先重新授权该账号")}finally{F("")}},x=async o=>{var ke,Pe;const k=te.current.next();(ke=Ne.current)==null||ke.abort();const V=new AbortController;Ne.current=V,R(!0),v(!1),H(!1),p("");const[ne,ie]=await Promise.allSettled([Xt({signal:V.signal}),Kl(o,{signal:V.signal})]);(Pe=te.current)!=null&&Pe.isCurrent(k)&&(ne.status==="fulfilled"?ue(ne.value.data||[]):(ue([]),p("通知渠道列表加载失败,请重试")),ie.status==="fulfilled"?(A(ie.value||[]),v(!0)):(A([]),p("通知绑定加载失败;本次保存不会修改现有绑定")),R(!1))},P=async o=>{var V;Le.current+=1,(V=Re.current)==null||V.abort(),Ie(),i({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),N(o),S({remark:o.remark||o.note||"",cookie:o.cookie||o.value||"",auto_confirm:o.auto_confirm||!1,pause_duration:o.pause_duration||0,username:o.username||"",login_password:o.login_password||"",show_browser:o.show_browser||!1,showLoginPassword:!1,clear_password:!1}),le("edit"),T({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,k]=await Promise.allSettled([x(o.id),tl(o.id)]);k.status==="fulfilled"?T({loading:!1,saving:!1,canOpen:k.value.can_open_long_login,enabled:k.value.enabled,error:""}):T({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"})},me=async()=>{if(!D||$.loading||$.saving||!$.canOpen)return;const o=!$.enabled;T(k=>({...k,saving:!0,error:""}));try{const k=await al(D.id,o);T({loading:!1,saving:!1,canOpen:k.can_open_long_login,enabled:k.enabled,error:""})}catch(k){T(V=>({...V,saving:!1,error:k instanceof Error?k.message:"保存登录信息设置失败"}))}},fe=async o=>{var ne,ie,ke,Pe;const k=Z.current.next();(ne=ce.current)==null||ne.abort();const V=new AbortController;ce.current=V,N(o),le("ai-settings"),re(!0);try{const Ce=await Ul(o.id,{signal:V.signal});if(!((ie=Z.current)!=null&&ie.isCurrent(k)))return;se({ai_enabled:Ce.ai_enabled??!1,max_discount_percent:Ce.max_discount_percent??10,max_discount_amount:Ce.max_discount_amount??100,max_bargain_rounds:Ce.max_bargain_rounds??3,custom_prompts:Ce.custom_prompts??""})}catch(Ce){(ke=Z.current)!=null&&ke.isCurrent(k)&&console.error("Failed to load AI settings:",Ce)}finally{(Pe=Z.current)!=null&&Pe.isCurrent(k)&&re(!1)}},ze=async()=>{if(D){re(!0);try{const o={};y.remark!==(D.remark||D.note||"")&&(o.remark=y.remark),y.cookie&&y.cookie!==(D.cookie||D.value||"")&&(o.cookie=y.cookie),y.auto_confirm!==D.auto_confirm&&(o.auto_confirm=y.auto_confirm),tr(y.pause_duration,D)&&(o.pause_duration=y.pause_duration);const k=ar(D,y);k&&Object.assign(o,k),lr(b,K)&&(o.channel_ids=Q),Object.keys(o).length>0&&await sl(D.id,o),le(null),$e()}catch(o){console.error("更新账号失败:",o),alert("更新失败,请重试")}finally{re(!1)}}},r=async()=>{if(!(!D||y.pause_duration<=0)){re(!0);try{const o=await el(D.id,y.pause_duration);N({...D,pause_duration:y.pause_duration,paused:(o==null?void 0:o.paused)===!0,paused_until:Number((o==null?void 0:o.paused_until)||0)}),await $e()}catch(o){alert(o instanceof Error?o.message:"重新暂停失败")}finally{re(!1)}}},a=async()=>{if(D){re(!0);try{await Wl(D.id,U),le(null),$e()}catch(o){console.error("更新AI设置失败:",o),alert("更新失败,请重试")}finally{re(!1)}}},u=async(o,k)=>{var ne;(ne=Re.current)==null||ne.abort();const V=new AbortController;Re.current=V;try{const ie=await rl(o,V.signal);if(k!==Le.current)return;if(ie.status==="success"){Ie(),i({sessionId:o,status:"success",message:ie.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}),S(ke=>({...ke,login_password:"",showLoginPassword:!1})),await $e();return}if(ie.status==="processing"||ie.status==="verification_required"){i({sessionId:o,status:ie.status,message:ie.message||(ie.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:ie.qr_code_url||""}),Ie(),Ae.current=window.setTimeout(()=>void u(o,k),1500);return}Ie(),i({sessionId:o,status:"failed",message:ie.error||ie.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""})}catch(ie){if(k!==Le.current)return;Ie(),i({sessionId:o,status:"failed",message:ie instanceof Error?ie.message:"查询密码登录状态失败",qrCodeUrl:""})}},w=async()=>{var V;if(!D)return;const o=y.username.trim();if(!o||!y.login_password){alert("请先填写登录账号和本次登录密码");return}Ie(),(V=Re.current)==null||V.abort();const k=++Le.current;i({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const ne=await ll({account_id:D.id,account:o,password:y.login_password,show_browser:y.show_browser});if(k!==Le.current)return;if(!ne.success||!ne.session_id)throw new Error(ne.message||"无法启动密码登录");i({sessionId:ne.session_id,status:"processing",message:ne.message||"登录处理中",qrCodeUrl:""}),await u(ne.session_id,k)}catch(ne){if(k!==Le.current)return;i({sessionId:"",status:"failed",message:ne instanceof Error?ne.message:"启动密码登录失败",qrCodeUrl:""})}},W=async()=>{var k;const o=E.sessionId;if(Le.current+=1,(k=Re.current)==null||k.abort(),Ie(),o)try{await nl(o)}catch(V){console.error("取消密码登录失败",V)}i({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},ae=async()=>{var o,k;(o=te.current)==null||o.cancel(),(k=Ne.current)==null||k.abort(),(E.status==="processing"||E.status==="verification_required")&&await W(),le(null)},ve=()=>{var o,k;(o=Z.current)==null||o.cancel(),(k=ce.current)==null||k.abort(),le(null)},he=async(o,k)=>{const V=await Za(o,k==null?void 0:k.id);if(!V.success||!V.account_id)throw new Error(V.message||"保存扫码授权失败");return V.account_id},De=async o=>{var ie,ke,Pe,Ce;Me(),(ie=_e.current)==null||ie.abort();const k=new AbortController;_e.current=k;const V=d.current.next();Be();const ne=o||null;xe(ne),I(!0),X("loading"),G(""),C(""),oe("");try{const Fe=await Ka({signal:k.signal});if(!((ke=d.current)!=null&&ke.isCurrent(V)))return;if(Fe.success&&Fe.qr_code_url&&Fe.session_id){const ts=Fe.session_id;G(Fe.qr_code_url),X("waiting"),(Pe=q.current)==null||Pe.start(ts,Ya,{onSuccess:async()=>{try{if(!await he(ts,ne)){X("error");return}}catch(Oe){console.error("保存扫码授权失败",Oe),X("error");return}X("success"),Ye()},onScanned:()=>{X("waiting")},onTerminalError:()=>{X("error")},onPollError:Oe=>{console.error("轮询扫码状态失败",Oe),X("error")},onVerificationRequired:Oe=>{X("verification"),Oe.face_qr_url&&oe(Oe.face_qr_url),Oe.verification_screenshot&&C(Oe.verification_screenshot)}})}}catch{if(!((Ce=d.current)!=null&&Ce.isCurrent(V)))return;X("error")}};if(l)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(Te,{className:"w-8 h-8 text-[#0094f7] animate-spin"})});const je=s.filter(o=>{const k=h.trim().toLowerCase();return k?[o.id,o.nickname,o.remark,o.note,o.username,o.runtime_message].some(V=>(V||"").toLowerCase().includes(k)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:h,onChange:o=>f(o.target.value),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:()=>De(),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Ps,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",je.length," / ",s.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[je.map(o=>{const k=ss(o),V=o.runtime_state==="auth_expired"||o.runtime_state==="verification_required";return e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300",children:[e.jsxs("div",{className:"flex items-center gap-5 sm:gap-8 min-w-0",children:[e.jsxs("div",{className:"relative",children:[o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(ns,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${k.dot}`,children:o.runtime_state==="online"&&e.jsx(Ge,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:o.nickname||o.remark||`账号 ${o.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${k.badge}`,children:k.label}),o.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(ds,{className:"w-3 h-3"})," AI"]}),o.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:o.profile_error,children:[e.jsx(ms,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"text-sm text-gray-500 font-medium mb-3 space-y-1",children:[e.jsx("p",{children:o.remark||o.note||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",o.id]})]}),o.runtime_message&&o.runtime_state!=="online"&&o.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${V?"text-red-700":"text-amber-700"}`,children:[e.jsx(ms,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:o.runtime_message}),V&&e.jsxs("button",{type:"button",onClick:()=>De(o),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(Ps,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),e.jsxs("div",{className:"flex gap-2",children:[o.auto_confirm&&e.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[e.jsx(Ge,{className:"w-3 h-3"})," 自动确认发货"]}),o.paused&&e.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[e.jsx(it,{className:"w-3 h-3"})," 暂停处理中"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 self-end lg:self-auto flex-shrink-0",children:[e.jsx("button",{onClick:()=>He(o),disabled:L===o.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(qe,{className:`w-5 h-5 ${L===o.id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>De(o),className:`p-3 rounded-xl transition-colors ${V?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(Ps,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>P(o),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Ot,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>fe(o),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(ds,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Ze(o.id,o.enabled),className:`p-3 rounded-xl transition-colors ${o.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:o.enabled?"停用账号":"启用账号",children:e.jsx(ma,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Xe(o.id),className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500",children:e.jsx(Je,{className:"w-5 h-5"})})]})]},o.id)}),s.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(ns,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),s.length>0&&je.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),g&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:We,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:ee?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:ee?`请用闲鱼APP扫码,为「${ee.nickname||ee.remark||ee.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-[#F7F8FA] rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${Y==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[Y==="loading"&&e.jsx(Te,{className:"w-10 h-10 text-[#0094f7] animate-spin"}),Y==="waiting"&&e.jsx(_t,{src:j,alt:"闲鱼登录二维码",className:"p-2"}),Y==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Ge,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),Y==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:"请关闭窗口后重新发起扫码登录。"})]}),Y==="verification"&&e.jsx(cr,{faceQrUrl:M,verificationScreenshot:de})]}),Y!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),O==="edit"&&D&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:D.nickname||D.remark||D.id})]}),e.jsx("button",{onClick:()=>void ae(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:D.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:y.remark,onChange:o=>S({...y,remark:o.target.value}),placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:y.cookie,onChange:o=>S({...y,cookie:o.target.value}),placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",y.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:()=>S({...y,auto_confirm:!y.auto_confirm}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${y.auto_confirm?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${y.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:y.pause_duration,onChange:o=>S({...y,pause_duration:parseInt(o.target.value)||0}),placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),y.pause_duration>0&&!D.paused&&y.pause_duration===(D.pause_duration||0)&&e.jsx("button",{type:"button",disabled:z,onClick:()=>void r(),className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(ua,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),$.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:$.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:$.loading||$.saving||!$.canOpen,onClick:()=>void me(),className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${$.enabled?"bg-[#0094f7]":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${$.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:y.username,onChange:o=>S({...y,username:o.target.value}),placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:y.showLoginPassword?"text":"password",value:y.login_password,onChange:o=>S({...y,login_password:o.target.value,clear_password:!1}),placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:()=>S({...y,showLoginPassword:!y.showLoginPassword}),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:y.showLoginPassword?e.jsx(rs,{className:"w-5 h-5"}):e.jsx(es,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:y.clear_password,onChange:o=>S({...y,clear_password:o.target.checked,login_password:o.target.checked?"":y.login_password}),className:"w-4 h-4 accent-[#0094f7]"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:()=>S({...y,show_browser:!y.show_browser}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${y.show_browser?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${y.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),E.status==="processing"||E.status==="verification_required"?e.jsx("button",{type:"button",onClick:W,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:w,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),E.message&&e.jsx("div",{className:`text-sm font-medium ${E.status==="failed"?"text-red-700":E.status==="success"?"text-green-700":"text-blue-800"}`,children:E.message}),E.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),E.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(_t,{src:E.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(J.length>0||B||m)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(xs,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),B&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Te,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),m&&!B&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:()=>x(D.id),children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:J.map(o=>{const k=Q.includes(Number(o.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:()=>{b&&(A(V=>k?V.filter(ne=>ne!==Number(o.id)):[...V,Number(o.id)]),H(!0))},disabled:!b,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${k?"bg-[#0094f7] border-[#0094f7]":"bg-white border-gray-300"}`,children:k&&e.jsx(Ge,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:o.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[o.type,o.enabled?"":" · 已停用"]})]})]},o.id)})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>void ae(),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:z,children:"取消"}),e.jsxs("button",{onClick:ze,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:z,children:[z?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),z?"保存中...":"保存"]})]})})]})}),document.body),O==="ai-settings"&&D&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ds,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:D.nickname||D.remark||D.id})]}),e.jsx("button",{onClick:ve,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(ds,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:()=>se({...U,ai_enabled:!U.ai_enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${U.ai_enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${U.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:U.max_discount_percent,onChange:o=>se({...U,max_discount_percent:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:U.max_discount_amount,onChange:o=>se({...U,max_discount_amount:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:U.max_bargain_rounds,onChange:o=>se({...U,max_bargain_rounds:parseInt(o.target.value)||1}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:U.custom_prompts,onChange:o=>se({...U,custom_prompts:o.target.value}),placeholder:`输入自定义的AI回复规则或风格指引... + +例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Ys,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:ve,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:z,children:"取消"}),e.jsxs("button",{onClick:a,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:z,children:[z?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),z?"保存中...":"保存"]})]})})]})}),document.body)]})},xr=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),mr=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],wt=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},ur=()=>{const[s,t]=n.useState([]),[l,c]=n.useState([]),[h,f]=n.useState([]),[L,F]=n.useState({}),[g,I]=n.useState("all"),[j,G]=n.useState(""),[Y,X]=n.useState(""),[de,C]=n.useState(""),M=n.useRef(0),[oe,ee]=n.useState(1),[xe,O]=n.useState(1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState(!1),[ue,Q]=n.useState(!1),[A,b]=n.useState(null),[v,B]=n.useState(null),[R,K]=n.useState({}),[H,m]=n.useState(!1),[p,y]=n.useState(""),[S,U]=n.useState(!1),[se,z]=n.useState(null),[re,E]=n.useState(null),[i,q]=n.useState(null),[d,_]=n.useState(!1),[te,Z]=n.useState(null),[pe,Ne]=n.useState(null),ce=async()=>{const x=++M.current;D(!0);try{const P=await cl(j||void 0,g,oe,20,de);if(x!==M.current)return;t(P.data),O(P.total_pages)}catch(P){console.error("加载订单失败:",P)}finally{x===M.current&&D(!1)}},_e=(x,P,me)=>{if(me&&me.trim())return me;if(L[`${x}:${P}`])return L[`${x}:${P}`];const fe=l.find(ze=>{if(me&&ze.item_title){const r=me.toLowerCase(),a=ze.item_title.toLowerCase();return a.includes(r)||r.includes(a)}return!1});return fe!=null&&fe.item_title?fe.item_title:"未知商品"},Re=x=>{const P={};x.forEach(me=>{me.item_id&&(P[`${me.cookie_id}:${me.item_id}`]=me.item_title||me.item_id)}),F(P)};n.useEffect(()=>{const x=window.setTimeout(()=>{ee(1),C(Y.trim())},300);return()=>window.clearTimeout(x)},[Y]),n.useEffect(()=>{ce()},[j,g,oe,de]),n.useEffect(()=>{Promise.all([Rs(),ps()]).then(([x,P])=>{f(x),c(P),Re(P)}).catch(x=>{console.error("加载商品列表失败:",x)})},[]);const ye=n.useMemo(()=>new Map(h.map(x=>[x.id,x])),[h]),Ae=x=>{const P=ye.get(x),me=(P==null?void 0:P.remark)||(P==null?void 0:P.nickname);return me?`${me} · ${x.slice(0,6)}`:`账号 ${x.slice(0,8)}`},Le=x=>{const P=ye.get(x);return(P==null?void 0:P.remark)||(P==null?void 0:P.nickname)||"未命名账号"},Be=async()=>{D(!0);try{const x=await ml(j||void 0,g);await ce(),x!=null&&x.message&&alert(x.message)}catch(x){console.error("同步订单失败:",x),alert((x==null?void 0:x.message)||"同步失败,请重试")}finally{D(!1)}},Ie=x=>{y(x),z(null),m(!0)},Me=async x=>{var P;U(!0),z(null);try{const me=await pl([p],x),fe=(P=me==null?void 0:me.results)==null?void 0:P[0];fe!=null&&fe.success?(z({success:!0,message:fe.message}),ce()):z({success:!1,message:(fe==null?void 0:fe.message)||"发货失败"})}catch(me){z({success:!1,message:(me==null?void 0:me.message)||"请求失败"})}finally{U(!1)}},We=x=>{b(x),$(!0)},Ye=x=>{B({...x}),J(!0)},$e=async()=>{if(!(!v||!v.order_id))try{const x={};v.status!==void 0&&(x.order_status=v.status),v.buyer_id!==void 0&&(x.buyer_id=v.buyer_id),v.amount!==void 0&&(x.amount=v.amount),v.receiver_name!==void 0&&(x.receiver_name=v.receiver_name),v.receiver_phone!==void 0&&(x.receiver_phone=v.receiver_phone),v.receiver_address!==void 0&&(x.receiver_address=v.receiver_address),v.item_id!==void 0&&(x.item_id=v.item_id),v.quantity!==void 0&&(x.quantity=v.quantity),v.item_title!==void 0&&(x.item_title=v.item_title),await dl(v.order_id,x),J(!1),B(null),ce()}catch(x){console.error("更新订单失败:",x),alert("更新失败,请重试")}},ss=async()=>{if(re){_(!0);try{const x=new FormData;x.append("file",re);const P=xr(await hl(x));q(P),E(null),await ce(),P.failed_count===0&&(Q(!1),q(null),alert(`订单导入成功,共 ${P.success_count} 条`))}catch(x){alert((x==null?void 0:x.message)||"导入失败,请检查文件格式")}finally{_(!1)}}},Ze=()=>{d||(Q(!1),E(null),q(null))},Xe=async x=>{Z(x);try{const P=await ul(x);P.success?await ce():alert(P.message||"同步失败")}catch(P){console.error("同步订单失败:",P),alert((P==null?void 0:P.message)||"同步失败,请重试")}finally{Z(null)}},He=async x=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){Ne(x);try{await xl(x),s.length===1&&oe>1?ee(P=>P-1):await ce()}catch(P){console.error("删除订单失败:",P),alert((P==null?void 0:P.message)||"删除失败,请重试"),await ce()}finally{Ne(null)}}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:ce,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(qe,{className:`w-5 h-5 ${le?"animate-spin":""}`})}),e.jsxs("button",{onClick:()=>{q(null),Q(!0)},className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(Qe,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:Be,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(ot,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-[#FAFAFA]",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:[{k:"all",v:"全部"},{k:"processing",v:"处理中"},{k:"shipped",v:"已发货"},{k:"pending_ship",v:"待发货"},{k:"completed",v:"已完成"},{k:"cancelled",v:"已取消"},{k:"refunding",v:"退款中"}].map(x=>e.jsx("button",{onClick:()=>{I(x.k),ee(1),X("")},className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${g===x.k?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:x.v},x.k))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ns,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:j,onChange:x=>{G(x.target.value),ee(1)},className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),h.map(x=>e.jsx("option",{value:x.id,children:Ae(x.id)},x.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(qt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0094f7] transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:Y,onChange:x=>{X(x.target.value),ee(1)},className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(x=>e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:x.item_image?e.jsx("img",{src:x.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Ns,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:_e(x.cookie_id,x.item_id,x.item_title)}),e.jsxs("div",{className:"mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:Le(x.cookie_id),children:[e.jsx(ns,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:Le(x.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",x.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",x.quantity," • ",Qs(x.created_at)]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:x.buyer_id}),x.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:x.receiver_name})]}),x.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:x.receiver_phone})]}),x.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:x.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:x.amount?`¥${x.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(wt,{status:x.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[x.status==="pending_ship"&&e.jsx("button",{onClick:()=>Ie(x.order_id),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${x.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(Mt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>We(x),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(es,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Ye(x),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Xe(x.order_id),disabled:te===x.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(qe,{className:`w-4 h-4 ${te===x.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>He(x.order_id),disabled:pe===x.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(Je,{className:"w-4 h-4"})})]})]},x.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",oe," 页 / 共 ",xe," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:oe<=1,onClick:()=>ee(x=>x-1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(pa,{className:"w-5 h-5"})}),e.jsx("button",{disabled:oe>=xe,onClick:()=>ee(x=>x+1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(ha,{className:"w-5 h-5"})})]})]})]}),N&&A&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:()=>$(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:A.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"所属账号"}),e.jsx("div",{className:"truncate whitespace-nowrap text-sm font-bold text-blue-700",title:Le(A.cookie_id),children:Le(A.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(wt,{status:A.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:A.amount?`¥${A.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:A.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:Qs(A.created_at)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[A.item_image&&e.jsx("img",{src:A.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:_e(A.cookie_id,A.item_id,A.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",A.item_id]}),A.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",A.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:A.buyer_id})]}),A.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:A.receiver_name})]}),A.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:A.receiver_phone})]}),A.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:A.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>$(!1),className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),A.status==="pending_ship"&&e.jsx("button",{onClick:()=>{$(!1),Ie(A.order_id)},className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),ue&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:Ze,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:x=>{var P;return E(((P=x.target.files)==null?void 0:P[0])||null)},className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),re&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:re.name})]})}),i&&i.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",i.success_count," 条,失败 ",i.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:mr(i).map((x,P)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:x.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:x.message||"导入失败"})]},`${x.order_id}-${P}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Ze,disabled:d,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:ss,disabled:!re||d,className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:d?"正在导入…":"导入订单"})]})})]})}),document.body),H&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),e.jsx("button",{onClick:()=>{m(!1),z(null)},className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:()=>Me("status_only"),disabled:S,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(ot,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:()=>Me("full_delivery"),disabled:S,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-[#0094f7] hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(Ns,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),S&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(qe,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),se&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${se.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[se.success?"✓ ":"✗ ",se.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:()=>{m(!1),z(null)},className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:se!=null&&se.success?"完成":"取消"})})]})}),document.body),T&&v&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:()=>J(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:v.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:v.status,onChange:x=>B({...v,status:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:v.buyer_id,onChange:x=>B({...v,buyer_id:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:v.amount,onChange:x=>B({...v,amount:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:v.receiver_name||"",onChange:x=>B({...v,receiver_name:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:v.receiver_phone||"",onChange:x=>B({...v,receiver_phone:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:v.receiver_address||"",onChange:x=>B({...v,receiver_address:x.target.value}),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:v.item_title||"",onChange:x=>B({...v,item_title:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>J(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:$e,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},pr=(s,t,l)=>{const c=l.trim().toLocaleLowerCase();return s.filter(h=>(!t||h.type===t)&&(!c||h.name.toLocaleLowerCase().includes(c)))},kt=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),hr=()=>{const[s,t]=n.useState([]),[l,c]=n.useState(!1),[h,f]=n.useState(!1),[L,F]=n.useState(null),[g,I]=n.useState({}),[j,G]=n.useState(kt),[Y,X]=n.useState(!1),[de,C]=n.useState("create"),[M,oe]=n.useState(null),[ee,xe]=n.useState(null),[O,le]=n.useState(!1),[D,N]=n.useState(""),[$,T]=n.useState(""),[J,ue]=n.useState(null),[Q,A]=n.useState(""),[b,v]=n.useState("");n.useEffect(()=>{Ve().then(t)},[]);const B=({type:i})=>{switch(i){case"text":return e.jsx(ct,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(dt,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(ja,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(zs,{className:"w-5 h-5 text-gray-500"})}},R=i=>{var q,d,_,te,Z;F(i),I({id:i.id,name:i.name||"",type:i.type||"text",api_url:((q=i.api_config)==null?void 0:q.url)||"",api_method:((d=i.api_config)==null?void 0:d.method)||"GET",api_timeout:((_=i.api_config)==null?void 0:_.timeout)||10,api_headers:((te=i.api_config)==null?void 0:te.headers)||"",api_params:((Z=i.api_config)==null?void 0:Z.params)||"",text_content:i.text_content||"",data_content:i.data_content||"",image_url:i.image_url||"",delay_seconds:i.delay_seconds||0,description:i.description||"",enabled:i.enabled}),c(!0)},K=async()=>{var i,q,d,_,te,Z,pe,Ne;if(L){if(!((i=g.name)!=null&&i.trim())){alert("请输入卡密名称");return}if(!g.type){alert("请选择卡密类型");return}try{const ce={name:g.name.trim(),type:g.type,description:(q=g.description)==null?void 0:q.trim(),delay_seconds:g.delay_seconds||0,enabled:g.enabled??!0};g.type==="api"?ce.api_config={url:((d=g.api_url)==null?void 0:d.trim())||"",method:g.api_method,timeout:g.api_timeout||10,headers:((_=g.api_headers)==null?void 0:_.trim())||void 0,params:((te=g.api_params)==null?void 0:te.trim())||void 0}:g.type==="text"?ce.text_content=((Z=g.text_content)==null?void 0:Z.trim())||"":g.type==="data"?ce.data_content=((pe=g.data_content)==null?void 0:pe.trim())||"":g.type==="image"&&(ce.image_url=((Ne=g.image_url)==null?void 0:Ne.trim())||""),await ft(L.id,ce),c(!1),Ve().then(t)}catch(ce){console.error("更新卡密失败:",ce),alert("更新失败,请重试")}}},H=async i=>{if(confirm("确认删除该卡密吗?"))try{await jl(i),Ve().then(t)}catch(q){console.error("删除卡密失败:",q),alert("删除失败,请重试")}},m=async()=>{if(!j.name.trim()){alert("请输入卡密名称");return}if(!j.content.trim()){alert(j.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const i={name:j.name.trim(),type:j.type,description:j.description.trim(),enabled:j.enabled,delay_seconds:j.delay_seconds};j.type==="text"&&(i.text_content=j.content.trim()),j.type==="data"&&(i.data_content=j.content.trim()),j.type==="image"&&(i.image_url=j.content.trim()),j.type==="api"&&(i.api_config={url:j.content.trim(),method:j.api_method,timeout:j.api_timeout,headers:j.api_headers.trim()||void 0,params:j.api_params.trim()||void 0}),await yl(i),f(!1),G(kt()),Ve().then(t)}catch(i){console.error("添加卡密失败:",i),alert("添加失败,请重试")}},p=async i=>{try{await ft(i.id,{...i,enabled:!i.enabled}),Ve().then(t)}catch(q){console.error("切换状态失败:",q)}},y=async i=>{try{await navigator.clipboard.writeText(String(i)),alert(`已复制卡密组ID:${i}`)}catch{prompt("复制卡密组ID",String(i))}},S=s.filter(i=>i.type==="data"),U=n.useMemo(()=>pr(s,Q,b),[s,b,Q]),se=()=>{const d=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 +VIP-MONTH-002 +VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(pe=>pe.map(Ne=>`"${String(Ne).replace(/"/g,'""')}"`).join(",")).join(` +`),_=new Blob(["\uFEFF"+d],{type:"text/csv;charset=utf-8"}),te=URL.createObjectURL(_),Z=document.createElement("a");Z.href=te,Z.download="卡密组批量导入模板.csv",document.body.appendChild(Z),Z.click(),Z.remove(),URL.revokeObjectURL(te)},z=async()=>{if(M){le(!0),xe(null);try{const i=await Nl(M);if(xe(i),i.created>0){const q=await Ve();t(q)}}catch(i){xe({error:(i==null?void 0:i.message)||"上传失败"})}finally{le(!1)}}},re=async()=>{if(!(!D||!$.trim())){le(!0),ue(null);try{const i=await vl(D,$);ue({added:i.added}),T("");const q=await Ve();t(q)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{le(!1)}}},E=()=>{var i;C("create"),oe(null),xe(null),N((i=S[0])!=null&&i.id?String(S[0].id):""),T(""),ue(null),X(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:E,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(js,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>f(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Qe,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ga,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:Q,onChange:i=>A(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(qt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:b,onChange:i=>v(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",U.length," / ",s.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:U.map(i=>{let q="";return i.type==="data"&&i.data_content?q=`库存: ${i.data_content.split(` +`).filter(_=>_.trim()).length} 条`:i.type==="text"&&i.text_content?q=i.text_content:i.type==="api"&&i.api_config?q=i.api_config.url:i.type==="image"&&i.image_url&&(q="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(B,{type:i.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:i.name,children:i.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>y(i.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:i.id}),e.jsx(ba,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:q,children:q})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>p(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>R(i),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>H(i.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Je,{className:"h-4 w-4"})})]})})]},i.id)})})]})}),U.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Dt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:s.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&L&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>c(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:i=>I({...g,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:i=>I({...g,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(L==null?void 0:L.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:i=>I({...g,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:g.api_method||"GET",onChange:i=>I({...g,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"超时时间(秒)"}),e.jsx("input",{type:"number",value:g.api_timeout||10,onChange:i=>I({...g,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:g.api_headers||"",onChange:i=>I({...g,api_headers:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"Authorization": "Bearer token"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:g.api_params||"",onChange:i=>I({...g,api_params:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"type": "card", "count": 1}'})]})]}),g.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:g.text_content||"",onChange:i=>I({...g,text_content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),g.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:g.data_content||"",onChange:i=>I({...g,data_content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个: +卡号1:密码1 +卡号2:密码2 +或者 +兑换码1 +兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(` +`).filter(i=>i.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:i=>I({...g,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:i=>I({...g,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:i=>I({...g,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>I({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>c(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:K,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),h&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>f(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:j.name,onChange:i=>G({...j,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(zs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(ct,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(dt,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:j.type==="data"?"库存内容(一行一个)":j.type==="text"?"固定回复内容":j.type==="image"?"图片 URL":"API 地址"}),j.type==="api"?e.jsx("input",{type:"url",value:j.content,onChange:i=>G({...j,content:i.target.value}),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):j.type==="image"?e.jsx("input",{type:"url",value:j.content,onChange:i=>G({...j,content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}):e.jsx("textarea",{value:j.content,onChange:i=>G({...j,content:i.target.value}),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${j.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:j.type==="data"?`CODE-123456 +CODE-789012 +...`:"请输入每次发货时发送的固定文字"}),j.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:j.content.split(` +`).filter(i=>i.trim()).length})," 条"]})]}),j.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:j.api_method,onChange:i=>G({...j,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:j.api_timeout,onChange:i=>G({...j,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:j.api_headers,onChange:i=>G({...j,api_headers:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:j.api_params,onChange:i=>G({...j,api_params:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:j.description,onChange:i=>G({...j,description:i.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:j.delay_seconds,onChange:i=>G({...j,delay_seconds:parseInt(i.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>f(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:m,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),Y&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>X(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>C("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${de==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(fa,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>C("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${de==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(js,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),de==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:se,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(ya,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx(js,{className:"w-4 h-4"}),M?M.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:i=>{var q;return oe(((q=i.target.files)==null?void 0:q[0])||null)}})]})]}),ee&&!ee.error&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",ee.total," 行 · 成功 ",ee.created," · 失败 ",ee.failed]}),ee.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:ee.rows.filter(i=>!i.success).map(i=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",i.row_no," 行「",i.name,"」:",i.error]},i.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:S.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:D,onChange:i=>N(i.target.value),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:S.map(i=>e.jsxs("option",{value:String(i.id),children:[i.name,"(ID: ",i.id,")"]},i.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{value:$,onChange:i=>T(i.target.value),placeholder:`VIP-001 +VIP-002 +VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),J&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",J.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>X(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),de==="create"?e.jsxs("button",{onClick:z,disabled:!M||O,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[O?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(js,{className:"w-4 h-4"}),O?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:re,disabled:!D||!$.trim()||O||S.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[O?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Qe,{className:"w-4 h-4"}),O?"处理中...":"追加卡密"]})]})]})}),document.body)]})},gr=s=>s.find(t=>t.status==="running"||t.status==="canceling"),br=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},fr=({onConfigureDelivery:s})=>{const[t,l]=n.useState([]),[c,h]=n.useState([]),[f,L]=n.useState([]),[F,g]=n.useState(""),[I,j]=n.useState(""),[G,Y]=n.useState(!1),[X,de]=n.useState(!1),[C,M]=n.useState(!1),[oe,ee]=n.useState(!1),[xe,O]=n.useState(!1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState("upload"),[ue,Q]=n.useState(null),[A,b]=n.useState(null),[v,B]=n.useState(null),[R,K]=n.useState(null),[H,m]=n.useState(null),p=n.useRef(!1),[y,S]=n.useState(null),[U,se]=n.useState({}),[z,re]=n.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[E,i]=n.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[q,d]=n.useState([]);n.useEffect(()=>{if(!le||E.images.length===0){d([]);return}const r=E.images.map((a,u)=>({key:a.name+u,url:URL.createObjectURL(a)}));return d(r),()=>{r.forEach(a=>URL.revokeObjectURL(a.url))}},[le,E.images]);const _=async()=>{const r=await ps();l(r)},te=async()=>{h(await Is())};n.useEffect(()=>{Promise.all([Rs(),ps(),Is(),yt(20)]).then(([r,a,u,w])=>{L(r),l(a),h(u);const W=w.find(ae=>["running","canceling"].includes(ae.status))||w.find(ae=>ae.status!=="preview");m(W||null)}).catch(r=>console.error("加载商品配置失败:",r))},[]),n.useEffect(()=>{if(!N||!(R!=null&&R.id)||!["running","canceling"].includes(R.status))return;const r=window.setInterval(async()=>{if(!p.current){p.current=!0;try{const a=await os(R.id);K(a),m(a),["running","canceling"].includes(a.status)||(J("done"),await _(),await te())}catch(a){console.error("刷新批量铺货进度失败:",a)}finally{p.current=!1}}},3e3);return()=>{window.clearInterval(r)}},[N,R==null?void 0:R.id,R==null?void 0:R.status]);const Z=async()=>{if(!F)return alert("请先选择账号");Y(!0);try{const r=await _l(F);await _(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{Y(!1)}},pe=r=>{S(r),se({...r}),ee(!0)},Ne=async()=>{if(y)try{await Rl(y.cookie_id,y.item_id,{item_title:U.item_title||"",item_description:U.item_description||"",item_category:U.item_category||"",item_price:U.item_price||"",item_detail:U.item_detail||y.item_detail||""}),await _(),await te(),ee(!1),S(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},ce=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await wl(r.cookie_id,r.item_id),l(a=>a.filter(u=>!(u.cookie_id===r.cookie_id&&u.item_id===r.item_id)))}catch(a){console.error("删除商品失败:",a),alert("删除失败,请重试")}},_e=async()=>{try{if(!z.cookie_id||!z.item_id){alert("请选择账号并填写商品ID");return}await kl(z.cookie_id,{item_id:z.item_id,item_title:z.item_title,item_price:z.item_price,item_detail:z.item_image?JSON.stringify({item_image:z.item_image}):""}),await _(),O(!1),re({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},Re=async()=>{if(!E.cookie_id)return alert("请选择发布账号");if(!E.title.trim())return alert("请填写商品标题");if(!E.price.trim())return alert("请填写商品价格");if(!E.quantity||Number(E.quantity)<=0)return alert("库存数量必须大于 0");if(E.images.length===0)return alert("至少上传 1 张商品图片");if(E.postage_mode==="fixed"&&!E.postage.trim())return alert("请填写一口价邮费");de(!0);try{const r=await Cl(E);if(await _(),D(!1),i({cookie_id:F||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),r!=null&&r.item_id){const a={id:r.item_id,cookie_id:E.cookie_id,item_id:r.item_id,item_title:r.item_title||E.title,item_price:r.item_price||E.price,item_image:r.item_image};s(a),alert("商品发布成功,ID: "+r.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(r){console.error("发布商品失败:",r);const a=r==null?void 0:r.payload;if((a==null?void 0:a.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((r==null?void 0:r.message)||"发布失败,请重试")}finally{de(!1)}},ye=async()=>{J("upload"),B(null),K(null),Q(null),b(null),$(!0),M(!0);try{const r=await yt(20),a=gr(r);if(a!=null&&a.id){const u=await os(a.id);m(u),K(u),J(["running","canceling"].includes(u.status)?"running":"done")}}catch(r){console.error("恢复最近批量铺货任务失败:",r)}finally{M(!1)}},Ae=async()=>{if(H!=null&&H.id){M(!0),$(!0);try{const r=await os(H.id);K(r),J(["running","canceling"].includes(r.status)?"running":"done")}catch(r){console.error("加载最近批量铺货结果失败:",r)}finally{M(!1)}}},Le=async()=>{if(!ue)return alert("请先上传商品表格");if(!F)return alert("请先选择默认发布账号");M(!0);try{const r=await Sl({file:ue,imagesZip:A,defaultCookieId:F});B(r),K(null),J("preview")}catch(r){console.error("批量铺货预检失败:",r),alert((r==null?void 0:r.message)||"预检失败,请检查表格和图片 zip")}finally{M(!1)}},Be=async()=>{if(v!=null&&v.preview_id){if(v.valid<=0)return alert("没有可发布的商品行");M(!0);try{const r=await Ll(v.preview_id),a=await os(r.batch_id||v.preview_id);K(a),m(a),J(a.status==="running"?"running":"done")}catch(r){console.error("启动批量铺货失败:",r),alert((r==null?void 0:r.message)||"启动发布任务失败")}finally{M(!1)}}},Ie=async()=>{if(R!=null&&R.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){M(!0);try{const r=await Il(R.id),a=await os(R.id);K(a),J((r==null?void 0:r.status)==="canceling"||a.status==="canceling"?"running":"done")}catch(r){alert((r==null?void 0:r.message)||"取消失败")}finally{M(!1)}}},Me=async()=>{const r=v==null?void 0:v.preview_id;if(r&&T==="preview")try{await Al(r)}catch(a){console.error("清理批量铺货预检失败:",a)}B(null),J("upload")},We=async()=>{await Me(),$(!1)},Ye=async()=>{if(R!=null&&R.id){M(!0);try{await $l(R.id),K(await os(R.id)),J("running")}catch(r){alert((r==null?void 0:r.message)||"重试失败")}finally{M(!1)}}},$e=()=>{const u=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","否","","否","","否","","",""]]].map(ve=>ve.map(he=>`"${String(he).replace(/"/g,'""')}"`).join(",")).join(` +`),w=new Blob(["\uFEFF"+u],{type:"text/csv;charset=utf-8"}),W=URL.createObjectURL(w),ae=document.createElement("a");ae.href=W,ae.download="批量铺货模板.csv",document.body.appendChild(ae),ae.click(),ae.remove(),URL.revokeObjectURL(W)},ss=()=>{re(r=>({...r,cookie_id:F||r.cookie_id})),O(!0)},Ze=()=>{i(r=>({...r,cookie_id:F||r.cookie_id})),D(!0)},Xe=r=>c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id).length>0?c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id):c.filter(a=>a.cookie_id===r.cookie_id&&!a.item_id),He=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},x=r=>{switch(r){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},P=n.useMemo(()=>new Map(f.map(r=>[r.id,r])),[f]),me=n.useMemo(()=>I?t.filter(r=>r.cookie_id===I):t,[I,t]),fe=r=>{const a=P.get(r),u=(a==null?void 0:a.remark)||(a==null?void 0:a.nickname);return u?`${u} · ${r.slice(0,6)}`:`账号 ${r.slice(0,8)}`},ze=r=>{const a=P.get(r);return(a==null?void 0:a.remark)||(a==null?void 0:a.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Na,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:r=>j(r.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(ns,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:F,onChange:r=>g(r.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]})]}),e.jsxs("button",{onClick:Z,disabled:G||!F,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${G?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ss,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Qe,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:Ze,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Ts,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void ye(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(_s,{className:"w-4 h-4"}),H&&["running","canceling"].includes(H.status)?"继续批量任务":"批量铺货"]}),H&&!["running","canceling"].includes(H.status)&&e.jsx("button",{onClick:()=>void Ae(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[me.map(r=>{const a=Xe(r),u=a.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:()=>pe(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:e.jsx(us,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>ce(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(Je,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[r.item_image?e.jsx("img",{src:r.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Et,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:br(r.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:r.item_title}),e.jsxs("div",{className:"mb-2 inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:ze(r.cookie_id),children:[e.jsx(ns,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:ze(r.cookie_id)})]}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",r.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${u?"text-emerald-600":"text-amber-600"}`,children:[u?e.jsx(Bt,{className:"w-3 h-3"}):e.jsx(va,{className:"w-3 h-3"}),u?`${a.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>s(r),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${u?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_a,{className:"w-3.5 h-3.5"}),u?"查看发货规则":"关联发货规则"]}),e.jsx(Ws,{className:"w-3.5 h-3.5"})]})})]},`${r.cookie_id}-${r.item_id}`)}),me.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(Tt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),I?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),oe&&y&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"560px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"编辑商品"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["ID: ",y.item_id]})]}),e.jsx("button",{onClick:()=>ee(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"商品标题",value:U.item_title||"",onChange:r=>se({...U,item_title:r.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:U.item_price||"",onChange:r=>se({...U,item_price:r.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:U.item_category||"",onChange:r=>se({...U,item_category:r.target.value})}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:U.item_description||"",onChange:r=>se({...U,item_description:r.target.value})})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:Ne,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),xe&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"720px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"添加商品"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"手动建立商品与自动发货规则的关联"})]}),e.jsx("button",{onClick:()=>O(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"所属账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:z.cookie_id,onChange:r=>re({...z,cookie_id:r.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品 ID"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入闲鱼商品 ID",value:z.item_id,onChange:r=>re({...z,item_id:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品价格"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 99.00",value:z.item_price,onChange:r=>re({...z,item_price:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入商品标题",value:z.item_title,onChange:r=>re({...z,item_title:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"图片 URL"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://...",value:z.item_image,onChange:r=>re({...z,item_image:r.target.value})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:_e,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),le&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"820px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"发布商品到闲鱼"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。"})]}),e.jsx("button",{onClick:()=>D(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 leading-6",children:"发布时必须填写库存。若账号没有库存发布能力,后端会返回明确的“库存权限不足”错误,不会误报为普通发布失败。"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:E.cookie_id,onChange:r=>i({...E,cookie_id:r.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:会员月卡自动发货",value:E.title,onChange:r=>i({...E,title:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"库存数量"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",type:"number",min:"1",placeholder:"必须大于 0",value:E.quantity,onChange:r=>i({...E,quantity:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品描述"}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述会用于自动识别类目;留空时使用标题",value:E.description,onChange:r=>i({...E,description:r.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"售价"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"99.00",value:E.price,onChange:r=>i({...E,price:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"原价(可选)"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"129.00",value:E.original_price,onChange:r=>i({...E,original_price:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"运费方式"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:E.postage_mode,onChange:r=>i({...E,postage_mode:r.target.value}),children:[e.jsx("option",{value:"free",children:"包邮"}),e.jsx("option",{value:"distance",children:"按距离计费"}),e.jsx("option",{value:"fixed",children:"一口价邮费"}),e.jsx("option",{value:"none",children:"无需邮寄"})]})]})]}),E.postage_mode==="fixed"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"一口价邮费"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 8.00",value:E.postage,onChange:r=>i({...E,postage:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品图片(1-9 张)"}),e.jsxs("label",{className:"flex min-h-[120px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50/50 transition-colors",children:[e.jsx(_s,{className:"w-8 h-8 text-emerald-600 mb-2"}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"选择图片"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:E.images.length?"已选择 "+E.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:r=>i({...E,images:Array.from(r.target.files||[]).slice(0,9)})})]}),q.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:q.map(r=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:r.url,alt:"",className:"w-full h-full object-cover"})},r.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:X,onClick:Re,className:"w-full bg-emerald-600 hover:bg-emerald-700 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ts,{className:"w-4 h-4"}),X?"正在发布...":"发布到闲鱼"]})})]})}),document.body),N&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"980px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量铺货"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。"})]}),e.jsx("button",{onClick:()=>void We(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]].map(([r,a])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${T===r?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:a},r))}),T==="upload"&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900 leading-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:"先下载模板,再按字段填写。"}),e.jsxs("div",{children:["图片字段写 zip 内相对路径,多个图片用英文分号分隔,例如 ",e.jsx("span",{className:"font-mono font-bold",children:"images/a.jpg;images/b.jpg"}),"。也支持直接填写图片 URL。"]})]}),e.jsx("button",{type:"button",onClick:$e,className:"shrink-0 rounded-xl bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700",children:"下载CSV模板"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"默认发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:F,onChange:r=>g(r.target.value),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors",children:[e.jsx(_s,{className:"w-9 h-9 text-blue-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传商品表格"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:ue?ue.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:r=>{var a;return Q(((a=r.target.files)==null?void 0:a[0])||null)}})]}),e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors",children:[e.jsx(_s,{className:"w-9 h-9 text-emerald-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传图片 zip(可选)"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:A?A.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:r=>{var a;return b(((a=r.target.files)==null?void 0:a[0])||null)}})]})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"字段说明"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。"})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950",children:[e.jsx("div",{className:"text-sm font-extrabold",children:"“付款后发送的卡密”怎么填"}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101"}),e.jsx("p",{className:"mt-1 leading-5",children:"从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:2"}),e.jsx("p",{className:"mt-1 leading-5",children:"每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:1:0;102:2:3"}),e.jsx("p",{className:"mt-1 leading-5",children:"先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。"})]})]}),e.jsxs("p",{className:"mt-3 leading-5 text-blue-800",children:["每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 ",e.jsx("code",{className:"font-bold",children:";"})," 隔开。"]})]}),e.jsx("div",{className:"overflow-x-auto rounded-xl border border-gray-100 bg-white",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"字段"}),e.jsx("th",{className:"px-3 py-2",children:"什么时候填写"}),e.jsx("th",{className:"px-3 py-2",children:"填写方法"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 text-gray-700",children:[["账号ID","需要覆盖默认账号时填写","上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行"],["标题","每个商品都要填","填写买家能看到的商品标题"],["描述","可以留空","留空时会使用商品标题作为描述"],["价格","每个商品都要填","只填数字,例如 19.90"],["原价","可以留空","需要展示划线原价时填写,例如 29.90"],["库存","可以留空","留空按 1 件处理;填写时必须大于 0"],["邮费模式","可以留空","留空表示包邮;包邮填 free,固定邮费填 fixed"],["邮费","邮费模式填 fixed 时填写","只填数字,例如 8.00"],["图片","每个商品都要填","填写 zip 内图片路径或图片网址;多张图片用英文分号隔开"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([r,a,u])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:r}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${a==="每个商品都要填"?"text-red-600":a==="可以留空"?"text-gray-500":"text-amber-700"}`,children:a}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:u})]},r))})]})})]})]}),T==="preview"&&v&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总行数"}),e.jsx("div",{className:"text-2xl font-extrabold text-gray-900 mt-1",children:v.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"可发布"}),e.jsx("div",{className:"text-2xl font-extrabold text-emerald-700 mt-1",children:v.valid})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"有问题"}),e.jsx("div",{className:"text-2xl font-extrabold text-red-700 mt-1",children:v.invalid})]})]}),e.jsx("div",{className:"max-h-[380px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"价格/库存"}),e.jsx("th",{className:"px-4 py-3",children:"图片"}),e.jsx("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:v.rows.map(r=>{var a,u;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:r.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${r.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:r.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:r.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",r.price||"-"," / ",r.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((a=r.images)==null?void 0:a.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((u=r.errors)==null?void 0:u.join(";"))||"-"})]},r.row_no)})})]})})]}),(T==="running"||T==="done")&&R&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:`rounded-2xl p-4 border ${x(R.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:He(R.status)})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总数"}),e.jsx("div",{className:"text-xl font-extrabold text-gray-900 mt-1",children:R.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"成功"}),e.jsx("div",{className:"text-xl font-extrabold text-emerald-700 mt-1",children:R.success})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"失败"}),e.jsx("div",{className:"text-xl font-extrabold text-red-700 mt-1",children:R.failed})]}),e.jsxs("div",{className:"rounded-2xl bg-blue-50 p-4 border border-blue-100",children:[e.jsx("div",{className:"text-xs font-bold text-blue-700",children:"等待"}),e.jsx("div",{className:"text-xl font-extrabold text-blue-700 mt-1",children:R.pending})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"商品ID"}),e.jsx("th",{className:"px-4 py-3",children:"错误原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:R.rows.map(r=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:r.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${x(r.status)}`,children:He(r.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:r.title}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:r.item_url?e.jsx("a",{href:r.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:r.item_id}):r.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:r.error_message||"-"})]},r.id))})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[T==="upload"&&e.jsxs("button",{disabled:C||!ue||!F,onClick:Le,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${C?"animate-spin":""}`}),C?"正在预检...":"开始预检"]}),T==="preview"&&v&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:C,onClick:()=>void Me(),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"返回修改"}),e.jsxs("button",{disabled:C||v.valid<=0,onClick:Be,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Ts,{className:"w-4 h-4"}),C?"启动中...":`确认发布 ${v.valid} 个商品`]})]}),(T==="running"||T==="done")&&R&&e.jsxs("div",{className:"flex gap-3 w-full",children:[R.status==="running"?e.jsx("button",{disabled:C,onClick:Ie,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):R.status==="canceling"?e.jsx("button",{disabled:!0,className:"flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold",children:"正在保存远端结果并安全取消…"}):e.jsx("button",{onClick:()=>window.open(`/items/publish-batches/${R.id}/result.csv`,"_blank"),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"下载结果"}),R.retryable>0&&!["running","canceling"].includes(R.status)&&e.jsxs("button",{disabled:C,onClick:Ye,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(qe,{className:`w-4 h-4 ${C?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(R.status)&&e.jsx("button",{onClick:()=>{$(!1),_(),te()},className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"完成"})]})]})]})}),document.body)]})},Ct="https://dashscope.aliyuncs.com/compatible-mode/v1",yr=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],jr=new Set(["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),Nr=()=>{const[s,t]=n.useState(null),[l,c]=n.useState(!1),[h,f]=n.useState(""),[L,F]=n.useState(!1),[g,I]=n.useState([]),[j,G]=n.useState(!1),[Y,X]=n.useState(""),[de,C]=n.useState(!1),M=n.useRef(null),[oe,ee]=n.useState(!1),[xe,O]=n.useState(!1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState(!1),[ue,Q]=n.useState(null),[A,b]=n.useState({new_username:"",current_password:"",new_password:"",confirm_password:""});n.useEffect(()=>{B(),Gt().then(p=>{p.username&&b(y=>({...y,new_username:p.username||""}))}).catch(()=>{})},[]),n.useEffect(()=>{const p=y=>{var S;(S=M.current)!=null&&S.contains(y.target)||C(!1)};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[]);const v=async(p,y=!1)=>{const S=p||s,U=(S==null?void 0:S.ai_api_url)||(S==null?void 0:S.ai_base_url)||Ct;G(!0),X("");try{const se=await Vl(U,(S==null?void 0:S.ai_api_key)||"");I(se),C(y&&se.length>0),!(S!=null&&S.ai_model)&&se.length>0&&t(z=>z&&{...z,ai_model:se[0]})}catch(se){I([]),C(!1),X(se.message||"读取模型失败")}finally{G(!1)}},B=()=>{c(!0),f(""),Kt().then(p=>{t(p),v(p)}).catch(p=>{t(null),f(p.message||"加载配置失败")}).finally(()=>c(!1))},R=async()=>{if(s){F(!0);try{const p=Object.fromEntries(Object.entries(s).filter(([y,S])=>!jr.has(y)&&S!==void 0&&S!==null));await Yt(p),alert("系统配置已保存")}catch(p){alert("保存失败:"+p.message)}finally{F(!1)}}},K=async p=>{p.preventDefault(),Q(null);const y=A.new_username.trim();if(y.length<3){Q({type:"error",text:"用户名至少需要 3 个字符"});return}if(!A.current_password){Q({type:"error",text:"请输入当前密码确认身份"});return}if(A.new_password&&A.new_password.length<8){Q({type:"error",text:"新密码至少需要 8 个字符"});return}if(A.new_password!==A.confirm_password){Q({type:"error",text:"两次输入的新密码不一致"});return}J(!0);try{const S=await Ga({current_password:A.current_password,new_username:y,new_password:A.new_password||void 0});if(!S.success){Q({type:"error",text:S.message||"登录凭据更新失败"});return}Q({type:"success",text:S.message||"登录凭据已更新"}),window.setTimeout(()=>window.location.reload(),1400)}catch(S){Q({type:"error",text:S.message||"登录凭据更新失败"})}finally{J(!1)}};if(!s)return e.jsx("div",{className:"p-8 text-center text-gray-400",children:h||(l?"加载配置中...":"暂无配置")});const H=s.ai_model||"",m=g;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(Ys,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:B,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(qe,{className:"w-4 h-4"}),"刷新"]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(wa,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:p=>t({...s,log_level:p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:yr.map(p=>e.jsx("option",{value:p.value,children:p.label},p.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:p=>t({...s,log_format:p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:p=>t({...s,renewal_log_retention_days:parseInt(p.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-[#0094f7] text-white",children:e.jsx(Ft,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||Ct,onChange:p=>t({...s,ai_api_url:p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:oe?"text":"password",value:s.ai_api_key||"",onChange:p=>t({...s,ai_api_key:p.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:"sk-..."}),e.jsx("button",{type:"button",onClick:()=>ee(!oe),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:oe?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:M,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:H,onFocus:()=>g.length>0&&C(!0),onChange:p=>{t({...s,ai_model:p.target.value}),g.length>0&&C(!0)},onKeyDown:p=>{p.key==="Escape"&&C(!1),p.key==="ArrowDown"&&g.length>0&&C(!0)},className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:()=>g.length>0&&C(p=>!p),disabled:g.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(ka,{className:`w-4 h-4 transition-transform ${de?"rotate-180":""}`})}),de&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:m.length>0?m.map(p=>e.jsxs("button",{type:"button",onClick:()=>{t({...s,ai_model:p}),C(!1)},className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-[#0094f7] flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:p}),p===H&&e.jsx(Ge,{className:"w-4 h-4 shrink-0 text-[#0094f7]"})]},p)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:()=>v(void 0,!0),disabled:j,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(qe,{className:`w-4 h-4 ${j?"animate-spin":""}`}),"读取模型"]})]}),Y?e.jsx("p",{className:"text-xs text-red-500",children:Y}):e.jsx("p",{className:"text-xs text-gray-500",children:g.length>0?`已从当前 API 地址读取到 ${g.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(Vs,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:p=>t({...s,"captcha.remote_service_url":p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:xe?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:p=>t({...s,"captcha.remote_secret_key":p.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off"}),e.jsx("button",{type:"button",onClick:()=>O(!xe),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:xe?"隐藏秘钥":"显示秘钥",children:xe?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:p=>t({...s,"captcha.remote_pass_cookies":p.target.checked}),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(xt,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:K,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ca,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:A.new_username,onChange:p=>b({...A,new_username:p.target.value}),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:le?"text":"password",value:A.current_password,onChange:p=>b({...A,current_password:p.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:()=>D(!le),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:le?"隐藏密码":"显示密码",children:le?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:N?"text":"password",value:A.new_password,onChange:p=>b({...A,new_password:p.target.value}),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:()=>$(!N),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:N?"隐藏密码":"显示密码",children:N?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:N?"text":"password",value:A.confirm_password,onChange:p=>b({...A,confirm_password:p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),ue&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${ue.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(Vs,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:ue.text})]}),e.jsxs("button",{type:"submit",disabled:T||!A.new_username||!A.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(xt,{className:"w-4 h-4"}),T?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:R,disabled:L,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(Ke,{className:"w-6 h-6"}),L?"保存中...":"保存所有配置"]})})]})},qs=(s,t)=>s.allowed_resolutions.includes(t),vr=(s,t)=>({runs:s.runs.filter(l=>!t||l.cookie_id===t),pending_tasks:s.pending_tasks.filter(l=>!t||l.cookie_id===t)}),_r=s=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[s]||"自动化异常",wr=async s=>{const t=s.loadIssues().then(s.onIssues).catch(s.onIssuesError),l=await s.loadRules();s.onRules(l),await t},kr=(s,t,l,c,h,f)=>s!==t||l!==c?!1:(f(h),!0),ls={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:Ns},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:Sa},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:zt}},Bs=["order_paid","buyer_reviewed","review_missing_timeout"],Cr="亲,商品使用满意的话,麻烦给个评价,谢谢~",bs=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),Ht=s=>{if(!s)return{};try{const t=JSON.parse(s);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}},as=(s,t={})=>{const l=Ht(s);return JSON.stringify({after_shipped_hours:Number(l.after_shipped_hours||72),repeat_interval_hours:Number(l.repeat_interval_hours||24),max_attempts:Number(l.max_attempts||1),...t})},fs=(s,t)=>{var c;const l=((c=ls[s])==null?void 0:c.label)||"自动化规则";return t?`${l} - ${t}`:l},St=s=>{const t=(s||"").trim();return t?Object.values(ls).some(l=>t===l.label||t.startsWith(`${l.label} -`)):!0},ys=(s,t=0)=>{if(s==="review_missing_timeout")return[{action_type:"send_text",message_template:Cr,enabled:!0,sort_order:1}];const l={action_type:"send_card",card_id:t,delivery_count:1,enabled:!0,sort_order:1};return s==="order_paid"?[l,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[l]},Sr=s=>{var l,c;if(s.trigger_type==="review_missing_timeout")return((c=(l=s.actions)==null?void 0:l.find(h=>h.action_type==="send_text"))==null?void 0:c.message_template)||"发送求评价文案";const t=(s.actions||[]).filter(h=>h.action_type==="send_card");return t.length?t.map(h=>h.card_name||`卡密 ${h.card_id}`).join(" / "):"未配置卡密库存"},Lt=(s,t=!1)=>{const l={blue:t?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:t?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:t?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return l[s]||l.blue},Lr=s=>s?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Ss=s=>(s==null?void 0:s.nickname)||(s==null?void 0:s.remark)||(s==null?void 0:s.id)||"未知账号",Ar=s=>s===!0||s===1||s==="1",Ir=({initialDeliveryTarget:s,onDeliveryTargetHandled:t})=>{var fe,ze,r;const[l,c]=n.useState("automation"),[h,f]=n.useState([]),[L,F]=n.useState({runs:[],pending_tasks:[]}),[g,I]=n.useState([]),[j,G]=n.useState({}),[Y,X]=n.useState([]),[de,C]=n.useState([]),[M,oe]=n.useState([]),[ee,xe]=n.useState(!1),[O,le]=n.useState(""),D=n.useRef(0),N=n.useRef("");N.current=O;const[$,T]=n.useState(!1),[J,ue]=n.useState(!1),[Q,A]=n.useState(!1),[b,v]=n.useState(null),[B,R]=n.useState(null),[K,H]=n.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""});Y.find(a=>a.id===O);const m=n.useCallback(async()=>{const[a,u,w,W]=await Promise.all([Rs(),Ve(),ps(),vt()]);X(a),C(u),oe(w),G(W),le(ae=>{var ve;return ae||((ve=a[0])==null?void 0:ve.id)||""})},[]),p=n.useCallback(async()=>{await wr({loadRules:Is,loadIssues:El,onRules:f,onIssues:F,onIssuesError:a=>console.warn("加载自动化异常列表失败,不阻断规则展示",a)})},[]),y=n.useCallback(async()=>{const a=O;if(a!==N.current)return;const u=++D.current;if(I([]),!a)return;const w=await ql(a);kr(u,D.current,a,N.current,w,I)},[O]),S=n.useCallback(async()=>{G(await vt())},[]),U=n.useCallback(async()=>{xe(!0);try{l==="automation"?await p():l==="reply"?await y():await S()}finally{xe(!1)}},[l,p,S,y]);n.useEffect(()=>{m().catch(a=>console.error("加载规则参考数据失败",a))},[m]),n.useEffect(()=>{U().catch(a=>console.error("刷新规则页面失败",a))},[U]);const se=n.useMemo(()=>h.filter(a=>!O||a.cookie_id===O),[h,O]),z=n.useMemo(()=>vr(L,O),[L,O]),re=n.useMemo(()=>Y.filter(a=>!O||a.id===O),[Y,O]),E=n.useMemo(()=>{var u;const a={order_paid:[],buyer_reviewed:[],review_missing_timeout:[]};for(const w of se)(u=a[w.trigger_type])==null||u.push(w);return a},[se]),i=n.useMemo(()=>{const a=(b==null?void 0:b.cookie_id)||O;return M.filter(u=>u.cookie_id===a)},[b==null?void 0:b.cookie_id,M,O]),q=n.useMemo(()=>{if(!(!(b!=null&&b.cookie_id)||!(b!=null&&b.item_id)))return M.find(a=>a.cookie_id===b.cookie_id&&a.item_id===b.item_id)},[b==null?void 0:b.cookie_id,b==null?void 0:b.item_id,M]),d=Ar(q==null?void 0:q.is_multi_spec),_=(b==null?void 0:b.trigger_type)||"order_paid",te=ls[_],Z=Ht(b==null?void 0:b.config_json),pe=n.useCallback((a="order_paid",u=O,w="")=>{const W=M.find(ve=>ve.cookie_id===u&&ve.item_id===w),ae=(W==null?void 0:W.item_title)||w;return{name:fs(a,ae),trigger_type:a,cookie_id:u,item_id:w,item_title:(W==null?void 0:W.item_title)||"",item_keyword:ae,card_group_id:0,priority:100,enabled:!0,config_json:a==="review_missing_timeout"?as():"{}",actions:ys(a),variants:a==="review_missing_timeout"?[]:[bs()]}},[M,O]),Ne=n.useCallback(a=>{var w,W;const u=a.trigger_type||"order_paid";v({...a,trigger_type:u,config_json:u==="review_missing_timeout"?as(a.config_json):a.config_json||"{}",actions:(w=a.actions)!=null&&w.length?a.actions.map(ae=>({...ae})):ys(u,a.card_group_id),variants:(W=a.variants)!=null&&W.length?a.variants.map(ae=>({...ae})):u==="review_missing_timeout"?[]:[bs()]}),T(!0)},[]);n.useEffect(()=>{if(!s)return;let a=!1;return(async()=>{c("automation"),le(s.cookieId),xe(!0);try{const[w,W,ae]=await Promise.all([Is(),ps(),Ve().catch(he=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",he),[]))]);if(a)return;f(w),oe(W),C(ae);const ve=w.find(he=>he.cookie_id===s.cookieId&&he.item_id===s.itemId&&he.trigger_type==="order_paid");if(ve)Ne(ve);else{const he=W.find(De=>De.cookie_id===s.cookieId&&De.item_id===s.itemId);v({...pe("order_paid",s.cookieId,s.itemId),item_title:(he==null?void 0:he.item_title)||"",item_keyword:(he==null?void 0:he.item_title)||s.itemId,name:fs("order_paid",(he==null?void 0:he.item_title)||s.itemId)}),T(!0)}}catch(w){console.error("打开商品自动化规则失败",w),alert("无法加载该商品的自动化规则")}finally{a||(xe(!1),t==null||t())}})(),()=>{a=!0}},[pe,s,t,Ne]);const ce=(a="order_paid")=>{if(!O){alert("请先选择账号");return}v(pe(a)),T(!0)},_e=a=>{var W,ae,ve,he,De;if(!b)return;const u=((ae=(W=b.variants)==null?void 0:W.find(je=>je.card_id))==null?void 0:ae.card_id)||((he=(ve=b.actions)==null?void 0:ve.find(je=>je.action_type==="send_card"))==null?void 0:he.card_id)||b.card_group_id||0,w=(q==null?void 0:q.item_title)||b.item_title||b.item_id||"";v({...b,trigger_type:a,name:St(b.name)?fs(a,w):b.name,card_group_id:u,config_json:a==="review_missing_timeout"?as(b.config_json):"{}",actions:ys(a,u),variants:a==="review_missing_timeout"?[]:(De=b.variants)!=null&&De.length?b.variants:[{...bs(),card_id:u}]})},Re=a=>{if(!b)return;const u=M.find(W=>W.cookie_id===(b.cookie_id||O)&&W.item_id===a),w=(u==null?void 0:u.item_title)||a;v({...b,item_id:a,item_title:(u==null?void 0:u.item_title)||"",item_keyword:w,name:St(b.name)?fs(_,w):b.name})},ye=(fe=b==null?void 0:b.variants)!=null&&fe.length?b.variants:[bs()],Ae=(a,u)=>{var W;if(!b)return;const w=ye.map((ae,ve)=>ve===a?{...ae,...u}:ae);v({...b,variants:w,card_group_id:((W=w[0])==null?void 0:W.card_id)||0})},Le=()=>{if(!b)return;const a=ye[ye.length-1];v({...b,variants:[...ye,{...bs(),spec_name:d&&(a==null?void 0:a.spec_name)||"",spec_value:d&&(a==null?void 0:a.spec_value)||""}]})},Be=async()=>{var W,ae,ve,he,De;if(!b)return;const a=b.trigger_type||"order_paid";if(!b.cookie_id){alert("请选择账号");return}const u=(W=b.variants)!=null&&W.length?b.variants:[];if(a!=="review_missing_timeout"){if(!u.length||u.some(je=>!je.card_id)){alert(a==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");return}if(d&&u.some(je=>!je.spec_name.trim()||!je.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}}if(a==="review_missing_timeout"&&!(((ve=(ae=b.actions)==null?void 0:ae.find(o=>o.action_type==="send_text"))==null?void 0:ve.message_template)||"").trim()){alert("请填写求评价文案");return}const w=a==="review_missing_timeout"?[]:u.map(je=>({...je,spec_name:d?je.spec_name.trim():"",spec_value:d?je.spec_value.trim():"",delivery_count:Math.max(1,Number(je.delivery_count)||1),enabled:je.enabled!==!1}));try{await jt({...b,trigger_type:a,name:(b.name||"").trim()||fs(a,(q==null?void 0:q.item_title)||b.item_id||""),config_json:a==="review_missing_timeout"?as(b.config_json):b.config_json||"{}",actions:(he=b.actions)!=null&&he.length?b.actions:ys(a,((De=w[0])==null?void 0:De.card_id)||b.card_group_id||0),variants:w}),T(!1),await Promise.all([p(),m()]),alert("保存成功")}catch(je){console.error("保存自动化规则失败:",je),alert("保存失败:"+je.message)}},Ie=async a=>{if(confirm("确定删除该自动化规则吗?"))try{await Tl(a),await p(),alert("删除成功")}catch(u){alert("删除失败:"+u.message)}},Me=async a=>{try{await jt({...a,enabled:!a.enabled}),await p()}catch(u){alert("操作失败:"+u.message)}},We=async(a,u)=>{if(confirm(u==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":u==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Fl(a,u),await p()}catch(W){alert("处理失败:"+W.message)}},Ye=async(a,u)=>{if(confirm(u==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Dl(a,u),await p()}catch(w){alert("处理失败:"+w.message)}},$e=()=>{if(!O){alert("请先选择账号");return}R({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),ue(!0)},ss=async()=>{var u,w,W;if(!B||!O)return;const a=B.type==="image"?!!((u=B.image_url)!=null&&u.trim()):!!((w=B.reply_content)!=null&&w.trim());if(!((W=B.keyword)!=null&&W.trim())||!a){alert("请填写关键词和回复内容");return}try{await Bl({...B,match_type:"fuzzy",enabled:!0},O),ue(!1),await y(),alert("保存成功")}catch(ae){alert("保存失败:"+ae.message)}},Ze=async a=>{if(!(!O||!confirm("确定删除该回复规则吗?")))try{await zl(a,O),await y(),alert("删除成功")}catch(u){alert("删除失败:"+u.message)}},Xe=async(a=O)=>{if(!a){alert("请先选择账号");return}try{const u=await Zl(a);H({cookie_id:a,enabled:u.enabled,reply_content:u.reply_content,reply_once:u.reply_once,reply_image_url:u.reply_image_url||""})}catch{H({cookie_id:a,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}A(!0)},He=async()=>{if(!K.cookie_id){alert("请先选择账号");return}if(K.enabled&&!K.reply_content.trim()&&!K.reply_image_url.trim()){alert("启用默认回复时,请填写回复内容或图片 URL");return}try{await Xl(K.cookie_id,{enabled:K.enabled,reply_content:K.reply_content,reply_once:K.reply_once,reply_image_url:K.reply_image_url}),A(!1),await S(),alert("保存成功")}catch(a){alert("保存失败:"+a.message)}},x=async a=>{if(confirm("确定删除该账号默认回复吗?"))try{await Hl(a),await S(),alert("删除成功")}catch(u){alert("删除失败:"+u.message)}},P=async a=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await er(a),alert("清空成功")}catch(u){alert("清空失败:"+u.message)}},me=l==="automation"?"新建自动化":l==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("select",{value:O,onChange:a=>le(a.target.value),className:"ios-input px-4 py-3 rounded-2xl text-sm min-w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),Y.map(a=>e.jsx("option",{value:a.id,children:Ss(a)},a.id))]}),e.jsxs("button",{onClick:U,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 transition-colors",children:[e.jsx(qe,{className:`w-4 h-4 ${ee?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:l==="automation"?()=>ce("order_paid"):l==="reply"?$e:()=>void Xe(),disabled:!O,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Qe,{className:"w-4 h-4"}),me]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:Us},{id:"reply",label:"关键词回复",icon:Ls},{id:"default",label:"账号默认回复",icon:ds}].map(a=>{const u=a.icon;return e.jsxs("button",{onClick:()=>c(a.id),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${l===a.id?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(u,{className:"w-4 h-4"}),a.label]},a.id)})}),l==="automation"&&(z.runs.length>0||z.pending_tasks.length>0)&&e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ms,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[z.runs.map(a=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",a.cookie_id," · 订单 ",a.order_id||"-"," · 已记录发送 ",a.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:_r(a.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:a.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[qs(a,"continue")&&e.jsx("button",{onClick:()=>void We(a.id,"continue"),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),qs(a,"retry")&&e.jsx("button",{onClick:()=>void We(a.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),qs(a,"cancel")&&e.jsx("button",{onClick:()=>void We(a.id,"cancel"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${a.id}`)),z.pending_tasks.map(a=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",a.cookie_id," · 延迟任务重试已达 ",a.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:a.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>void Ye(a.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:()=>void Ye(a.id,"dismiss"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${a.id}`))]})]}),l==="automation"&&e.jsxs("div",{className:"grid grid-cols-1 2xl:grid-cols-[360px_1fr] gap-6",children:[e.jsxs("aside",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:Bs.map(a=>{const u=ls[a],w=u.icon;return e.jsx("button",{type:"button",onClick:()=>ce(a),className:`w-full text-left rounded-2xl border p-4 transition-colors ${Lt(u.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(w,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:u.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:u.description})]})]})},a)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-4",children:"规则概览"}),e.jsx("div",{className:"space-y-3",children:Bs.map(a=>{const u=ls[a],w=u.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(w,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:u.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:E[a].length})]},a)})})]})]}),e.jsx("section",{className:"space-y-4",children:se.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(Us,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"从左侧选择一个模板开始配置。"})]}):se.map(a=>{const u=ls[a.trigger_type],w=u.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${Lt(u.accent,!0)}`,children:e.jsx(w,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:a.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Lr(a.enabled)}`,children:a.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:u.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:a.item_title||a.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:Sr(a)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:()=>Ne(a),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(us,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:()=>Me(a),className:`px-4 py-2 rounded-xl text-sm font-bold ${a.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:a.enabled?"禁用":"启用"}),e.jsx("button",{onClick:()=>Ie(a.id),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Je,{className:"w-4 h-4"})})]})]})},a.id)})})]}),l==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(ms,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[g.map(a=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",a.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:a.type==="image"&&a.image_url?a.image_url:a.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:()=>{R({...a}),ue(!0)},className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Ze(a.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Je,{className:"w-5 h-5"})})]})]},a.id)),g.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),l==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(ms,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[re.map(a=>{const u=j[a.id],w=!!(u!=null&&u.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${w?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${w?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(ds,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:Ss(a)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${w?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:w?"已启用":"未启用"}),(u==null?void 0:u.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:w?u.reply_content||u.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:()=>void Xe(a.id),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(us,{className:"w-4 h-4"})}),w&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>void P(a.id),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:()=>void x(a.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Je,{className:"w-5 h-5"})})]})]})]},a.id)}),re.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),$&&b&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:b.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:te.description})]}),e.jsx("button",{onClick:()=>T(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:Bs.map(a=>{const u=ls[a],w=u.icon,W=_===a;return e.jsx("button",{type:"button",onClick:()=>_e(a),className:`w-full rounded-2xl p-4 text-left border transition-all ${W?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(w,{className:`w-5 h-5 mt-0.5 ${W?"text-[#0094f7]":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:u.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${W?"text-gray-500":"text-gray-400"}`,children:u.description})]})]})},a)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:te.flow.map((a,u)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:u+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:a})]},a))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-[#F7F8FA]",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Bt,{className:"w-5 h-5 text-[#0094f7]"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:b.name||"",onChange:a=>v({...b,name:a.target.value}),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:b.cookie_id||"",onChange:a=>v({...b,cookie_id:a.target.value,item_id:"",item_title:"",item_keyword:""}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),Y.map(a=>e.jsx("option",{value:a.id,children:Ss(a)},a.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:b.item_id||"",onChange:a=>Re(a.target.value),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),i.map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]})]}),q&&_!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:q.item_title||q.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${d?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:d?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),_!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(La,{className:"w-5 h-5 text-[#0094f7]"}),e.jsx("h4",{className:"font-black text-gray-900",children:_==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:d?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:Le,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Qe,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:ye.map((a,u)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${d?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:a.spec_name,onChange:w=>Ae(u,{spec_name:w.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:a.spec_value,onChange:w=>Ae(u,{spec_value:w.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:a.card_id||"",onChange:w=>Ae(u,{card_id:Number(w.target.value)}),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),de.filter(w=>w.enabled&&w.type!=="api").map(w=>e.jsx("option",{value:w.id,children:w.name},w.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:a.delivery_count,onChange:w=>Ae(u,{delivery_count:Math.max(1,Number(w.target.value)||1)}),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:a.delay_override===!0,onChange:w=>Ae(u,{delay_override:w.target.checked}),className:"accent-[#0094f7]"}),"覆盖卡密默认延时"]}),a.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:a.delay_seconds||0,onChange:w=>Ae(u,{delay_seconds:Math.max(0,Number(w.target.value)||0)}),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:a.delay_override?`本动作延时 ${a.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:ye.length===1,onClick:()=>v({...b,variants:ye.filter((w,W)=>W!==u)}),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(Je,{className:"w-4 h-4"})})]},a.id||u))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(zt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(Z.after_shipped_hours||72),onChange:a=>v({...b,config_json:as(b.config_json,{after_shipped_hours:Math.max(1,Number(a.target.value)||72)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(Z.repeat_interval_hours||24),onChange:a=>v({...b,config_json:as(b.config_json,{repeat_interval_hours:Math.max(1,Number(a.target.value)||24)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(Z.max_attempts||1),onChange:a=>v({...b,config_json:as(b.config_json,{max_attempts:Math.max(1,Number(a.target.value)||1)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((r=(ze=b.actions)==null?void 0:ze.find(a=>a.action_type==="send_text"))==null?void 0:r.message_template)||"",onChange:a=>{var u;return v({...b,actions:((u=b.actions)!=null&&u.length?b.actions:ys("review_missing_timeout")).map(w=>w.action_type==="send_text"?{...w,message_template:a.target.value}:w)})},className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:b.priority||100,onChange:a=>v({...b,priority:Number(a.target.value)||100}),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:b.enabled!==!1,onChange:a=>v({...b,enabled:a.target.checked}),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:()=>T(!1),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:Be,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),J&&B&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:B.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:()=>ue(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:B.item_id||"",onChange:a=>R({...B,item_id:a.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),M.filter(a=>!O||a.cookie_id===O).map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:B.type||"text",onChange:a=>{const u=a.target.value;R({...B,type:u,reply_content:u==="text"?B.reply_content:"",image_url:u==="image"?B.image_url:""})},className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:B.keyword||"",onChange:a=>R({...B,keyword:a.target.value}),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),B.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:B.image_url||"",onChange:a=>R({...B,image_url:a.target.value}),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:B.reply_content||"",onChange:a=>R({...B,reply_content:a.target.value}),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:()=>ue(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ss,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Zs,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Q&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:()=>A(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:K.cookie_id,onChange:a=>H({...K,cookie_id:a.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),Y.map(a=>e.jsx("option",{value:a.id,children:Ss(a)},a.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:()=>H({...K,enabled:!K.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${K.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${K.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:K.reply_content,onChange:a=>H({...K,reply_content:a.target.value}),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:K.reply_image_url,onChange:a=>H({...K,reply_image_url:a.target.value}),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:K.reply_once,onChange:a=>H({...K,reply_once:a.target.checked}),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:()=>A(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:He,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})},$r=s=>{const t=String(s.smtp_from||"").trim(),l=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t);return{...s,smtp_from_name:s.smtp_from_name||(l?"":t),smtp_from_address:s.smtp_from_address||(l?t:s.smtp_user||""),smtp_use_tls:At(s.smtp_use_tls,!0),smtp_use_ssl:At(s.smtp_use_ssl,!1)}},At=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},Hs=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],Ks=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ea=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),l=Hs.some(c=>String(s[c]??"").trim()!=="");return{...s,use_custom_smtp:t?Ks(s.use_custom_smtp,!1):l}},It=(s,t)=>{const l={...s,use_custom_smtp:!0};for(const c of Hs)String(l[c]??"").trim()===""&&t[c]!==void 0&&(l[c]=t[c]);return l.smtp_port||(l.smtp_port=587),l.smtp_from_address||(l.smtp_from_address=l.smtp_user||""),l.smtp_use_tls=Ks(l.smtp_use_tls,!0),l.smtp_use_ssl=Ks(l.smtp_use_ssl,!1),l},Rr=s=>{const t=ea(s),l={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(l.use_custom_smtp)for(const c of Hs)l[c]=t[c];return l},cs={bark:{label:"Bark",icon:xs,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容","URL 路径里 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:Ls,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:Ls,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:Ls,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Aa,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:Zs,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:Ut,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},sa=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],Pr=s=>!s||s.length===0?"全部事件":s.map(l=>{var c;return((c=sa.find(h=>h.value===l))==null?void 0:c.label)||l}).join("、"),Tr=({isAdmin:s=!1})=>{const[t,l]=n.useState([]),[c,h]=n.useState(!0),[f,L]=n.useState(!1),[F,g]=n.useState(null),[I,j]=n.useState(!1),[G,Y]=n.useState(""),[X,de]=n.useState(null),[C,M]=n.useState({}),[oe,ee]=n.useState(!1),[xe,O]=n.useState(!1),[le,D]=n.useState(!1),[N,$]=n.useState({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),T=async()=>{h(!0);try{const m=await Xt();l(m.data||[])}catch(m){console.error("加载通知渠道失败",m)}finally{h(!1)}},J=async()=>{try{const m=await Kt();M($r(m||{}))}catch(m){console.error("加载 SMTP 配置失败",m)}},ue=async()=>{ee(!0);try{await Yt({smtp_server:C.smtp_server||"",smtp_port:C.smtp_port||587,smtp_user:C.smtp_user||"",smtp_password:C.smtp_password||"",smtp_from_name:C.smtp_from_name||"",smtp_from_address:C.smtp_from_address||C.smtp_user||"",smtp_use_tls:C.smtp_use_tls!==!1,smtp_use_ssl:C.smtp_use_ssl===!0}),Q("success","SMTP 配置已保存")}catch(m){Q("error",(m==null?void 0:m.message)||"保存失败")}finally{ee(!1)}};n.useEffect(()=>{T(),s?J():M({})},[s]);const Q=(m,p)=>{de({type:m,text:p}),window.setTimeout(()=>de(null),3e3)},A=()=>{g(null),$({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),D(!1),L(!0)},b=m=>{g(m);const p=m.type==="email"?ea({...m.config||{}}):null,y=p?p.use_custom_smtp===!0?It(p,C):p:{...m.config||{}};$({name:m.name,type:m.type,enabled:m.enabled,config:y,event_types:m.event_types||[]}),D(!1),L(!0)},v=async()=>{const m=cs[N.type];for(const y of m.fields)if(y.required&&!String(N.config[y.key]||"").trim()){Q("error",`请填写 ${y.label}`);return}if(!N.name.trim()){Q("error","请填写渠道名称");return}let p=N.config;if(N.type==="email"&&(p=Rr(N.config),p.use_custom_smtp)){const S=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([U])=>!String(p[U]||"").trim());if(S){Q("error",`请填写 ${S[1]}`);return}}j(!0);try{const y={name:N.name.trim(),type:N.type,config:p,event_types:N.event_types,enabled:N.enabled};F?await Nt(F.id,y):await Jl(y),L(!1),await T(),Q("success",F?"已更新":"已创建")}catch(y){console.error("保存失败",y),Q("error",(y==null?void 0:y.message)||"保存失败")}finally{j(!1)}},B=async m=>{if(confirm(`确认删除渠道「${m.name}」吗?已绑定该渠道的账号会自动解绑。`))try{await Ql(m.id),await T(),Q("success","已删除")}catch(p){Q("error",(p==null?void 0:p.message)||"删除失败")}},R=async m=>{try{await Nt(m.id,{enabled:!m.enabled}),l(p=>p.map(y=>y.id===m.id?{...y,enabled:!y.enabled}:y))}catch(p){Q("error",(p==null?void 0:p.message)||"切换失败")}},K=async m=>{Y(m.id);try{await Yl(m.id),Q("success","测试通知已发送,请检查对应渠道")}catch(p){Q("error",(p==null?void 0:p.message)||"发送失败")}finally{Y("")}},H=cs[N.type];return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:T,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(qe,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:A,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(xs,{className:"w-5 h-5 text-[#0094f7] mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),c?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Te,{className:"w-8 h-8 text-[#0094f7] animate-spin"})}):t.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(xs,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:t.map(m=>{const p=cs[m.type]||cs.webhook,y=p.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(y,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:m.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:p.label}),!m.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:p.fields.map(S=>{var U;return(U=m.config)==null?void 0:U[S.key]}).filter(Boolean).map((S,U)=>e.jsx("span",{className:"mr-3",children:String(S).length>40?String(S).slice(0,40)+"…":String(S)},U))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Pr(m.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:()=>R(m),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${m.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:m.enabled?"启用中":"已停用"}),e.jsxs("button",{onClick:()=>K(m),disabled:G===m.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-[#0094f7] hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[G===m.id?e.jsx(Te,{className:"w-3 h-3 animate-spin"}):e.jsx(Zs,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{onClick:()=>b(m),className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(Ot,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>B(m),className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(Je,{className:"w-4 h-4"})})]})]},m.id)})}),s&&e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(Ut,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 服务器"}),e.jsx("input",{type:"text",value:C.smtp_server||"",onChange:m=>M({...C,smtp_server:m.target.value}),placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:C.smtp_port||587,onChange:m=>M({...C,smtp_port:parseInt(m.target.value)||587}),placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{type:"email",value:C.smtp_user||"",onChange:m=>M({...C,smtp_user:m.target.value}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:xe?"text":"password",value:C.smtp_password||"",onChange:m=>M({...C,smtp_password:m.target.value}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>O(!xe),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:xe?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{type:"text",value:C.smtp_from_name||"",onChange:m=>M({...C,smtp_from_name:m.target.value}),placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{type:"email",value:C.smtp_from_address||C.smtp_user||"",onChange:m=>M({...C,smtp_from_address:m.target.value}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:C.smtp_use_tls!==!1,onChange:m=>M({...C,smtp_use_tls:m.target.checked,smtp_use_ssl:m.target.checked?!1:C.smtp_use_ssl})}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:C.smtp_use_ssl===!0,onChange:m=>M({...C,smtp_use_ssl:m.target.checked,smtp_use_tls:m.target.checked?!1:C.smtp_use_tls})}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:ue,disabled:oe,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[oe?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),oe?"保存中...":"保存 SMTP 配置"]})]}),f&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:F?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:()=>L(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:N.name,onChange:m=>$({...N,name:m.target.value}),placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys(cs).map(m=>{const p=cs[m],y=p.icon,S=N.type===m;return e.jsxs("button",{type:"button",onClick:()=>$({...N,type:m,config:{}}),className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${S?"border-[#0094f7] bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(y,{className:`w-5 h-5 ${S?"text-[#0094f7]":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${S?"text-[#0094f7]":"text-gray-600"}`,children:p.label})]},m)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",H.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:H.guide.steps.map((m,p)=>e.jsx("li",{children:m},p))}),H.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:H.guide.urlFormat})]}),H.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",H.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:H.fields.map(m=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[m.label,m.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{type:m.type==="password"?"password":m.type==="number"?"number":"text",value:String(N.config[m.key]||""),onChange:p=>$({...N,config:{...N.config,[m.key]:p.target.value}}),placeholder:m.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),m.help&&e.jsx("p",{className:"text-xs text-gray-500",children:m.help})]},m.key))}),N.type==="email"&&e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"SMTP 来源"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-gray-500",children:N.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:()=>{const m=N.config.use_custom_smtp===!0;$({...N,config:m?{...N.config,use_custom_smtp:!1}:It(N.config,C)})},className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${N.config.use_custom_smtp===!0?"bg-[#0094f7]":"bg-gray-300"}`,"aria-label":"使用独立 SMTP",children:e.jsx("span",{className:`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${N.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),N.config.use_custom_smtp===!0&&e.jsxs("div",{className:"space-y-4 border-t border-blue-100 bg-white/80 p-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 服务器 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:String(N.config.smtp_server||""),onChange:m=>$({...N,config:{...N.config,smtp_server:m.target.value}}),placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 端口 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"number",value:String(N.config.smtp_port||587),onChange:m=>$({...N,config:{...N.config,smtp_port:m.target.value}}),placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["登录邮箱 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"email",value:String(N.config.smtp_user||""),onChange:m=>$({...N,config:{...N.config,smtp_user:m.target.value}}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["密码 / 授权码 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:le?"text":"password",value:String(N.config.smtp_password||""),onChange:m=>$({...N,config:{...N.config,smtp_password:m.target.value}}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>D(m=>!m),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:le?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{type:"text",value:String(N.config.smtp_from_name||""),onChange:m=>$({...N,config:{...N.config,smtp_from_name:m.target.value}}),placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["发件邮箱地址 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"email",value:String(N.config.smtp_from_address||""),onChange:m=>$({...N,config:{...N.config,smtp_from_address:m.target.value}}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:N.config.smtp_use_tls!==!1,onChange:m=>$({...N,config:{...N.config,smtp_use_tls:m.target.checked,smtp_use_ssl:m.target.checked?!1:N.config.smtp_use_ssl}})}),"STARTTLS(常用于 587)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:N.config.smtp_use_ssl===!0,onChange:m=>$({...N,config:{...N.config,smtp_use_ssl:m.target.checked,smtp_use_tls:m.target.checked?!1:N.config.smtp_use_tls}})}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:sa.map(m=>{const p=N.event_types.includes(m.value);return e.jsxs("button",{type:"button",onClick:()=>{const y=p?N.event_types.filter(S=>S!==m.value):[...N.event_types,m.value];$({...N,event_types:y})},className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${p?"border-[#0094f7] bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${p?"bg-[#0094f7] border-[#0094f7]":"border-gray-300"}`,children:p&&e.jsx(Ge,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${p?"text-[#0094f7]":"text-gray-800"}`,children:m.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:m.description})]},m.value)})})]}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:()=>$({...N,enabled:!N.enabled}),className:`relative w-11 h-6 rounded-full transition-colors ${N.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${N.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>L(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:v,disabled:I,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[I?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ge,{className:"w-4 h-4"}),I?"保存中...":"保存"]})]})]})}),document.body),X&&e.jsxs("div",{className:"fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in",style:{background:X.type==="success"?"#10b981":"#ef4444",color:"white"},children:[X.type==="success"?e.jsx(Ge,{className:"w-4 h-4"}):e.jsx(we,{className:"w-4 h-4"}),X.text]})]})},ta={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},$t=Object.fromEntries(Object.entries(ta).map(([s,t])=>[t,s])),Rt=()=>ta[window.location.pathname]||"dashboard",Er=/Win/i.test(navigator.platform||navigator.userAgent),Fr=()=>{const[s,t]=n.useState(!1),[l,c]=n.useState(!1),[h,f]=n.useState(Rt),[L,F]=n.useState(!0),[g,I]=n.useState(!1),[j,G]=n.useState(""),[Y,X]=n.useState(""),[de,C]=n.useState(!1),[M,oe]=n.useState(""),[ee,xe]=n.useState(),O=$=>{const T=$==="settings"&&!l?"dashboard":$,J=$t[T];J&&J!==window.location.pathname&&window.history.pushState({},"",J),f(T)};n.useEffect(()=>{const $=()=>f(Rt());return window.addEventListener("popstate",$),()=>window.removeEventListener("popstate",$)},[]),n.useEffect(()=>{Gt().then(T=>{if((T==null?void 0:T.initialized)===!1){I(!0),t(!1),c(!1);return}I(!1),T!=null&&T.authenticated?(t(!0),c(T.is_admin===!0)):c(!1)}).catch(()=>{t(!1),c(!1)}).finally(()=>F(!1));const $=()=>{t(!1),c(!1)};return window.addEventListener("auth:logout",$),()=>window.removeEventListener("auth:logout",$)},[]),n.useEffect(()=>{!L&&s&&!l&&h==="settings"&&(window.history.replaceState({},"",$t.dashboard),f("dashboard"))},[L,s,l,h]);const le=async $=>{$.preventDefault(),C(!0),oe("");try{const T=await Wa({username:j,password:Y});T.success?(t(!0),c(T.is_admin===!0)):oe(T.message||"登录失败")}catch(T){const J=T instanceof Error?T.message:String(T);oe(J||"登录失败")}finally{C(!1)}},D=async()=>{try{await Va()}catch($){console.error("退出登录失败",$)}finally{t(!1),c(!1)}};if(L)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f5f5f7]",children:e.jsx(Te,{className:"w-8 h-8 text-[#0094f7] animate-spin"})});if(g)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:e.jsx(Gs,{sizeClass:"w-24 h-24"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"系统尚未初始化"}),e.jsx("p",{className:"text-gray-600 font-medium",children:"为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 rounded-2xl bg-gray-50 border border-gray-100",children:[e.jsx("div",{className:"text-sm font-bold text-gray-900 mb-2",children:"请在服务器上执行:"}),e.jsx("pre",{className:"text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto",children:Er?'.\\xianyu-server.exe -init-admin -db data\\xianyu_data.db -admin-password "请设置密码"':"./xianyu-server -init-admin -db data/xianyu_data.db -admin-password '请设置密码'"}),e.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"完成后刷新页面即可进入登录。"})]}),e.jsxs("button",{type:"button",onClick:()=>window.location.reload(),className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group",children:["我已初始化,刷新 ",e.jsx(Ws,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!s)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-lg border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"group mx-auto mb-6 flex cursor-pointer justify-center",children:e.jsx(Gs,{sizeClass:"w-24 h-24",logoClassName:"w-full h-full text-white group-hover:scale-110 transition-transform"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),e.jsxs("form",{onSubmit:le,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(ns,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"text",placeholder:"管理员账号",value:j,onChange:$=>G($.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(Ia,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"密码",value:Y,onChange:$=>X($.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),M&&e.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"})," ",M]}),e.jsx("button",{type:"submit",disabled:de,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:de?e.jsx(Te,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["立即登录 ",e.jsx(Ws,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:e.jsx("div",{className:"mt-6 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const N=()=>{switch(h){case"dashboard":return e.jsx(Os,{});case"accounts":return e.jsx(dr,{});case"orders":return e.jsx(ur,{});case"cards":return e.jsx(hr,{});case"items":return e.jsx(fr,{onConfigureDelivery:$=>{xe({cookieId:$.cookie_id,itemId:$.item_id,requestId:Date.now()}),O("rules")}});case"rules":return e.jsx(Ir,{initialDeliveryTarget:ee,onDeliveryTargetHandled:()=>xe(void 0)});case"notifications":return e.jsx(Tr,{isAdmin:l});case"settings":return l?e.jsx(Nr,{}):e.jsx(Os,{});default:return e.jsx(Os,{})}};return e.jsxs("div",{className:"flex min-h-screen bg-[#F4F5F7] text-[#111]",children:[e.jsx(Ma,{activeTab:h,isAdmin:l,onNavigate:O,onLogout:D}),e.jsxs("main",{className:"flex-1 ml-64 p-8 md:p-12 overflow-y-auto h-screen relative scroll-smooth",children:[e.jsx("div",{className:"fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"}),e.jsx("div",{className:"max-w-[1400px] mx-auto pb-10",children:N()})]})]})},aa=document.getElementById("root");if(!aa)throw new Error("Could not find root element to mount to");const Dr=ra.createRoot(aa);Dr.render(e.jsx(na.StrictMode,{children:e.jsx(Fr,{})})); diff --git a/internal/webui/static/assets/index-hVsGsb1z.css b/internal/webui/static/assets/index-hVsGsb1z.css new file mode 100644 index 0000000..7d5a49b --- /dev/null +++ b/internal/webui/static/assets/index-hVsGsb1z.css @@ -0,0 +1 @@ +*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.-inset-1{top:-.25rem;right:-.25rem;bottom:-.25rem;left:-.25rem}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{right:-.25rem}.-right-6{right:-1.5rem}.-top-6{top:-1.5rem}.bottom-10{bottom:2.5rem}.bottom-8{bottom:2rem}.bottom-\[-10\%\]{bottom:-10%}.left-0{left:0}.left-0\.5{left:.125rem}.left-1{left:.25rem}.left-1\.5{left:.375rem}.left-1\/2{left:50%}.left-4{left:1rem}.left-5{left:1.25rem}.left-\[-10\%\]{left:-10%}.right-0{right:0}.right-10{right:2.5rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-\[-10\%\]{right:-10%}.top-0{top:0}.top-0\.5{top:.125rem}.top-1{top:.25rem}.top-1\.5{top:.375rem}.top-1\/2{top:50%}.top-2{top:.5rem}.top-4{top:1rem}.top-\[-10\%\]{top:-10%}.top-\[calc\(100\%\+6px\)\]{top:calc(100% + 6px)}.-z-10{z-index:-10}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-\[10000\]{z-index:10000}.col-span-2{grid-column:span 2 / span 2}.col-span-full{grid-column:1 / -1}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-10{margin-bottom:2.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-2\.5{margin-bottom:.625rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-64{margin-left:16rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.mt-auto{margin-top:auto}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.line-clamp-3{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.contents{display:contents}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-24{height:6rem}.h-28{height:7rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-80{height:20rem}.h-9{height:2.25rem}.h-\[280px\]{height:280px}.h-\[300px\]{height:300px}.h-\[350px\]{height:350px}.h-\[48px\]{height:48px}.h-\[60\%\]{height:60%}.h-\[800px\]{height:800px}.h-auto{height:auto}.h-full{height:100%}.h-screen{height:100vh}.max-h-44{max-height:11rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-\[380px\]{max-height:380px}.max-h-\[400px\]{max-height:400px}.max-h-\[420px\]{max-height:420px}.max-h-\[min\(64vh\,28rem\)\]{max-height:min(64vh,28rem)}.min-h-0{min-height:0px}.min-h-36{min-height:9rem}.min-h-64{min-height:16rem}.min-h-\[120px\]{min-height:120px}.min-h-\[150px\]{min-height:150px}.min-h-\[400px\]{min-height:400px}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-28{width:7rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[19\%\]{width:19%}.w-\[23\%\]{width:23%}.w-\[27\%\]{width:27%}.w-\[60\%\]{width:60%}.w-\[7\%\]{width:7%}.w-\[8\%\]{width:8%}.w-\[800px\]{width:800px}.w-\[9\%\]{width:9%}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.min-w-0{min-width:0px}.min-w-64{min-width:16rem}.min-w-\[200px\]{min-width:200px}.min-w-\[210px\]{min-width:210px}.min-w-\[260px\]{min-width:260px}.max-w-64{max-width:16rem}.max-w-6xl{max-width:72rem}.max-w-72{max-width:18rem}.max-w-\[12rem\]{max-width:12rem}.max-w-\[1400px\]{max-width:1400px}.max-w-\[15rem\]{max-width:15rem}.max-w-\[240px\]{max-width:240px}.max-w-\[260px\]{max-width:260px}.max-w-\[280px\]{max-width:280px}.max-w-\[340px\]{max-width:340px}.max-w-\[80px\]{max-width:80px}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.flex-1{flex:1 1 0%}.flex-shrink-0,.shrink-0{flex-shrink:0}.table-fixed{table-layout:fixed}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-5{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-6{--tw-translate-x: 1.5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-7{--tw-translate-x: 1.75rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\[1\.02\]{--tw-scale-x: 1.02;--tw-scale-y: 1.02;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.cursor-pointer{cursor:pointer}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-2\.5{gap:.625rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-5{gap:1.25rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-100>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(243 244 246 / var(--tw-divide-opacity, 1))}.divide-gray-50>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(249 250 251 / var(--tw-divide-opacity, 1))}.self-start{align-self:flex-start}.self-end{align-self:flex-end}.self-center{align-self:center}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overscroll-contain{overscroll-behavior:contain}.scroll-smooth{scroll-behavior:smooth}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:6px}.rounded-2xl,.rounded-3xl{border-radius:10px}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:7px}.rounded-md{border-radius:6px}.rounded-xl{border-radius:8px}.border{border-width:1px}.border-0{border-width:0px}.border-2{border-width:2px}.border-4{border-width:4px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[\#0094f7\]{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.border-amber-100{--tw-border-opacity: 1;border-color:rgb(254 243 199 / var(--tw-border-opacity, 1))}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-emerald-100{--tw-border-opacity: 1;border-color:rgb(209 250 229 / var(--tw-border-opacity, 1))}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-50{--tw-border-opacity: 1;border-color:rgb(249 250 251 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-purple-100{--tw-border-opacity: 1;border-color:rgb(243 232 255 / var(--tw-border-opacity, 1))}.border-red-100{--tw-border-opacity: 1;border-color:rgb(254 226 226 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\/10{border-color:#ffffff1a}.bg-\[\#0094f7\]{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F4F5F7\]{--tw-bg-opacity: 1;background-color:rgb(244 245 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F7F8FA\]{--tw-bg-opacity: 1;background-color:rgb(247 248 250 / var(--tw-bg-opacity, 1))}.bg-\[\#FAFAFA\]{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.bg-\[\#f5f5f7\]{--tw-bg-opacity: 1;background-color:rgb(245 245 247 / var(--tw-bg-opacity, 1))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-100\/70{background-color:#fef3c7b3}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-50\/60{background-color:#fffbeb99}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-100\/70{background-color:#dbeafeb3}.bg-blue-200\/30{background-color:#bfdbfe4d}.bg-blue-200\/40{background-color:#bfdbfe66}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-50\/40{background-color:#eff6ff66}.bg-blue-50\/50{background-color:#eff6ff80}.bg-blue-50\/60{background-color:#eff6ff99}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-500\/20{background-color:#3b82f633}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-50\/60{background-color:#ecfdf599}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-100\/50{background-color:#f3f4f680}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-200\/50{background-color:#e5e7eb80}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-pink-50{--tw-bg-opacity: 1;background-color:rgb(253 242 248 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-50{--tw-bg-opacity: 1;background-color:rgb(250 245 255 / var(--tw-bg-opacity, 1))}.bg-purple-50\/50{background-color:#faf5ff80}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-slate-900{--tw-bg-opacity: 1;background-color:rgb(15 23 42 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/5{background-color:#ffffff0d}.bg-white\/80{background-color:#fffc}.bg-white\/90{background-color:#ffffffe6}.bg-white\/95{background-color:#fffffff2}.bg-opacity-10{--tw-bg-opacity: .1}.bg-gradient-to-bl{background-image:linear-gradient(to bottom left,var(--tw-gradient-stops))}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-0{padding:0}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-16{padding:4rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-20{padding:5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-20{padding-top:5rem;padding-bottom:5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-10{padding-bottom:2.5rem}.pb-24{padding-bottom:6rem}.pl-10{padding-left:2.5rem}.pl-11{padding-left:2.75rem}.pl-14{padding-left:3.5rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-5{padding-left:1.25rem}.pl-6{padding-left:1.5rem}.pr-10{padding-right:2.5rem}.pr-11{padding-right:2.75rem}.pr-12{padding-right:3rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pr-9{padding-right:2.25rem}.pt-1{padding-top:.25rem}.pt-4{padding-top:1rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[13px\]{font-size:13px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-black{font-weight:900}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-4{line-height:1rem}.leading-5{line-height:1.25rem}.leading-6{line-height:1.5rem}.leading-relaxed{line-height:1.625}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.text-\[\#111\]{--tw-text-opacity: 1;color:rgb(17 17 17 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-800\/80{color:#92400ecc}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity, 1))}.text-amber-900\/90{color:#78350fe6}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-blue-900{--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}.text-blue-950{--tw-text-opacity: 1;color:rgb(23 37 84 / var(--tw-text-opacity, 1))}.text-emerald-600{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-pink-600{--tw-text-opacity: 1;color:rgb(219 39 119 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity, 1))}.text-slate-400{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.text-slate-950{--tw-text-opacity: 1;color:rgb(2 6 23 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-white\/30{color:#ffffff4d}.accent-\[\#0094f7\]{accent-color:#0094f7}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-25{opacity:.25}.opacity-30{opacity:.3}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_20px_60px_-15px_rgba\(0\,0\,0\,0\.05\)\]{--tw-shadow: 0 20px 60px -15px rgba(0,0,0,.05);--tw-shadow-colored: 0 20px 60px -15px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[4px_0_24px_rgba\(0\,0\,0\,0\.02\)\]{--tw-shadow: 4px 0 24px rgba(0,0,0,.02);--tw-shadow-colored: 4px 0 24px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-blue-100{--tw-shadow-color: #dbeafe;--tw-shadow: var(--tw-shadow-colored)}.shadow-blue-200{--tw-shadow-color: #bfdbfe;--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-100{--tw-shadow-color: #d1fae5;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200{--tw-shadow-color: #e5e7eb;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200\/70{--tw-shadow-color: rgb(229 231 235 / .7);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-4{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-white{--tw-ring-opacity: 1;--tw-ring-color: rgb(255 255 255 / var(--tw-ring-opacity, 1))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-2xl{--tw-blur: blur(40px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-\[120px\]{--tw-blur: blur(120px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-3xl{--tw-backdrop-blur: blur(64px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.squircle{-webkit-mask-image:url(/static/assets/squircle-rb6SKa34.svg);mask-image:url(/static/assets/squircle-rb6SKa34.svg);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;border-radius:0}*{box-sizing:border-box;margin:0;padding:0}html,body,#root{height:100%;width:100%}body{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;background-color:#f4f5f7;color:#fff;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.ios-card{background:#fff;border-radius:8px;border:1px solid rgba(0,0,0,.02);box-shadow:0 8px 24px #0000000a;transition:transform .2s ease,box-shadow .2s ease}.ios-card:hover{box-shadow:0 12px 32px #0000000f}.ios-input{background:#f7f8fa;border:1px solid transparent;transition:all .3s cubic-bezier(.25,.8,.25,1);color:#111;font-weight:500}.ios-input:focus{background:#fff;border-color:#0094f7;box-shadow:0 0 0 4px #0094f74d;outline:none}.ios-input::-moz-placeholder{color:#9ca3af;font-weight:400}.ios-input::placeholder{color:#9ca3af;font-weight:400}.ios-btn-primary{background:#0094f7;color:#fff;font-weight:700;border:none;transition:all .2s cubic-bezier(.25,.8,.25,1);cursor:pointer}.ios-btn-primary:hover:not(:disabled){background:#0071e3;transform:translateY(-1px);box-shadow:0 8px 20px #0094f74d}.ios-btn-primary:active:not(:disabled){transform:translateY(1px);box-shadow:0 2px 8px #0094f733}.ios-btn-primary:disabled{background:#f0f0f0;color:#aaa;box-shadow:none;transform:none;cursor:not-allowed}.ios-btn-secondary{background:#f7f8fa;color:#fff;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-secondary:hover{background:#e5e7eb;border-color:#d1d5db}.ios-btn-danger{background:#fee2e2;color:#dc2626;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-danger:hover{background:#fecaca;border-color:#fca5a5}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#0000001a;border-radius:10px}::-webkit-scrollbar-thumb:hover{background:#0003}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .5s cubic-bezier(.16,1,.3,1) forwards}@keyframes slideUp{0%{opacity:0;transform:translateY(30px) scale(.95)}to{opacity:1;transform:translateY(0) scale(1)}}.animate-slide-up{animation:slideUp .3s cubic-bezier(.16,1,.3,1) forwards}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}::-moz-selection{background:#0094f7;color:#fff}::selection{background:#0094f7;color:#fff}.text-brand{color:#0094f7}.bg-brand{background-color:#0094f7}.border-brand{border-color:#0094f7}.status-badge{display:inline-flex;align-items:center;padding:4px 12px;border-radius:9999px;font-size:12px;font-weight:600}.status-badge-success{background-color:#d1fae5;color:#065f46}.status-badge-warning{background-color:#fef3c7;color:#92400e}.status-badge-error{background-color:#fee2e2;color:#991b1b}.status-badge-info{background-color:#dbeafe;color:#1e40af}.loading-skeleton{background:linear-gradient(90deg,#f3f4f6,#e5e7eb,#f3f4f6);background-size:200% 100%;animation:loading 1.5s ease-in-out infinite}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;align-items:center;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto;display:flex;flex-direction:column;background-color:#fff;border-radius:10px;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}.modal-header{flex-shrink:0;padding:2rem 2rem 1.5rem;border-bottom:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-body{flex:1 1 auto;overflow-y:auto;overflow-x:hidden;padding:2rem}.modal-footer{flex-shrink:0;padding:1.5rem 2rem 2rem;border-top:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-container-lg{max-width:64rem}.modal-overlay-centered{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-overlay-centered .modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto 0;display:flex;flex-direction:column;background-color:#fff;border-radius:10px;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}@media(max-width:768px){.ios-card{border-radius:6px}.ios-input{font-size:16px}.modal-container{max-width:calc(100% - 2rem);max-height:90vh;border-radius:8px}.modal-header,.modal-body,.modal-footer{padding-left:1.5rem;padding-right:1.5rem}}.hover\:translate-y-\[-4px\]:hover{--tw-translate-y: -4px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-\[\#0094f7\]:hover{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.hover\:border-amber-300:hover{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.hover\:border-blue-300:hover{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.hover\:border-emerald-300:hover{--tw-border-opacity: 1;border-color:rgb(110 231 183 / var(--tw-border-opacity, 1))}.hover\:border-gray-300:hover{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.hover\:border-gray-400:hover{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.hover\:bg-\[\#0071e3\]:hover{--tw-bg-opacity: 1;background-color:rgb(0 113 227 / var(--tw-bg-opacity, 1))}.hover\:bg-\[\#0094f7\]:hover{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.hover\:bg-\[\#FFFDE7\]\/50:hover{background-color:#fffde780}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-black:hover{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-100:hover{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50:hover{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50\/50:hover{background-color:#ecfdf580}.hover\:bg-emerald-700:hover{--tw-bg-opacity: 1;background-color:rgb(4 120 87 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-100:hover{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.hover\:bg-green-50:hover{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.hover\:bg-purple-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/10:hover{background-color:#ffffff1a}.hover\:text-\[\#0094f7\]:hover{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.hover\:text-black:hover{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-green-600:hover{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-400:focus{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-0:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-\[\#0094f7\]:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(0 148 247 / var(--tw-ring-opacity, 1))}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-25:disabled{opacity:.25}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.disabled\:opacity-70:disabled{opacity:.7}.group:focus-within .group-focus-within\:text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.group:focus-within .group-focus-within\:text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-125{--tw-scale-x: 1.25;--tw-scale-y: 1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.group:hover .group-hover\:text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:opacity-100{opacity:1}@media(min-width:640px){.sm\:w-48{width:12rem}.sm\:w-56{width:14rem}.sm\:w-72{width:18rem}.sm\:max-w-sm{max-width:24rem}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.sm\:grid-cols-\[1fr_180px\]{grid-template-columns:1fr 180px}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-8{gap:2rem}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:col-span-3{grid-column:span 3 / span 3}.md\:col-span-full{grid-column:1 / -1}.md\:w-auto{width:auto}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.md\:grid-cols-\[1\.4fr_110px_40px\]{grid-template-columns:1.4fr 110px 40px}.md\:grid-cols-\[180px_1fr\]{grid-template-columns:180px 1fr}.md\:grid-cols-\[1fr_1fr_1\.4fr_110px_40px\]{grid-template-columns:1fr 1fr 1.4fr 110px 40px}.md\:flex-row{flex-direction:row}.md\:items-end{align-items:flex-end}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:border-l{border-left-width:1px}.md\:border-t-0{border-top-width:0px}.md\:p-12{padding:3rem}.md\:pl-6{padding-left:1.5rem}.md\:pt-0{padding-top:0}}@media(min-width:1024px){.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-\[320px_1fr\]{grid-template-columns:320px 1fr}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}.lg\:self-auto{align-self:auto}}@media(min-width:1280px){.xl\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.xl\:flex-row{flex-direction:row}.xl\:items-end{align-items:flex-end}.xl\:items-center{align-items:center}.xl\:justify-between{justify-content:space-between}}@media(min-width:1536px){.\32xl\:grid-cols-\[360px_1fr\]{grid-template-columns:360px 1fr}} diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html index 3af871e..924f906 100644 --- a/internal/webui/static/index.html +++ b/internal/webui/static/index.html @@ -6,12 +6,12 @@ Ydisks闲鱼助手 - 自动发货与管家系统 - + - + - +
diff --git a/internal/xianyu/cookierefresh/cookies.go b/internal/xianyu/cookierefresh/cookies.go index 8739635..10c06a6 100644 --- a/internal/xianyu/cookierefresh/cookies.go +++ b/internal/xianyu/cookierefresh/cookies.go @@ -2,8 +2,12 @@ package cookierefresh import ( "encoding/json" + "net/http" + "net/url" + "path" "sort" "strings" + "time" ) const ( @@ -77,6 +81,185 @@ func MergeSetCookies(original string, setCookies []string) string { return MarshalCookieString(m) } +// SnapshotFromCookieString 为只有扁平 Cookie 的历史账号建立兼容快照。浏览器刷新后 +// 应使用真实快照覆盖它,避免长期依赖推断出的 Domain/Path。 +func SnapshotFromCookieString(cookieString, domain string) []BrowserCookie { + domain = strings.TrimSpace(domain) + if domain == "" { + domain = ".goofish.com" + } + out := make([]BrowserCookie, 0) + for name, value := range ParseCookieString(cookieString) { + out = append(out, BrowserCookie{Name: name, Value: value, Domain: domain, Path: "/", Secure: true}) + } + return NormalizeSnapshot(out) +} + +// ReconcileSnapshotWithCookieString 在调用方暂时只能获得扁平 Cookie 结果时保留 +// 已知属性,并同步值与删除项。新增字段使用 .goofish.com 根路径作为兼容作用域。 +func ReconcileSnapshotWithCookieString(snapshot []BrowserCookie, cookieString string) []BrowserCookie { + values := ParseCookieString(cookieString) + seen := make(map[string]struct{}) + out := make([]BrowserCookie, 0, len(snapshot)+len(values)) + for _, cookie := range NormalizeSnapshot(snapshot) { + value, exists := values[cookie.Name] + if !exists { + continue + } + cookie.Value = value + out = append(out, cookie) + seen[cookie.Name] = struct{}{} + } + for name, value := range values { + if _, exists := seen[name]; exists { + continue + } + out = append(out, BrowserCookie{Name: name, Value: value, Domain: ".goofish.com", Path: "/", Secure: true}) + } + return NormalizeSnapshot(out) +} + +// CookieHeaderForURL 按浏览器 Domain/Path/Secure/Expires 规则生成指定 URL 的 +// Cookie header,并保留不同路径下的同名 Cookie。 +func CookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time) string { + target, err := url.Parse(rawURL) + if err != nil || target.Hostname() == "" { + return "" + } + type matchedCookie struct { + cookie BrowserCookie + index int + } + matched := make([]matchedCookie, 0, len(snapshot)) + for index, cookie := range NormalizeSnapshot(snapshot) { + if cookie.Expires > 0 && cookie.Expires <= float64(now.Unix()) { + continue + } + if cookie.Secure && target.Scheme != "https" && target.Scheme != "wss" { + continue + } + if !cookieDomainMatches(target.Hostname(), cookie.Domain) || !cookiePathMatches(target.EscapedPath(), cookie.Path) { + continue + } + matched = append(matched, matchedCookie{cookie: cookie, index: index}) + } + sort.SliceStable(matched, func(i, j int) bool { + if len(matched[i].cookie.Path) != len(matched[j].cookie.Path) { + return len(matched[i].cookie.Path) > len(matched[j].cookie.Path) + } + return matched[i].index < matched[j].index + }) + parts := make([]string, 0, len(matched)) + for _, item := range matched { + parts = append(parts, item.cookie.Name+"="+item.cookie.Value) + } + return strings.Join(parts, "; ") +} + +// ApplySetCookies 把某次请求响应的 Set-Cookie 应用到完整快照。删除操作只删除 +// 相同 name/domain/path 的 Cookie,不会误删其他作用域下的同名项。 +func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []string, now time.Time) []BrowserCookie { + target, err := url.Parse(requestURL) + if err != nil || target.Hostname() == "" { + return NormalizeSnapshot(snapshot) + } + state := make(map[string]BrowserCookie) + for _, cookie := range NormalizeSnapshot(snapshot) { + state[snapshotKey(cookie)] = cookie + } + for _, raw := range setCookies { + parsed, err := http.ParseSetCookie(raw) + if err != nil || strings.TrimSpace(parsed.Name) == "" { + continue + } + domain := strings.ToLower(strings.TrimSpace(parsed.Domain)) + if domain == "" { + domain = strings.ToLower(target.Hostname()) + } else if !strings.HasPrefix(domain, ".") { + domain = "." + domain + } + cookiePath := parsed.Path + if cookiePath == "" { + cookiePath = defaultCookiePath(target.Path) + } + cookie := BrowserCookie{ + Name: parsed.Name, Value: parsed.Value, Domain: domain, Path: cookiePath, + HTTPOnly: parsed.HttpOnly, Secure: parsed.Secure, SameSite: sameSiteLabel(parsed.SameSite), + } + if !parsed.Expires.IsZero() { + cookie.Expires = float64(parsed.Expires.Unix()) + } + key := snapshotKey(cookie) + if parsed.MaxAge < 0 || (!parsed.Expires.IsZero() && !parsed.Expires.After(now)) { + delete(state, key) + continue + } + state[key] = cookie + } + out := make([]BrowserCookie, 0, len(state)) + for _, cookie := range state { + out = append(out, cookie) + } + return NormalizeSnapshot(out) +} + +func snapshotKey(cookie BrowserCookie) string { + return cookie.Name + "\x00" + strings.ToLower(cookie.Domain) + "\x00" + cookie.Path +} + +func cookieDomainMatches(host, domain string) bool { + host = strings.ToLower(strings.TrimSpace(host)) + domain = strings.ToLower(strings.TrimSpace(domain)) + if domain == "" { + return false + } + if strings.HasPrefix(domain, ".") { + base := strings.TrimPrefix(domain, ".") + return host == base || strings.HasSuffix(host, "."+base) + } + return host == domain +} + +func cookiePathMatches(requestPath, cookiePath string) bool { + if requestPath == "" { + requestPath = "/" + } + if cookiePath == "" { + cookiePath = "/" + } + if requestPath == cookiePath { + return true + } + if !strings.HasPrefix(requestPath, cookiePath) { + return false + } + return strings.HasSuffix(cookiePath, "/") || (len(requestPath) > len(cookiePath) && requestPath[len(cookiePath)] == '/') +} + +func defaultCookiePath(requestPath string) string { + if requestPath == "" || requestPath[0] != '/' || requestPath == "/" { + return "/" + } + dir := path.Dir(requestPath) + if dir == "." || dir == "/" { + return "/" + } + return dir +} + +func sameSiteLabel(value http.SameSite) string { + switch value { + case http.SameSiteStrictMode: + return "Strict" + case http.SameSiteLaxMode: + return "Lax" + case http.SameSiteNoneMode: + return "None" + default: + return "" + } +} + // ChangedCookieNames 返回两个 Cookie 字符串之间发生变化的字段名。 func ChangedCookieNames(before, after string) []string { a := ParseCookieString(before) diff --git a/internal/xianyu/cookierefresh/cookies_test.go b/internal/xianyu/cookierefresh/cookies_test.go index 10e4889..a062ec8 100644 --- a/internal/xianyu/cookierefresh/cookies_test.go +++ b/internal/xianyu/cookierefresh/cookies_test.go @@ -1,6 +1,10 @@ package cookierefresh -import "testing" +import ( + "strings" + "testing" + "time" +) func TestMetadataSnapshotKeyCompatibility(t *testing.T) { oldMeta := `{"cookie_refresh_snapshot":[{"name":"a","value":"1","domain":".goofish.com","path":"/"}]}` @@ -17,6 +21,43 @@ func TestMetadataSnapshotKeyCompatibility(t *testing.T) { } } +func TestCookieHeaderForURLScopesDomainPathAndSecure(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + snapshot := []BrowserCookie{ + {Name: "root", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true}, + {Name: "passport", Value: "2", Domain: "passport.goofish.com", Path: "/newlogin", Secure: true}, + {Name: "other", Value: "3", Domain: "h5api.m.goofish.com", Path: "/", Secure: true}, + {Name: "expired", Value: "4", Domain: ".goofish.com", Path: "/", Expires: float64(now.Add(-time.Hour).Unix())}, + } + got := CookieHeaderForURL(snapshot, "https://passport.goofish.com/newlogin/silentHasLogin.do", now) + if got != "passport=2; root=1" { + t.Fatalf("CookieHeaderForURL=%q", got) + } +} + +func TestApplySetCookiesPreservesAttributesAndDeletesExactScope(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + snapshot := []BrowserCookie{ + {Name: "sid", Value: "root", Domain: ".goofish.com", Path: "/"}, + {Name: "sid", Value: "login", Domain: ".goofish.com", Path: "/newlogin"}, + } + updated := ApplySetCookies(snapshot, "https://passport.goofish.com/newlogin/silentHasLogin.do", []string{ + "sid=; Domain=.goofish.com; Path=/newlogin; Max-Age=0", + "fresh=ok; Domain=.goofish.com; Path=/; Secure; HttpOnly; SameSite=None", + }, now) + if got := CookieHeaderForURL(updated, "https://www.goofish.com/", now); !strings.Contains(got, "sid=root") || !strings.Contains(got, "fresh=ok") { + t.Fatalf("updated header=%q snapshot=%+v", got, updated) + } + for _, cookie := range updated { + if cookie.Name == "sid" && cookie.Path == "/newlogin" { + t.Fatalf("精确作用域删除失败: %+v", updated) + } + if cookie.Name == "fresh" && (!cookie.Secure || !cookie.HTTPOnly || cookie.SameSite != "None") { + t.Fatalf("Cookie 属性未保留: %+v", cookie) + } + } +} + func TestChangedSnapshotLabels(t *testing.T) { before := []BrowserCookie{{Name: "a", Value: "1", Domain: ".goofish.com", Path: "/"}} after := []BrowserCookie{{Name: "a", Value: "2", Domain: ".goofish.com", Path: "/"}} diff --git a/internal/xianyu/mtop/client.go b/internal/xianyu/mtop/client.go index fc0a208..b64993e 100644 --- a/internal/xianyu/mtop/client.go +++ b/internal/xianyu/mtop/client.go @@ -35,6 +35,12 @@ const UserPageNavAPI = "https://h5api.m.goofish.com/h5/mtop.idle.web.user.page.n // ItemListAPI 是卖家商品列表端点。 const ItemListAPI = "https://h5api.m.goofish.com/h5/mtop.idle.web.xyh.item.list/1.0/" +// SoldOrdersAPI 是闲鱼卖家工作台的已售订单列表端点。 +const SoldOrdersAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.trade.merchant.sold.get/1.0/" + +// ItemDetailAPI 是闲鱼 PC 商品详情端点。 +const ItemDetailAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.pc.detail/1.0/" + const ( MTopRetryGap = time.Second ItemPageGap = time.Second @@ -59,6 +65,8 @@ type ClientImpl struct { TokenURL string ConsignURL string OrderDetailURL string + SoldOrdersURL string + ItemDetailURL string LoginUserURL string TokenExecutor TokenRequestExecutor } @@ -151,6 +159,7 @@ type ItemListItem struct { ItemDetail string AuctionType string ItemStatus int + IsMultiSpec bool } func hasMTopSuccess(ret []string) bool { @@ -301,19 +310,16 @@ func mergeSetCookie(orig string, current map[string]string, resp *http.Response) } changed := false for _, sc := range setCookies { - // Set-Cookie: name=value; Path=/; ... - pair := sc - if i := strings.Index(pair, ";"); i >= 0 { - pair = pair[:i] + parsed, err := http.ParseSetCookie(sc) + if err != nil || strings.TrimSpace(parsed.Name) == "" { + continue } - if eq := strings.Index(pair, "="); eq >= 0 { - name := strings.TrimSpace(pair[:eq]) - val := strings.TrimSpace(pair[eq+1:]) - if name != "" { - current[name] = val - changed = true - } + if parsed.MaxAge < 0 || (!parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) { + delete(current, parsed.Name) + } else { + current[parsed.Name] = parsed.Value } + changed = true } if !changed { return orig diff --git a/internal/xianyu/mtop/item_detail.go b/internal/xianyu/mtop/item_detail.go new file mode 100644 index 0000000..4c8f898 --- /dev/null +++ b/internal/xianyu/mtop/item_detail.go @@ -0,0 +1,139 @@ +// Package mtop: 商品详情域 — 补充商品列表未返回的多规格信息。 +package mtop + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "xianyu-go/internal/xianyu/protocol" +) + +// ItemDetailFetcher 是商品同步使用的可选详情能力。 +type ItemDetailFetcher interface { + DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error) +} + +var _ ItemDetailFetcher = (*ClientImpl)(nil) + +// DetectItemMultiSpec 查询商品详情并识别多规格结构。该调用不刷新 token, +// 也不合并或持久化响应 Cookie。 +func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error) { + itemID = strings.TrimSpace(itemID) + if itemID == "" { + return false, fmt.Errorf("item_id 不能为空") + } + token := protocol.SignToken(cookies) + if token == "" { + return false, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取商品详情") + } + dataVal := `{"itemId":` + strconv.Quote(itemID) + `}` + timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10) + sign := protocol.GenerateSign(timestamp, token, dataVal) + endpoint := c.ItemDetailURL + if endpoint == "" { + endpoint = ItemDetailAPI + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildItemDetailQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal))) + if err != nil { + return false, err + } + setCommonHeaders(req, cookies) + req.Header.Set("Origin", "https://www.goofish.com") + req.Header.Set("Referer", "https://www.goofish.com/item?id="+url.QueryEscape(itemID)) + + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + resp, err := hc.Do(req) + if err != nil { + return false, fmt.Errorf("商品详情请求失败: %w", err) + } + defer resp.Body.Close() + raw, err := readMTopBody(resp) + if err != nil { + return false, err + } + var decoded struct { + Ret []string `json:"ret"` + Data map[string]any `json:"data"` + } + if err := json.Unmarshal(raw, &decoded); err != nil { + return false, fmt.Errorf("解析商品详情响应失败: %w (body=%s)", err, truncate(string(raw), 300)) + } + if !hasMTopSuccess(decoded.Ret) { + return false, fmt.Errorf("商品详情接口返回非成功: ret=%v", decoded.Ret) + } + return detectItemMultiSpec(decoded.Data), nil +} + +func buildItemDetailQuery(timestamp, sign string) string { + values := url.Values{ + "jsv": {"2.7.2"}, + "appKey": {protocol.SignAppKey}, + "t": {timestamp}, + "sign": {sign}, + "v": {"1.0"}, + "type": {"originaljson"}, + "accountSite": {"xianyu"}, + "dataType": {"json"}, + "timeout": {"20000"}, + "api": {"mtop.taobao.idle.pc.detail"}, + "sessionOption": {"AutoLoginOnly"}, + "spm_cnt": {"a21ybx.item.0.0"}, + } + return values.Encode() +} + +func detectItemMultiSpec(value any) bool { + return detectMultiSpecValue(value, false, 0) +} + +func detectMultiSpecValue(value any, skuContext bool, depth int) bool { + if depth > 16 { + return false + } + switch typed := value.(type) { + case map[string]any: + for key, child := range typed { + normalized := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(key)) + switch normalized { + case "multisku", "ismultisku", "ismultispec", "multiplesku": + if mtopBool(child) { + return true + } + case "skulist", "skus": + if list, ok := child.([]any); ok && len(list) > 1 { + return true + } + case "skuprops", "skuproperties", "specprops", "specifications": + if list, ok := child.([]any); ok && len(list) > 0 { + return true + } + case "props", "properties": + if skuContext { + if list, ok := child.([]any); ok && len(list) > 0 { + return true + } + } + } + nextSKUContext := skuContext || normalized == "skudo" || normalized == "skubase" || normalized == "skumodel" + if detectMultiSpecValue(child, nextSKUContext, depth+1) { + return true + } + } + case []any: + for _, child := range typed { + if detectMultiSpecValue(child, skuContext, depth+1) { + return true + } + } + } + return false +} diff --git a/internal/xianyu/mtop/item_detail_test.go b/internal/xianyu/mtop/item_detail_test.go new file mode 100644 index 0000000..8989566 --- /dev/null +++ b/internal/xianyu/mtop/item_detail_test.go @@ -0,0 +1,58 @@ +package mtop + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func TestDetectItemMultiSpec(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("api") != "mtop.taobao.idle.pc.detail" { + t.Errorf("query=%s", r.URL.RawQuery) + } + rawBody, _ := io.ReadAll(r.Body) + form, _ := url.ParseQuery(string(rawBody)) + if form.Get("data") != `{"itemId":"item-1"}` { + t.Errorf("data=%q", form.Get("data")) + } + _, _ = io.WriteString(w, `{"ret":["SUCCESS::调用成功"],"data":{"skuDO":{"skuProperties":[{"name":"颜色"}],"skuList":[{"id":"1"},{"id":"2"}]}}}`) + })) + defer server.Close() + client := &ClientImpl{HTTPClient: server.Client(), ItemDetailURL: server.URL} + got, err := client.DetectItemMultiSpec(context.Background(), "_m_h5_tk=token_1", "item-1") + if err != nil || !got { + t.Fatalf("got=%v err=%v", got, err) + } +} + +func TestDetectItemMultiSpecSignals(t *testing.T) { + cases := []struct { + name string + data any + want bool + }{ + {name: "explicit", data: map[string]any{"multiSKU": true}, want: true}, + {name: "two skus", data: map[string]any{"skuList": []any{1, 2}}, want: true}, + {name: "sku props", data: map[string]any{"skuDO": map[string]any{"props": []any{"颜色"}}}, want: true}, + {name: "single", data: map[string]any{"multiSKU": false, "skuList": []any{1}}, want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := detectItemMultiSpec(tc.data); got != tc.want { + t.Fatalf("got=%v want=%v", got, tc.want) + } + }) + } +} + +func TestDetectItemMultiSpecRejectsMissingToken(t *testing.T) { + client := &ClientImpl{} + if _, err := client.DetectItemMultiSpec(context.Background(), "unb=1", "item-1"); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") { + t.Fatalf("err=%v", err) + } +} diff --git a/internal/xianyu/mtop/items.go b/internal/xianyu/mtop/items.go index e587dd5..2b22eb8 100644 --- a/internal/xianyu/mtop/items.go +++ b/internal/xianyu/mtop/items.go @@ -237,6 +237,7 @@ func parseItemList(data map[string]any) []ItemListItem { ItemDetail: string(detailJSON), AuctionType: mtopString(cardData["auctionType"]), ItemStatus: mtopInt(cardData["itemStatus"]), + IsMultiSpec: detectItemMultiSpec(cardData), }) } return items diff --git a/internal/xianyu/mtop/sold_orders.go b/internal/xianyu/mtop/sold_orders.go new file mode 100644 index 0000000..c129630 --- /dev/null +++ b/internal/xianyu/mtop/sold_orders.go @@ -0,0 +1,240 @@ +// Package mtop: 卖家订单列表域 — 从卖家工作台发现并解析订单。 +package mtop + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "xianyu-go/internal/xianyu/protocol" +) + +const soldOrdersReferer = "https://seller.goofish.com/?site=COMMONPRO#/seller-trade/order-manage" + +// SoldOrderFetcher 是订单同步使用的可选能力,不扩展基础 Client 接口,避免影响其他调用方的 mock。 +type SoldOrderFetcher interface { + FetchSoldOrdersPage(ctx context.Context, cookies string, pageNumber, pageSize int) (*SoldOrdersPage, error) +} + +// SoldOrdersPage 是一页卖家订单列表。 +type SoldOrdersPage struct { + Items []SoldOrder + NextPage bool + TotalCount int +} + +// SoldOrder 是订单列表可直接落库的字段。 +type SoldOrder struct { + OrderID string + ItemID string + BuyerID string + OrderStatus string + Quantity string + Amount string + ReceiverName string + ReceiverPhone string + ReceiverAddr string + ReceiverCity string + IsBargain bool + PlatformStatus string +} + +var _ SoldOrderFetcher = (*ClientImpl)(nil) + +// FetchSoldOrdersPage 获取卖家已售订单。该能力只使用调用方传入的 Cookie 签名, +// 不刷新 token、不合并 Set-Cookie,也不持久化 Cookie。 +func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pageNumber, pageSize int) (*SoldOrdersPage, error) { + if pageNumber < 1 { + pageNumber = 1 + } + if pageSize < 1 || pageSize > 100 { + pageSize = 30 + } + token := protocol.SignToken(cookies) + if token == "" { + return nil, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取订单列表") + } + payload := map[string]any{ + "pageNumber": pageNumber, + "rowsPerPage": pageSize, + "orderIds": "", + "queryCode": "ALL", + "orderSearchParam": "{}", + } + rawPayload, err := json.Marshal(payload) + if err != nil { + return nil, err + } + dataVal := string(rawPayload) + timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10) + sign := protocol.GenerateSign(timestamp, token, dataVal) + endpoint := c.SoldOrdersURL + if endpoint == "" { + endpoint = SoldOrdersAPI + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildSoldOrdersQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal))) + if err != nil { + return nil, err + } + setCommonHeaders(req, cookies) + req.Header.Set("Accept", "application/json") + req.Header.Set("Origin", "https://seller.goofish.com") + req.Header.Set("Referer", soldOrdersReferer) + req.Header.Set("idle_site_biz_code", "COMMONPRO") + + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + resp, err := hc.Do(req) + if err != nil { + return nil, fmt.Errorf("订单列表请求失败: %w", err) + } + defer resp.Body.Close() + raw, err := readMTopBody(resp) + if err != nil { + return nil, err + } + var decoded struct { + Ret []string `json:"ret"` + Data struct { + Module map[string]any `json:"module"` + } `json:"data"` + } + if err := json.Unmarshal(raw, &decoded); err != nil { + return nil, fmt.Errorf("解析订单列表响应失败: %w (body=%s)", err, truncate(string(raw), 300)) + } + if !hasMTopSuccess(decoded.Ret) { + return nil, fmt.Errorf("订单列表接口返回非成功: ret=%v", decoded.Ret) + } + module := decoded.Data.Module + rawItems, _ := module["items"].([]any) + items := make([]SoldOrder, 0, len(rawItems)) + for _, rawItem := range rawItems { + item, ok := parseSoldOrder(rawItem) + if ok { + items = append(items, item) + } + } + return &SoldOrdersPage{ + Items: items, + NextPage: mtopBool(module["nextPage"]), + TotalCount: mtopInt(module["totalCount"]), + }, nil +} + +func buildSoldOrdersQuery(timestamp, sign string) string { + values := url.Values{ + "jsv": {"2.7.2"}, + "appKey": {protocol.SignAppKey}, + "t": {timestamp}, + "sign": {sign}, + "v": {"1.0"}, + "type": {"json"}, + "accountSite": {"xianyu"}, + "dataType": {"json"}, + "timeout": {"20000"}, + "api": {"mtop.taobao.idle.trade.merchant.sold.get"}, + "valueType": {"string"}, + "sessionOption": {"AutoLoginOnly"}, + "spm_cnt": {"a21107h.42831410.0.0"}, + } + return values.Encode() +} + +func parseSoldOrder(raw any) (SoldOrder, bool) { + item, ok := raw.(map[string]any) + if !ok { + return SoldOrder{}, false + } + common, _ := item["commonData"].(map[string]any) + buyer, _ := item["buyerInfoVO"].(map[string]any) + price, _ := item["priceVO"].(map[string]any) + rights, _ := item["rightVO"].(map[string]any) + orderID := strings.TrimSpace(mtopString(common["orderId"])) + if orderID == "" { + return SoldOrder{}, false + } + rawStatus := strings.TrimSpace(mtopString(common["orderStatus"])) + status := normalizeSoldOrderStatus(rawStatus, mtopBool(common["inRefund"])) + amount := firstMTopString(price, "totalPrice", "confirmFee", "auctionPrice") + quantity := firstMTopString(price, "buyNum", "quantity") + if quantity == "" || quantity == "0" { + quantity = "1" + } + isBargain := false + buttons, _ := rights["btnList"].([]any) + for _, rawButton := range buttons { + button, _ := rawButton.(map[string]any) + if strings.EqualFold(mtopString(button["tradeAction"]), "SKIP_PIN") { + isBargain = true + break + } + } + return SoldOrder{ + OrderID: orderID, + ItemID: strings.TrimSpace(mtopString(common["itemId"])), + BuyerID: strings.TrimSpace(mtopString(buyer["buyerId"])), + OrderStatus: status, + Quantity: quantity, + Amount: amount, + ReceiverName: firstMTopString(buyer, "name", "receiverName"), + ReceiverPhone: firstMTopString(buyer, "phone", "receiverPhone"), + ReceiverAddr: firstMTopString(buyer, "address", "receiverAddress"), + ReceiverCity: firstMTopString(buyer, "city", "receiverCity"), + IsBargain: isBargain, + PlatformStatus: rawStatus, + }, true +} + +func normalizeSoldOrderStatus(raw string, inRefund bool) string { + if inRefund { + return "refunding" + } + switch strings.TrimSpace(raw) { + case "待付款", "处理中": + return "processing" + case "待发货", "已付款": + return "pending_ship" + case "已发货": + return "shipped" + case "交易成功", "已完成": + return "completed" + case "交易关闭", "已关闭", "退款关闭", "退款成功", "已退款": + return "cancelled" + case "退款中": + return "refunding" + default: + return "unknown" + } +} + +func firstMTopString(values map[string]any, keys ...string) string { + for _, key := range keys { + if value := strings.TrimSpace(mtopString(values[key])); value != "" { + return value + } + } + return "" +} + +func mtopBool(value any) bool { + switch typed := value.(type) { + case bool: + return typed + case float64: + return typed != 0 + case int: + return typed != 0 + case string: + normalized := strings.ToLower(strings.TrimSpace(typed)) + return normalized == "true" || normalized == "1" || normalized == "yes" + default: + return false + } +} diff --git a/internal/xianyu/mtop/sold_orders_test.go b/internal/xianyu/mtop/sold_orders_test.go new file mode 100644 index 0000000..46672b8 --- /dev/null +++ b/internal/xianyu/mtop/sold_orders_test.go @@ -0,0 +1,81 @@ +package mtop + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func TestFetchSoldOrdersPageRequestAndParse(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("api") != "mtop.taobao.idle.trade.merchant.sold.get" || r.URL.Query().Get("sign") == "" { + t.Errorf("query=%s", r.URL.RawQuery) + } + if r.Header.Get("Origin") != "https://seller.goofish.com" || r.Header.Get("idle_site_biz_code") != "COMMONPRO" { + t.Errorf("headers=%v", r.Header) + } + rawBody, _ := io.ReadAll(r.Body) + form, _ := url.ParseQuery(string(rawBody)) + var payload map[string]any + if err := json.Unmarshal([]byte(form.Get("data")), &payload); err != nil { + t.Fatal(err) + } + if payload["pageNumber"] != float64(2) || payload["rowsPerPage"] != float64(30) || payload["queryCode"] != "ALL" { + t.Errorf("payload=%+v", payload) + } + _, _ = io.WriteString(w, `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"true","totalCount":"31","items":[{`+ + `"commonData":{"orderId":"order-1","itemId":"item-1","orderStatus":"待发货","inRefund":"false"},`+ + `"buyerInfoVO":{"buyerId":"buyer-1","name":"李四","phone":"13900000000","address":"杭州市"},`+ + `"priceVO":{"totalPrice":"29.90","buyNum":"3"},"rightVO":{"btnList":[{"tradeAction":"SKIP_PIN"}]}}]}}}`) + })) + defer server.Close() + + client := &ClientImpl{HTTPClient: server.Client(), SoldOrdersURL: server.URL} + page, err := client.FetchSoldOrdersPage(context.Background(), "unb=1; _m_h5_tk=token_1;", 2, 30) + if err != nil { + t.Fatal(err) + } + if !page.NextPage || page.TotalCount != 31 || len(page.Items) != 1 { + t.Fatalf("page=%+v", page) + } + item := page.Items[0] + if item.OrderID != "order-1" || item.ItemID != "item-1" || item.OrderStatus != "pending_ship" || + item.Quantity != "3" || item.Amount != "29.90" || !item.IsBargain || item.ReceiverName != "李四" { + t.Fatalf("item=%+v", item) + } +} + +func TestFetchSoldOrdersPageRejectsMissingTokenAndFailure(t *testing.T) { + client := &ClientImpl{} + if _, err := client.FetchSoldOrdersPage(context.Background(), "unb=1", 1, 30); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") { + t.Fatalf("err=%v", err) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, `{"ret":["FAIL_BIZ_ERROR::失败"]}`) + })) + defer server.Close() + client = &ClientImpl{HTTPClient: server.Client(), SoldOrdersURL: server.URL} + if _, err := client.FetchSoldOrdersPage(context.Background(), "_m_h5_tk=token_1", 1, 30); err == nil || !strings.Contains(err.Error(), "非成功") { + t.Fatalf("err=%v", err) + } +} + +func TestNormalizeSoldOrderStatus(t *testing.T) { + cases := map[string]string{ + "待付款": "processing", "待发货": "pending_ship", "已发货": "shipped", + "交易成功": "completed", "退款成功": "cancelled", "退款中": "refunding", + } + for input, want := range cases { + if got := normalizeSoldOrderStatus(input, false); got != want { + t.Fatalf("input=%s got=%s want=%s", input, got, want) + } + } + if got := normalizeSoldOrderStatus("待发货", true); got != "refunding" { + t.Fatalf("inRefund got=%s", got) + } +} diff --git a/internal/xianyu/renew/service.go b/internal/xianyu/renew/service.go index 733a975..cd9b15e 100644 --- a/internal/xianyu/renew/service.go +++ b/internal/xianyu/renew/service.go @@ -11,6 +11,7 @@ import ( "fmt" "io" "net/http" + "net/url" "sort" "strconv" "strings" @@ -21,20 +22,125 @@ import ( ) const ( - HasLoginURL = "https://passport.goofish.com/newlogin/hasLogin.do" - SilentHasLoginURL = "https://passport.goofish.com/newlogin/silentHasLogin.do" - SetLoginSettingsURL = "https://passport.goofish.com/ac/account/setLoginSettings.do" - defaultRequestTimout = 20 * time.Second - maxRenewBodyBytes = 2 << 20 + HasLoginURL = "https://passport.goofish.com/newlogin/hasLogin.do" + SilentHasLoginURL = "https://passport.goofish.com/newlogin/silentHasLogin.do" + SetLoginSettingsURL = "https://passport.goofish.com/ac/account/setLoginSettings.do" + QueryLoginSettingsURL = "https://passport.goofish.com/ac/account/queryLoginSettings.do" + defaultRequestTimout = 2 * time.Second + maxRenewBodyBytes = 2 << 20 ) // Service 是 Cookie 接口续期服务。零值可用;测试可覆盖 URL 和 HTTPClient。 type Service struct { - HTTPClient *http.Client - HasLoginURL string - SilentHasLoginURL string - SetLoginSettingsURL string - RetryDelay time.Duration + HTTPClient *http.Client + HasLoginURL string + SilentHasLoginURL string + QueryLoginSettingsURL string + SetLoginSettingsURL string + DocumentReferer string + RetryDelay time.Duration +} + +type LongLoginSettings struct { + CanOpenLongLogin bool `json:"can_open_long_login"` + Enabled bool `json:"enabled"` + NewCookies string `json:"-"` + SetCookies []string `json:"-"` +} + +// QueryLongLoginSettings 对齐官网个人信息弹窗的“保存登录信息”查询。 +func (s Service) QueryLongLoginSettings(ctx context.Context, cookiesStr string) (*LongLoginSettings, error) { + return s.longLoginRequest(ctx, cookiesStr, nil) +} + +// SetLongLoginSettings 中 status=0 表示开启,status=1 表示关闭。 +func (s Service) SetLongLoginSettings(ctx context.Context, cookiesStr string, enabled bool) (*LongLoginSettings, error) { + status := "1" + if enabled { + status = "0" + } + return s.longLoginRequest(ctx, cookiesStr, &status) +} + +func (s Service) longLoginRequest(ctx context.Context, cookiesStr string, status *string) (*LongLoginSettings, error) { + target := s.urlOrDefault(s.QueryLoginSettingsURL, QueryLoginSettingsURL) + var body io.Reader + if status != nil { + target = s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL) + body = strings.NewReader("status=" + url.QueryEscape(*status)) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, body) + if err != nil { + return nil, err + } + q := req.URL.Query() + q.Set("fromSite", "77") + q.Set("appName", "xianyu") + q.Set("bizEntrance", "web") + req.URL.RawQuery = q.Encode() + setSilentHasLoginHeaders(req, cookiesStr, s.documentReferer()) + if status != nil { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + hc := s.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: defaultRequestTimout} + } + requestCtx, cancel := context.WithTimeout(req.Context(), defaultRequestTimout) + defer cancel() + resp, err := hc.Do(req.Clone(requestCtx)) + if err != nil { + return nil, fmt.Errorf("保存登录信息请求失败: %w", err) + } + defer resp.Body.Close() + raw, err := readRenewBody(resp.Body) + if err != nil { + return nil, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("保存登录信息 HTTP 状态异常: %d", resp.StatusCode) + } + value, ok := findReturnValue(raw) + if !ok { + return nil, fmt.Errorf("保存登录信息响应缺少 returnValue") + } + canOpen, _ := value["canOpenLongLogin"].(bool) + enabledValue, hasEnabled := value["hasLongTokenLogin"].(bool) + if status != nil && !hasEnabled { + enabledValue = *status == "0" + } + setCookies := filterValidSetCookies(resp.Header.Values("Set-Cookie")) + return &LongLoginSettings{ + CanOpenLongLogin: canOpen, + Enabled: enabledValue, + NewCookies: MergeSetCookies(cookiesStr, setCookies), + SetCookies: setCookies, + }, nil +} + +func findReturnValue(raw []byte) (map[string]any, bool) { + var payload map[string]any + if json.Unmarshal(raw, &payload) != nil { + return nil, false + } + return findMapChild(payload, "returnValue", 0) +} + +func findMapChild(parent map[string]any, key string, depth int) (map[string]any, bool) { + if parent == nil || depth > 6 { + return nil, false + } + if value, ok := parent[key].(map[string]any); ok { + return value, true + } + for _, child := range parent { + if nested, ok := child.(map[string]any); ok { + if value, found := findMapChild(nested, key, depth+1); found { + return value, true + } + } + } + return nil, false } // Result 描述一次接口续期的完整结果。 @@ -45,6 +151,7 @@ type Result struct { RenewMethod string NewCookies string UpdatedCookieNames []string + SetCookies []string StepDetails []StepResult Message string ResponseText string @@ -118,6 +225,7 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string) (*Result, RenewMethod: "auto_login_plugin", NewCookies: newCookies, UpdatedCookieNames: ChangedCookieNames(cookiesStr, newCookies), + SetCookies: append([]string(nil), call.SetCookies...), StepDetails: []StepResult{call.Step}, Message: message, ResponseText: string(call.Body), @@ -140,8 +248,17 @@ func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason s } func cookieTimeAfter(raw string, now time.Time) bool { - millis, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64) - return err == nil && millis > now.UnixMilli() + raw = strings.TrimSpace(raw) + if raw == "" { + return false + } + millis, err := strconv.ParseInt(raw, 10, 64) + if err != nil { + // plugin.js 使用 Invalid Date <= now;结果为 false,因此非空异常值 + // 会继续进入对应续期分支。 + return true + } + return millis > now.UnixMilli() } func autoLoginSkipMessage(reason string) string { @@ -167,7 +284,7 @@ func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (ca return callResult{}, err } q := req.URL.Query() - q.Set("documentReferer", "https://www.goofish.com/") + q.Set("documentReferer", s.documentReferer()) q.Set("appName", "xianyu") q.Set("appEntrance", "xianyu_sdkSilent") q.Set("fromSite", "0") @@ -181,7 +298,7 @@ func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (ca return callResult{}, fmt.Errorf("未知静默续期模式: %s", mode) } req.URL.RawQuery = q.Encode() - setSilentHasLoginHeaders(req, cookiesStr) + setSilentHasLoginHeaders(req, cookiesStr, s.documentReferer()) return s.doRenewRequest(req, "silentHasLogin") } @@ -190,11 +307,10 @@ func (s Service) doRenewRequest(req *http.Request, name string) (callResult, err if hc == nil { hc = &http.Client{Timeout: defaultRequestTimout} } - client := *hc - client.CheckRedirect = func(*http.Request, []*http.Request) error { - return http.ErrUseLastResponse - } - resp, err := client.Do(req) + requestCtx, cancel := context.WithTimeout(req.Context(), defaultRequestTimout) + defer cancel() + req = req.Clone(requestCtx) + resp, err := hc.Do(req) if err != nil { return callResult{}, fmt.Errorf("%s 请求失败: %w", name, err) } @@ -209,7 +325,7 @@ func (s Service) doRenewRequest(req *http.Request, name string) (callResult, err HTTPStatus: resp.StatusCode, SetCookieCount: len(setCookies), } - if resp.StatusCode < 200 || resp.StatusCode >= 400 { + if resp.StatusCode < 200 || resp.StatusCode >= 300 { step.Message = fmt.Sprintf("HTTP状态异常: %d", resp.StatusCode) return callResult{Step: step, SetCookies: setCookies, Body: body}, nil } @@ -246,8 +362,7 @@ func renewBusinessOK(body []byte) bool { return true } } - ok, _ := content["success"].(bool) - return ok + return false } func mtopInt(v any) int { @@ -265,14 +380,15 @@ func mtopInt(v any) int { } } -func setSilentHasLoginHeaders(req *http.Request, cookiesStr string) { +func setSilentHasLoginHeaders(req *http.Request, cookiesStr, documentReferer string) { xianyu.ApplyBrowserFingerprint(req.Header) req.Header.Set("Accept", "*/*") - req.Header.Set("Accept-Language", "en,zh-CN;q=0.9,zh;q=0.8,ru;q=0.7") + req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8") req.Header.Set("Cache-Control", "no-cache") req.Header.Set("Pragma", "no-cache") req.Header.Set("Priority", "u=1, i") - req.Header.Set("Referer", "https://www.goofish.com/") + req.Header.Set("Origin", "https://www.goofish.com") + req.Header.Set("Referer", documentReferer) req.Header.Set("sec-fetch-dest", "empty") req.Header.Set("sec-fetch-mode", "cors") req.Header.Set("sec-fetch-site", "same-site") @@ -286,6 +402,13 @@ func (s Service) urlOrDefault(v, fallback string) string { return fallback } +func (s Service) documentReferer() string { + if strings.TrimSpace(s.DocumentReferer) != "" { + return strings.TrimSpace(s.DocumentReferer) + } + return "https://www.goofish.com/im" +} + func readRenewBody(r io.Reader) ([]byte, error) { body, err := io.ReadAll(io.LimitReader(r, maxRenewBodyBytes+1)) if err != nil { @@ -312,7 +435,7 @@ func filterValidSetCookies(setCookies []string) []string { } out := make([]string, 0, len(setCookies)) for _, sc := range setCookies { - if strings.Contains(sc, "Max-Age=0") || strings.Contains(sc, "1970") { + if strings.TrimSpace(sc) == "" { continue } out = append(out, sc) @@ -325,19 +448,15 @@ func filterValidSetCookies(setCookies []string) []string { func MergeSetCookies(original string, setCookies []string) string { cookies := protocol.TransCookies(original) for _, sc := range setCookies { - pair := sc - if i := strings.Index(pair, ";"); i >= 0 { - pair = pair[:i] - } - name, val, ok := strings.Cut(pair, "=") - if !ok { + parsed, err := http.ParseSetCookie(sc) + if err != nil || strings.TrimSpace(parsed.Name) == "" { continue } - name = strings.TrimSpace(name) - if name == "" { - continue + if parsed.MaxAge < 0 || (!parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) { + delete(cookies, parsed.Name) + } else { + cookies[parsed.Name] = parsed.Value } - cookies[name] = strings.TrimSpace(val) } return marshalCookies(cookies) } @@ -347,8 +466,15 @@ func ChangedCookieNames(original, newCookies string) []string { oldMap := protocol.TransCookies(original) newMap := protocol.TransCookies(newCookies) changed := make([]string, 0) - for k, v := range newMap { - if oldMap[k] != v { + seen := make(map[string]struct{}, len(oldMap)+len(newMap)) + for k := range oldMap { + seen[k] = struct{}{} + } + for k := range newMap { + seen[k] = struct{}{} + } + for k := range seen { + if oldMap[k] != newMap[k] { changed = append(changed, k) } } diff --git a/internal/xianyu/renew/service_test.go b/internal/xianyu/renew/service_test.go index ad5de7e..e747ce9 100644 --- a/internal/xianyu/renew/service_test.go +++ b/internal/xianyu/renew/service_test.go @@ -29,7 +29,7 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) { {name: "fatigue", cookies: map[string]string{"sdkSilent": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10), "havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantReason: "fatigue"}, {name: "havana", cookies: map[string]string{"havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana}, {name: "cookie3 backup", cookies: map[string]string{"havana_lgc_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10), "cookie3_bak_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeCookie3}, - {name: "expired", cookies: map[string]string{"havana_lgc_exp": "bad", "cookie3_bak_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)}, wantReason: "long_login_expired"}, + {name: "malformed long-login expiry follows browser Invalid Date branch", cookies: map[string]string{"havana_lgc_exp": "bad", "cookie3_bak_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -41,6 +41,51 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) { } } +func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if r.Method != http.MethodPost { + t.Fatalf("method=%s", r.Method) + } + if r.URL.Query().Get("fromSite") != "77" || r.URL.Query().Get("appName") != "xianyu" || r.URL.Query().Get("bizEntrance") != "web" { + t.Fatalf("query=%s", r.URL.RawQuery) + } + if r.Header.Get("Origin") != "https://www.goofish.com" || r.Header.Get("Referer") != "https://www.goofish.com/im" { + t.Fatalf("origin/referer=%q/%q", r.Header.Get("Origin"), r.Header.Get("Referer")) + } + if !strings.Contains(r.Header.Get("Cookie"), "unb=1") { + t.Fatalf("Cookie=%q", r.Header.Get("Cookie")) + } + if strings.Contains(r.URL.Path, "set") { + if err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" { + t.Fatalf("set form=%v err=%v", r.Form, err) + } + } + http.SetCookie(w, &http.Cookie{Name: "havana_lgc_exp", Value: futureMillis(24 * time.Hour), Path: "/", HttpOnly: true}) + _, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`)) + })) + defer srv.Close() + + service := Service{ + HTTPClient: srv.Client(), + QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do", + SetLoginSettingsURL: srv.URL + "/setLoginSettings.do", + DocumentReferer: "https://www.goofish.com/im", + } + queried, err := service.QueryLongLoginSettings(context.Background(), "unb=1") + if err != nil || !queried.CanOpenLongLogin || !queried.Enabled { + t.Fatalf("query result=%+v err=%v", queried, err) + } + set, err := service.SetLongLoginSettings(context.Background(), queried.NewCookies, true) + if err != nil || !set.Enabled || len(set.SetCookies) != 1 || !strings.Contains(set.NewCookies, "havana_lgc_exp=") { + t.Fatalf("set result=%+v err=%v", set, err) + } + if calls.Load() != 2 { + t.Fatalf("calls=%d", calls.Load()) + } +} + func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) { xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "native-browser-ua", SecChUA: `"Chromium";v="999"`, Platform: "macOS", Mobile: "?0"}) var calls atomic.Int32 @@ -52,6 +97,9 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) { if r.URL.Query().Get("skipSessionFilter") != "" || r.URL.Query().Get("c2r") != "" { t.Fatalf("havana mode included cookie3 flags: %s", r.URL.RawQuery) } + if got := r.URL.Query().Get("documentReferer"); got != "https://www.goofish.com/im" { + t.Fatalf("documentReferer=%q", got) + } if got := r.Header.Get("User-Agent"); got != "native-browser-ua" { t.Fatalf("User-Agent=%q", got) } @@ -63,7 +111,7 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) { })) defer srv.Close() - svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1} + svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, DocumentReferer: "https://www.goofish.com/im", RetryDelay: -1} input := "unb=1; havana_lgc_exp=" + futureMillis(time.Hour) res, err := svc.RenewAPIFirst(context.Background(), input) if err != nil { @@ -140,6 +188,28 @@ func TestMergeSetCookies(t *testing.T) { } } +func TestMergeSetCookiesAppliesServerDeletion(t *testing.T) { + got := MergeSetCookies("unb=1; stale=a; expired=b", []string{ + "stale=; Max-Age=0; Path=/", + "expired=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/", + }) + if strings.Contains(got, "stale=") || strings.Contains(got, "expired=") { + t.Fatalf("deleted cookies survived: %q", got) + } + if changed := strings.Join(ChangedCookieNames("unb=1; stale=a; expired=b", got), ","); changed != "expired,stale" { + t.Fatalf("ChangedCookieNames=%s", changed) + } +} + +func TestRenewBusinessOKMatchesOfficialPlugin(t *testing.T) { + if renewBusinessOK([]byte(`{"content":{"success":true}}`)) { + t.Fatal("official plugin requires processFinished=true and resultCode=100") + } + if !renewBusinessOK([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`)) { + t.Fatal("official success payload was rejected") + } +} + func TestRenewBodyLimit(t *testing.T) { _, err := readRenewBody(strings.NewReader(strings.Repeat("x", maxRenewBodyBytes+1))) if err == nil || !strings.Contains(err.Error(), fmt.Sprint(maxRenewBodyBytes>>20)) { diff --git a/internal/xianyu/ws/client.go b/internal/xianyu/ws/client.go index 2cc879d..17c07b1 100644 --- a/internal/xianyu/ws/client.go +++ b/internal/xianyu/ws/client.go @@ -8,6 +8,7 @@ import ( "fmt" "log/slog" "net/http" + "regexp" "strings" "sync" "time" @@ -19,17 +20,17 @@ import ( ) // WSURL 闲鱼 IM WebSocket 地址。 -const WSURL = "wss://wss-goofish.dingtalk.com/" +const WSURL = "wss://wss-goofish.dingtalk.com:443" const ( - wsOpenTimeout = 30 * time.Second - regResponseTimeout = 30 * time.Second - protocolPingInterval = 20 * time.Second - protocolPingTimeout = 15 * time.Second + wsOpenTimeout = 30 * time.Second + regResponseTimeout = 30 * time.Second ) -// 变量仅用于让单元测试无需真实等待 10 秒;生产值严格对齐参考实现。 -var heartbeatRetryInterval = 5 * time.Second +var ( + heartbeatResponseTimeout = 30 * time.Second + batchConnectDelays = []time.Duration{0, 200 * time.Millisecond, 900 * time.Millisecond, 1500 * time.Millisecond, 4 * time.Second} +) // RegAppKey WS /reg 用的 app-key。 const RegAppKey = "444e9908a51d1cb236a27862abc769c9" @@ -44,18 +45,28 @@ type Config struct { // Conn 包装一条已注册的 WebSocket 连接。 type Conn struct { - ws *websocket.Conn - cfg Config - logger *slog.Logger - sendMu sync.Mutex - preReadMu sync.Mutex - preRead []bufferedFrame - recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string) + ws *websocket.Conn + cfg Config + logger *slog.Logger + sendMu sync.Mutex + recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string) + + readCtx context.Context + readCancel context.CancelFunc + readDone chan struct{} + initOnce sync.Once + readErrMu sync.Mutex + readErr error + + pendingMu sync.Mutex + pending map[string]chan map[string]any + pushes chan incomingFrame } -type bufferedFrame struct { +type incomingFrame struct { messageType websocket.MessageType data []byte + parsed map[string]any } // SetRecorder 设置帧记录器。 @@ -63,135 +74,208 @@ func (c *Conn) SetRecorder(rec func(direction, rawText, parsedJSON, parseStatus, c.recorder = rec } -// Dial 建立并注册 WS 连接:握手 → /reg → /r/SyncStatus/ackDiff。 +// Dial 保留旧的一步式入口;新账号主循环使用 Open → 获取 token → Register, +// 从而与官网 authConnect 的顺序一致。 func Dial(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) { - if logger == nil { - logger = slog.Default() - } - // 参考实现的 WEBSOCKET_HEADERS 为空,只在拨号前加入 Cookie。额外伪造 - // Origin/User-Agent 等头会改变服务端看到的连接指纹。 - hdr := websocketHeaders(cfg.CookieStr) - - logger.Info("正在连接闲鱼 WebSocket", "url", WSURL) - dialCtx, cancel := context.WithTimeout(ctx, wsOpenTimeout) - defer cancel() - c, _, err := websocket.Dial(dialCtx, WSURL, &websocket.DialOptions{HTTPHeader: hdr}) + conn, err := Open(ctx, cfg, logger) if err != nil { - return nil, fmt.Errorf("WS dial: %w", err) + return nil, err } - // 闲鱼消息多为文本 JSON。 - c.SetReadLimit(8 << 20) // 8 MiB,宽松上限 - - conn := &Conn{ws: c, cfg: cfg, logger: logger, recorder: cfg.Recorder} - if err := conn.register(ctx); err != nil { - _ = c.CloseNow() + if err := conn.Register(ctx, cfg.DeviceID, cfg.AccessToken); err != nil { + _ = conn.Close() return nil, err } return conn, nil } -func websocketHeaders(cookieStr string) http.Header { +// Open 按官网 batchConnectWs 策略并行打开最多五条原生 WebSocket,采用最先 +// 成功的连接并关闭冗余连接。此阶段不请求 token,也不发送 /reg。 +func Open(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) { + if logger == nil { + logger = slog.Default() + } + logger.Info("正在连接闲鱼 WebSocket", "url", WSURL) + return openBatch(ctx, WSURL, cfg, logger) +} + +func websocketHeaders() http.Header { hdr := http.Header{} - hdr.Set("Cookie", strings.NewReplacer("\n", "", "\r", "").Replace(cookieStr)) + hdr.Set("Origin", "https://www.goofish.com") + if ua := xianyu.CurrentBrowserFingerprint().UserAgent; ua != "" { + hdr.Set("User-Agent", ua) + } return hdr } -// register 发送 /reg 与 ackDiff。 +var ( + chromeVersionPattern = regexp.MustCompile(`(?:Chrome|CriOS)/([\d.]+)`) + edgeVersionPattern = regexp.MustCompile(`Edg(?:e|A|iOS)?/([\d.]+)`) + firefoxVersionPattern = regexp.MustCompile(`Firefox/([\d.]+)`) + safariVersionPattern = regexp.MustCompile(`Version/([\d.]+).*Safari`) + macVersionPattern = regexp.MustCompile(`Mac OS X[ /]([\d_\.]+)`) + windowsVersionPattern = regexp.MustCompile(`Windows NT ([\d.]+)`) + androidVersionPattern = regexp.MustCompile(`Android[ /]([\d.]+)`) +) + +// OfficialRegistrationUA mirrors IMPaaS 2.2.0's ua-parser-js composition. +// The raw UA (and therefore its browser version) comes from local Chromium; +// all wrapper fields and ordering are fixed to the official web implementation. +func OfficialRegistrationUA(rawUA string) string { + rawUA = strings.TrimSpace(rawUA) + if rawUA == "" { + return "" + } + osName, osVersion := parseOfficialOS(rawUA) + browserName, browserVersion := parseOfficialBrowser(rawUA) + return strings.Join([]string{ + rawUA, + "DingTalk(2.2.0)", + fmt.Sprintf("OS(%s/%s)", osName, osVersion), + fmt.Sprintf("Browser(%s/%s)", browserName, browserVersion), + "DingWeb/2.2.0", + "DingWeb/2.2.0", + }, " ") +} + +func parseOfficialOS(ua string) (string, string) { + if match := macVersionPattern.FindStringSubmatch(ua); len(match) == 2 { + return "Mac OS", strings.ReplaceAll(match[1], "_", ".") + } + if match := windowsVersionPattern.FindStringSubmatch(ua); len(match) == 2 { + versions := map[string]string{"10.0": "10", "6.3": "8.1", "6.2": "8", "6.1": "7", "6.0": "Vista", "5.1": "XP"} + if version := versions[match[1]]; version != "" { + return "Windows", version + } + return "Windows", match[1] + } + if match := androidVersionPattern.FindStringSubmatch(ua); len(match) == 2 { + return "Android", match[1] + } + if strings.Contains(ua, "Linux") { + return "Linux", "other" + } + return "other", "other" +} + +func parseOfficialBrowser(ua string) (string, string) { + for _, candidate := range []struct { + name string + pattern *regexp.Regexp + }{{"Edge", edgeVersionPattern}, {"Chrome", chromeVersionPattern}, {"Firefox", firefoxVersionPattern}, {"Safari", safariVersionPattern}} { + if match := candidate.pattern.FindStringSubmatch(ua); len(match) == 2 { + return candidate.name, match[1] + } + } + return "other", "other" +} + +type dialResult struct { + conn *websocket.Conn + err error +} + +func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logger) (*Conn, error) { + batchCtx, cancel := context.WithCancel(ctx) + results := make(chan dialResult, len(batchConnectDelays)) + for _, delay := range batchConnectDelays { + delay := delay + go func() { + if delay > 0 { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-batchCtx.Done(): + results <- dialResult{err: batchCtx.Err()} + return + case <-timer.C: + } + } + dialCtx, dialCancel := context.WithTimeout(batchCtx, wsOpenTimeout) + defer dialCancel() + conn, _, err := websocket.Dial(dialCtx, target, &websocket.DialOptions{HTTPHeader: websocketHeaders()}) + results <- dialResult{conn: conn, err: err} + }() + } + + var lastErr error + for processed := 1; processed <= len(batchConnectDelays); processed++ { + result := <-results + if result.err != nil { + lastErr = result.err + continue + } + cancel() + // 继续排空结果并关闭稍后成功的冗余连接。 + remaining := len(batchConnectDelays) - processed + go func() { + for i := 0; i < remaining; i++ { + result := <-results + if result.conn != nil { + _ = result.conn.CloseNow() + } + } + }() + result.conn.SetReadLimit(8 << 20) + return newConn(result.conn, cfg, logger), nil + } + cancel() + if lastErr == nil { + lastErr = context.Canceled + } + return nil, fmt.Errorf("WS dial: %w", lastErr) +} + +func newConn(raw *websocket.Conn, cfg Config, logger *slog.Logger) *Conn { + if logger == nil { + logger = slog.Default() + } + c := &Conn{ws: raw, cfg: cfg, logger: logger, recorder: cfg.Recorder} + c.ensureReadPump() + return c +} + +func (c *Conn) ensureReadPump() { + c.initOnce.Do(func() { + if c.logger == nil { + c.logger = slog.Default() + } + c.readCtx, c.readCancel = context.WithCancel(context.Background()) + c.readDone = make(chan struct{}) + c.pending = make(map[string]chan map[string]any) + c.pushes = make(chan incomingFrame, 128) + go c.readPump() + }) +} + +// Register 发送官网最终态 /reg headers。注册后不主动构造 ackDiff。 +func (c *Conn) Register(ctx context.Context, deviceID, accessToken string) error { + c.ensureReadPump() + c.cfg.DeviceID = deviceID + c.cfg.AccessToken = accessToken + response, err := c.request(ctx, "/reg", map[string]any{ + "cache-header": "app-key token ua wv", + "app-key": RegAppKey, + "token": accessToken, + "ua": OfficialRegistrationUA(xianyu.CurrentBrowserFingerprint().UserAgent), + "dt": "j", + "wv": "im:3,au:3,sy:6", + "sync": "0,0;0;0;", + "did": deviceID, + }, nil, regResponseTimeout) + if err != nil { + return fmt.Errorf("等待 /reg 响应失败: %w", err) + } + code, ok := responseCode(response["code"]) + if ok && code == 200 { + c.logger.Info("WS 注册完成") + return nil + } + return newRegError(code, response) +} + +// register 兼容包内旧测试。 func (c *Conn) register(ctx context.Context) error { - regMID := protocol.GenerateMid() - reg := map[string]any{ - "lwp": "/reg", - "headers": map[string]any{ - "cache-header": "app-key token ua wv", - "app-key": RegAppKey, - "token": c.cfg.AccessToken, - "ua": xianyu.CurrentBrowserFingerprint().UserAgent, - "dt": "j", - "wv": "im:3,au:3,sy:6", - "sync": "0,0;0;0;", - "did": c.cfg.DeviceID, - "mid": regMID, - }, - } - if err := c.sendJSON(ctx, reg); err != nil { - return fmt.Errorf("发送 /reg 失败: %w", err) - } - if err := c.waitForRegResponse(ctx, regMID); err != nil { - return err - } - - // 官方只在 /reg 认证成功后启动后续同步。保留原有短等待,避免紧贴注册 - // 响应发送同步请求。 - select { - case <-time.After(time.Second): - case <-ctx.Done(): - return ctx.Err() - } - - now := time.Now().UnixMilli() - ackDiff := map[string]any{ - "lwp": "/r/SyncStatus/ackDiff", - "headers": map[string]any{"mid": protocol.GenerateMid()}, - "body": []any{ - map[string]any{ - "pipeline": "sync", - "tooLong2Tag": "PNM,1", - "channel": "sync", - "topic": "sync", - "highPts": 0, - "pts": now * 1000, - "seq": 0, - "timestamp": now, - }, - }, - } - if err := c.sendJSON(ctx, ackDiff); err != nil { - return fmt.Errorf("发送 ackDiff 失败: %w", err) - } - c.logger.Info("WS 注册完成") - return nil -} - -func (c *Conn) waitForRegResponse(ctx context.Context, requestMID string) error { - regCtx, cancel := context.WithTimeout(ctx, regResponseTimeout) - defer cancel() - - for { - messageType, data, err := c.ws.Read(regCtx) - if err != nil { - return fmt.Errorf("等待 /reg 响应失败: %w", err) - } - var frame map[string]any - if err := json.Unmarshal(data, &frame); err != nil { - c.bufferFrame(messageType, data) - continue - } - if !isRegResponse(frame, requestMID) { - c.bufferFrame(messageType, data) - continue - } - c.recordParsedIncoming(data, frame) - code, ok := responseCode(frame["code"]) - if ok && code == 200 { - return nil - } - return newRegError(code, frame) - } -} - -func isRegResponse(frame map[string]any, requestMID string) bool { - if _, ok := frame["code"]; !ok { - return false - } - headers, _ := frame["headers"].(map[string]any) - responseMIDValue, hasMID := headers["mid"] - responseMID := strings.TrimSpace(fmt.Sprint(responseMIDValue)) - if !hasMID || responseMID == "" || responseMID == "" { - // /reg is the only outstanding request during registration. Some gateway - // versions omit mid on an immediate authentication failure. - return true - } - return midKey(responseMID) == midKey(requestMID) + return c.Register(ctx, c.cfg.DeviceID, c.cfg.AccessToken) } func midKey(mid string) string { @@ -220,23 +304,111 @@ func responseCode(value any) (int, bool) { return 0, false } -func (c *Conn) bufferFrame(messageType websocket.MessageType, data []byte) { - copyOfData := append([]byte(nil), data...) - c.preReadMu.Lock() - c.preRead = append(c.preRead, bufferedFrame{messageType: messageType, data: copyOfData}) - c.preReadMu.Unlock() +func (c *Conn) request(ctx context.Context, path string, headers map[string]any, body any, timeout time.Duration) (map[string]any, error) { + c.ensureReadPump() + if headers == nil { + headers = make(map[string]any) + } + mid := strings.TrimSpace(fmt.Sprint(headers["mid"])) + if mid == "" || mid == "" { + mid = protocol.GenerateMid() + headers["mid"] = mid + } + key := midKey(mid) + responseCh := make(chan map[string]any, 1) + c.pendingMu.Lock() + c.pending[key] = responseCh + c.pendingMu.Unlock() + defer func() { + c.pendingMu.Lock() + delete(c.pending, key) + c.pendingMu.Unlock() + }() + + frame := map[string]any{"lwp": path, "headers": headers} + if body != nil { + frame["body"] = body + } + if err := c.sendJSON(ctx, frame); err != nil { + return nil, err + } + waitCtx := ctx + cancel := func() {} + if timeout > 0 { + waitCtx, cancel = context.WithTimeout(ctx, timeout) + } + defer cancel() + select { + case response := <-responseCh: + return response, nil + case <-c.readDone: + return nil, c.connectionReadError() + case <-waitCtx.Done(): + return nil, waitCtx.Err() + } } -func (c *Conn) readNext(ctx context.Context) (websocket.MessageType, []byte, error) { - c.preReadMu.Lock() - if len(c.preRead) > 0 { - frame := c.preRead[0] - c.preRead = c.preRead[1:] - c.preReadMu.Unlock() - return frame.messageType, frame.data, nil +func (c *Conn) readPump() { + defer close(c.readDone) + for { + messageType, data, err := c.ws.Read(c.readCtx) + if err != nil { + c.readErrMu.Lock() + c.readErr = err + c.readErrMu.Unlock() + return + } + var parsed map[string]any + if err := json.Unmarshal(data, &parsed); err != nil { + if c.recorder != nil { + c.recorder("in", string(data), "", "non_json", err.Error()) + } + continue + } + c.recordParsedIncoming(data, parsed) + if _, hasCode := parsed["code"]; hasCode { + if _, hasHeaders := parsed["headers"].(map[string]any); hasHeaders { + c.dispatchResponse(parsed) + continue + } + } + incoming := incomingFrame{messageType: messageType, data: append([]byte(nil), data...), parsed: parsed} + select { + case c.pushes <- incoming: + case <-c.readCtx.Done(): + return + } } - c.preReadMu.Unlock() - return c.ws.Read(ctx) +} + +func (c *Conn) dispatchResponse(frame map[string]any) bool { + headers, _ := frame["headers"].(map[string]any) + key := midKey(strings.TrimSpace(fmt.Sprint(headers["mid"]))) + c.pendingMu.Lock() + ch := c.pending[key] + if ch == nil && key == "" && len(c.pending) == 1 { + for _, only := range c.pending { + ch = only + } + } + c.pendingMu.Unlock() + if ch == nil { + return false + } + select { + case ch <- frame: + default: + } + return true +} + +func (c *Conn) connectionReadError() error { + c.readErrMu.Lock() + defer c.readErrMu.Unlock() + if c.readErr != nil { + return c.readErr + } + return fmt.Errorf("WebSocket 读取循环已结束") } func (c *Conn) recordParsedIncoming(data []byte, parsed map[string]any) { @@ -250,111 +422,52 @@ func (c *Conn) recordParsedIncoming(data []byte, parsed map[string]any) { c.recorder("in", string(data), parsedJSON, "json", "") } -// HeartbeatLoop 周期性发送应用层心跳 {"lwp":"/!"},直到 ctx 取消或连续失败 maxFailures 次。 +// HeartbeatLoop 对齐官网:注册后先等待一个间隔,再发送 /! 并等待同 mid 响应; +// 任一请求失败或 30 秒无响应即结束连接。 func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error { - const maxFailures = 3 - consecutive := 0 - pingCtx, cancelPing := context.WithCancel(ctx) - defer cancelPing() - pingErr := make(chan error, 1) - go func() { pingErr <- c.protocolPingLoop(pingCtx) }() - - for { - // 参考实现连接建立后立即发送应用层心跳,成功后才等待 15 秒。 - hb := map[string]any{ - "lwp": "/!", - "headers": map[string]any{"mid": protocol.GenerateMid()}, - } - // 2s 超时保护。 - sendCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - err := c.sendJSON(sendCtx, hb) - cancel() - if err != nil { - consecutive++ - c.logger.Error("心跳发送失败", "err", err, "consecutive", consecutive) - if consecutive >= maxFailures { - return fmt.Errorf("心跳连续失败 %d 次", maxFailures) - } - if err := waitHeartbeat(ctx, pingErr, heartbeatRetryInterval); err != nil { - return err - } - continue - } - consecutive = 0 - if err := waitHeartbeat(ctx, pingErr, interval); err != nil { - return err - } - } -} - -func waitHeartbeat(ctx context.Context, pingErr <-chan error, delay time.Duration) error { - timer := time.NewTimer(delay) - defer timer.Stop() - select { - case <-ctx.Done(): - return ctx.Err() - case err := <-pingErr: - if err == nil { - return fmt.Errorf("WebSocket PING 循环意外退出") - } - return err - case <-timer.C: - return nil - } -} - -// protocolPingLoop 对齐参考库的 ping_interval=20、ping_timeout=15。 -func (c *Conn) protocolPingLoop(ctx context.Context) error { - ticker := time.NewTicker(protocolPingInterval) + c.ensureReadPump() + ticker := time.NewTicker(interval) defer ticker.Stop() for { select { case <-ctx.Done(): return ctx.Err() + case <-c.readDone: + return c.connectionReadError() case <-ticker.C: } - pingCtx, cancel := context.WithTimeout(ctx, protocolPingTimeout) - err := c.ws.Ping(pingCtx) - cancel() + response, err := c.request(ctx, "/!", map[string]any{}, nil, heartbeatResponseTimeout) if err != nil { - return fmt.Errorf("WebSocket PING 失败: %w", err) + if ctx.Err() != nil { + return ctx.Err() + } + return fmt.Errorf("心跳响应失败: %w", err) + } + if code, ok := responseCode(response["code"]); ok && code != http.StatusOK { + return fmt.Errorf("心跳响应状态异常: %d", code) } } } -// ReceiveLoop 阻塞读取消息:回 ACK,对同步包解密并回调 handler。 -// 非 JSON / 非同步包消息仅记录后跳过。返回 ctx 错误或致命读取错误。 +// ReceiveLoop 消费 readPump 分发的 Push。响应帧永远不会进入这里,因此不会被 +// 错误 ACK;Push ACK 原样复用服务端完整 headers。 func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[string]any)) error { + c.ensureReadPump() for { - msgType, data, err := c.readNext(ctx) - if err != nil { - return fmt.Errorf("WS read: %w", err) + var frame incomingFrame + select { + case <-ctx.Done(): + return ctx.Err() + case <-c.readDone: + return fmt.Errorf("WS read: %w", c.connectionReadError()) + case frame = <-c.pushes: } - _ = msgType - rawText := string(data) - var raw map[string]any - if err := json.Unmarshal(data, &raw); err != nil { - if c.recorder != nil { - c.recorder("in", rawText, "", "non_json", err.Error()) - } - c.logger.Debug("非 JSON 消息,跳过", "err", err) - continue - } - if c.recorder != nil { - if b, e := json.Marshal(raw); e == nil { - c.recorder("in", rawText, string(b), "json", "") - } else { - c.recorder("in", rawText, "", "json", e.Error()) - } - } - - // 心跳响应等直接跳过。 - if code, ok := raw["code"]; ok && code != nil { - c.logger.Debug("收到响应", "code", code) - } - - // 收到消息后先回复 ACK。 + raw := frame.parsed + rawText := string(frame.data) c.sendACK(ctx, raw) + if err := c.handleSyncExtra(ctx, raw); err != nil { + c.logger.Error("同步状态恢复失败", "err", err) + } // 仅处理同步包:body.syncPushPackage.data[0].data syncData, ok := extractSyncPayload(raw) @@ -383,21 +496,40 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str } } -// sendACK 回复 {"code":200, headers:{mid,sid,...}},失败时仅记录日志。 +func (c *Conn) handleSyncExtra(ctx context.Context, msg map[string]any) error { + body, _ := msg["body"].(map[string]any) + extra, _ := body["syncExtraType"].(map[string]any) + typeCode, ok := responseCode(extra["type"]) + if !ok || (typeCode != 1 && typeCode != 2) { + return nil + } + state, err := c.request(ctx, "/r/SyncStatus/getState", map[string]any{}, []any{map[string]any{"topic": "sync"}}, regResponseTimeout) + if err != nil { + return fmt.Errorf("getState: %w", err) + } + if code, ok := responseCode(state["code"]); !ok || code != http.StatusOK || state["body"] == nil { + return fmt.Errorf("getState 返回异常: code=%v", state["code"]) + } + response, err := c.request(ctx, "/r/SyncStatus/ackDiff", map[string]any{}, []any{state["body"]}, regResponseTimeout) + if err != nil { + return fmt.Errorf("ackDiff: %w", err) + } + if code, ok := responseCode(response["code"]); ok && code != http.StatusOK { + return fmt.Errorf("ackDiff 返回异常: code=%d", code) + } + return nil +} + +// sendACK 回复 {"code":200, headers:<服务端完整 headers>}。 func (c *Conn) sendACK(ctx context.Context, msg map[string]any) { headers, _ := msg["headers"].(map[string]any) - ack := map[string]any{ - "code": 200, - "headers": map[string]any{ - "mid": ackVal(headers, "mid", protocol.GenerateMid()), - "sid": ackVal(headers, "sid", ""), - }, + ackHeaders := make(map[string]any, len(headers)) + for key, value := range headers { + ackHeaders[key] = value } - ackHeaders := ack["headers"].(map[string]any) - for _, k := range []string{"app-key", "ua", "dt"} { - if v, ok := headers[k]; ok && v != nil { - ackHeaders[k] = v - } + ack := map[string]any{ + "code": 200, + "headers": ackHeaders, } // ACK 失败不阻塞主循环。 ackCtx, cancel := context.WithTimeout(ctx, 2*time.Second) @@ -405,14 +537,6 @@ func (c *Conn) sendACK(ctx context.Context, msg map[string]any) { cancel() } -// ackVal 取 header 中的 key,缺失或为 nil 时返回 fallback。 -func ackVal(headers map[string]any, key string, fallback any) any { - if v, ok := headers[key]; ok && v != nil { - return v - } - return fallback -} - // extractSyncPayload 取出 body.syncPushPackage.data[0].data(字符串)。 func extractSyncPayload(msg map[string]any) (string, bool) { body, _ := msg["body"].(map[string]any) @@ -561,5 +685,7 @@ func stripGoofish(s string) string { // Close 关闭连接。 func (c *Conn) Close() error { + c.ensureReadPump() + c.readCancel() return c.ws.Close(websocket.StatusNormalClosure, "bye") } diff --git a/internal/xianyu/ws/client_test.go b/internal/xianyu/ws/client_test.go index 935a214..940372f 100644 --- a/internal/xianyu/ws/client_test.go +++ b/internal/xianyu/ws/client_test.go @@ -2,15 +2,27 @@ package ws import ( "encoding/base64" - "reflect" "testing" + + "xianyu-go/internal/xianyu" ) -func TestWebsocketHeadersOnlyContainSanitizedCookie(t *testing.T) { - got := websocketHeaders("a=1;\r\nb=2") - want := map[string][]string{"Cookie": {"a=1;b=2"}} - if !reflect.DeepEqual(map[string][]string(got), want) { - t.Fatalf("websocket headers = %#v, want %#v", got, want) +func TestWebsocketHeadersMatchBrowserHandshake(t *testing.T) { + xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "runtime-browser-ua"}) + got := websocketHeaders() + if got.Get("Origin") != "https://www.goofish.com" || got.Get("User-Agent") != "runtime-browser-ua" { + t.Fatalf("websocket headers = %#v", got) + } + if got.Get("Cookie") != "" { + t.Fatalf("dingtalk WebSocket 不应收到 goofish Cookie: %#v", got) + } +} + +func TestOfficialRegistrationUAUsesRuntimeBrowserVersion(t *testing.T) { + raw := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/138.0.7204.92 Safari/537.36" + want := raw + " DingTalk(2.2.0) OS(Mac OS/10.15.7) Browser(Chrome/138.0.7204.92) DingWeb/2.2.0 DingWeb/2.2.0" + if got := OfficialRegistrationUA(raw); got != want { + t.Fatalf("OfficialRegistrationUA() = %q, want %q", got, want) } } @@ -40,13 +52,6 @@ func TestDecodeSyncDataJSONAndInvalid(t *testing.T) { } func TestWSHelpers(t *testing.T) { - headers := map[string]any{"mid": "m1", "nil": nil} - if got := ackVal(headers, "mid", "fallback"); got != "m1" { - t.Fatalf("ackVal existing = %v", got) - } - if got := ackVal(headers, "nil", "fallback"); got != "fallback" { - t.Fatalf("ackVal nil = %v", got) - } if got := stripGoofish(" 123@goofish "); got != "123" { t.Fatalf("stripGoofish = %q", got) } diff --git a/internal/xianyu/ws/dial_test.go b/internal/xianyu/ws/dial_test.go index 9515bc2..24478fc 100644 --- a/internal/xianyu/ws/dial_test.go +++ b/internal/xianyu/ws/dial_test.go @@ -7,7 +7,6 @@ import ( "errors" "net/http" "net/http/httptest" - "strings" "sync" "testing" "time" @@ -17,8 +16,7 @@ import ( "xianyu-go/internal/xianyu" ) -// startRegServer 启动一个本地 WS 服务,模拟 /reg 握手:读取客户端发来的 /reg 与 -// ackDiff 两条消息,验证它们的结构,然后保持连接打开(由调用方决定何时关闭)。 +// startRegServer 启动一个本地 WS 服务,模拟 /reg 握手并保持连接打开。 // 返回服务实例与一个收集到所有客户端消息的 channel。 func startRegServer(t *testing.T) (*httptest.Server, chan map[string]any) { t.Helper() @@ -75,13 +73,13 @@ func dialLocal(t *testing.T, srv *httptest.Server, cfg Config) *Conn { } dialed.SetReadLimit(8 << 20) t.Cleanup(func() { _ = dialed.CloseNow() }) - return &Conn{ws: dialed, cfg: cfg, logger: nilLogger(), recorder: cfg.Recorder} + return newConn(dialed, cfg, nilLogger()) } -// TestRegister_SendsRegAndAckDiff 直接调用 register 覆盖 /reg 握手 + ackDiff 两条消息。 -// 验证:1) /reg 消息含正确 lwp/app-key/token/ua/did;2) ackDiff 消息 lwp 正确且 body 非空。 -func TestRegister_SendsRegAndAckDiff(t *testing.T) { - xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "playwright-native-ua"}) +// TestRegisterSendsOnlyOfficialReg 验证注册只发送 /reg,不再伪造 ackDiff。 +func TestRegisterSendsOnlyOfficialReg(t *testing.T) { + rawUA := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/138.0.7204.92 Safari/537.36" + xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: rawUA}) srv, got := startRegServer(t) conn := dialLocal(t, srv, Config{ CookieStr: "cookie=1", @@ -103,15 +101,15 @@ collect: select { case m := <-got: msgs = append(msgs, m) - if len(msgs) >= 2 { + if len(msgs) >= 1 { break collect } case <-timer.C: break collect } } - if len(msgs) < 2 { - t.Fatalf("期望收到 2 条消息,实际 %d: %#v", len(msgs), msgs) + if len(msgs) != 1 { + t.Fatalf("期望只收到 /reg,实际 %d: %#v", len(msgs), msgs) } reg := msgs[0] @@ -125,8 +123,8 @@ collect: if headers["token"] != "token-abc" { t.Errorf("/reg token = %v, 期望 token-abc", headers["token"]) } - if headers["ua"] != "playwright-native-ua" { - t.Errorf("/reg ua = %v, 期望 Playwright 原生 UA", headers["ua"]) + if headers["ua"] != OfficialRegistrationUA(rawUA) { + t.Errorf("/reg ua = %v, 期望官方复合 UA", headers["ua"]) } if headers["did"] != "device-xyz" { t.Errorf("/reg did = %v, 期望 device-xyz", headers["did"]) @@ -135,27 +133,23 @@ collect: t.Errorf("/reg mid 应为非空字符串, 实际 %v", headers["mid"]) } - ackDiff := msgs[1] - if ackDiff["lwp"] != "/r/SyncStatus/ackDiff" { - t.Fatalf("第二条消息 lwp 应为 ackDiff, 实际 %v", ackDiff["lwp"]) - } - body, _ := ackDiff["body"].([]any) - if len(body) == 0 { - t.Fatalf("ackDiff body 为空") - } - first, _ := body[0].(map[string]any) - if first["pipeline"] != "sync" || first["channel"] != "sync" { - t.Errorf("ackDiff body[0] 结构异常: %#v", first) - } } -// TestRegister_ContextCancelledDuringWait register 在 1 秒等待期间 ctx 取消应返回 ctx.Err。 +// TestRegister_ContextCancelledDuringWait register 等不到响应时应服从 ctx 取消。 func TestRegister_ContextCancelledDuringWait(t *testing.T) { - srv, _ := startRegServer(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c, err := websocket.Accept(w, r, nil) + if err != nil { + return + } + defer c.CloseNow() + _, _, _ = c.Read(r.Context()) + <-r.Context().Done() + })) + t.Cleanup(srv.Close) conn := dialLocal(t, srv, Config{}) ctx, cancel := context.WithCancel(context.Background()) - // 等到 /reg 发出、进入 1 秒等待后再取消。 go func() { time.Sleep(100 * time.Millisecond) cancel() @@ -219,7 +213,6 @@ func TestRegisterBuffersFrameBeforeResponse(t *testing.T) { _ = c.Write(ctx, websocket.MessageText, pushRaw) response, _ := json.Marshal(map[string]any{"code": 200, "headers": map[string]any{"mid": headers["mid"]}}) _ = c.Write(ctx, websocket.MessageText, response) - _, _, _ = c.Read(ctx) // ackDiff })) t.Cleanup(srv.Close) @@ -229,12 +222,13 @@ func TestRegisterBuffersFrameBeforeResponse(t *testing.T) { if err := conn.register(ctx); err != nil { t.Fatalf("register: %v", err) } - _, data, err := conn.readNext(ctx) - if err != nil { - t.Fatalf("read buffered frame: %v", err) - } var got map[string]any - _ = json.Unmarshal(data, &got) + select { + case frame := <-conn.pushes: + got = frame.parsed + case <-ctx.Done(): + t.Fatalf("read buffered frame: %v", ctx.Err()) + } if got["lwp"] != push["lwp"] { t.Fatalf("buffered frame=%v want=%v", got, push) } @@ -266,7 +260,7 @@ func TestDial_RegisterFailure(t *testing.T) { } defer dialed.CloseNow() dialed.SetReadLimit(8 << 20) - conn := &Conn{ws: dialed, cfg: Config{}, logger: nilLogger()} + conn := newConn(dialed, Config{}, nilLogger()) err = conn.register(dialCtx) if err == nil { t.Fatal("register 应在连接关闭时返回错误") @@ -328,7 +322,7 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) { defer dialed.CloseNow() dialed.SetReadLimit(8 << 20) - conn := &Conn{ws: dialed, logger: nilLogger()} + conn := newConn(dialed, Config{}, nilLogger()) var ackSeen map[string]any var onMessageCount int loopDone := make(chan error, 1) @@ -366,7 +360,7 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) { } } -// TestSendACK_NoHeaders 消息无 headers 时 ACK 用 fallback mid(GenerateMid 非空)且 sid 为空。 +// TestSendACK_NoHeaders 消息无 headers 时 ACK 原样返回空 headers。 func TestSendACK_NoHeaders(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := websocket.Accept(w, r, nil) @@ -408,7 +402,7 @@ func TestSendACK_NoHeaders(t *testing.T) { defer dialed.CloseNow() dialed.SetReadLimit(8 << 20) - conn := &Conn{ws: dialed, logger: nilLogger()} + conn := newConn(dialed, Config{}, nilLogger()) var ackSeen map[string]any loopDone := make(chan error, 1) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) @@ -425,22 +419,13 @@ func TestSendACK_NoHeaders(t *testing.T) { t.Fatal("未收到 ack") } ackHeaders, _ := ackSeen["headers"].(map[string]any) - mid, _ := ackHeaders["mid"].(string) - if mid == "" { - t.Errorf("无 headers 时 ACK mid 应用 fallback (GenerateMid), 实际空") - } - if ackHeaders["sid"] != "" { - t.Errorf("无 headers 时 ACK sid 应为空, 实际 %v", ackHeaders["sid"]) + if len(ackHeaders) != 0 { + t.Errorf("无 headers 时 ACK 应保持空 headers, 实际 %v", ackHeaders) } } -// TestHeartbeatLoop_SendFailure 服务端立刻关闭连接,HeartbeatLoop 的 sendJSON 应失败; -// 连续失败达 maxFailures(3) 次后应返回错误。 +// TestHeartbeatLoop_SendFailure 服务端关闭后心跳立即结束,不做三次写失败重试。 func TestHeartbeatLoop_SendFailure(t *testing.T) { - oldRetry := heartbeatRetryInterval - heartbeatRetryInterval = 20 * time.Millisecond - t.Cleanup(func() { heartbeatRetryInterval = oldRetry }) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := websocket.Accept(w, r, nil) if err != nil { @@ -460,7 +445,7 @@ func TestHeartbeatLoop_SendFailure(t *testing.T) { defer dialed.CloseNow() dialed.SetReadLimit(8 << 20) - conn := &Conn{ws: dialed, logger: nilLogger()} + conn := newConn(dialed, Config{}, nilLogger()) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() loopDone := make(chan error, 1) @@ -472,9 +457,6 @@ func TestHeartbeatLoop_SendFailure(t *testing.T) { if err == nil { t.Fatal("HeartbeatLoop 应在连续失败后返回错误") } - if !strings.Contains(err.Error(), "心跳连续失败") { - t.Fatalf("期望心跳连续失败错误, 实际 %v", err) - } case <-time.After(8 * time.Second): t.Fatal("HeartbeatLoop 未在超时内退出") } @@ -759,7 +741,7 @@ func TestSetRecorder_RecordsOutgoingAndIncoming(t *testing.T) { dir, parsed, status string }{direction, parsedJSON, parseStatus}) } - conn := &Conn{ws: dialed, logger: nilLogger()} + conn := newConn(dialed, Config{}, nilLogger()) // 通过 SetRecorder 方法设置(覆盖该方法),而非直接赋值字段。 conn.SetRecorder(rec) if conn.recorder == nil { @@ -825,7 +807,7 @@ func TestClose_TerminatesConnection(t *testing.T) { t.Fatalf("dial: %v", err) } dialed.SetReadLimit(8 << 20) - conn := &Conn{ws: dialed, logger: nilLogger()} + conn := newConn(dialed, Config{}, nilLogger()) if err := conn.Close(); err != nil { t.Fatalf("Close: %v", err) diff --git a/internal/xianyu/ws/receive_loop_test.go b/internal/xianyu/ws/receive_loop_test.go index cdceed8..0dae8c7 100644 --- a/internal/xianyu/ws/receive_loop_test.go +++ b/internal/xianyu/ws/receive_loop_test.go @@ -66,7 +66,7 @@ func TestReceiveLoop_DecodesSyncPayload(t *testing.T) { defer dialed.CloseNow() dialed.SetReadLimit(8 << 20) - conn := &Conn{ws: dialed, logger: nilLogger()} + conn := newConn(dialed, Config{}, nilLogger()) var got map[string]any loopDone := make(chan error, 1) @@ -120,7 +120,7 @@ func TestReceiveLoop_NonJSONSkipped(t *testing.T) { defer dialed.CloseNow() dialed.SetReadLimit(8 << 20) - conn := &Conn{ws: dialed, logger: nilLogger()} + conn := newConn(dialed, Config{}, nilLogger()) var got map[string]any loopDone := make(chan error, 1) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) @@ -162,7 +162,7 @@ func TestHeartbeatLoop_ContextCancel(t *testing.T) { defer dialed.CloseNow() dialed.SetReadLimit(8 << 20) - conn := &Conn{ws: dialed, logger: nilLogger()} + conn := newConn(dialed, Config{}, nilLogger()) ctx, cancel := context.WithCancel(context.Background()) loopDone := make(chan error, 1) go func() {