diff --git a/docs/slider-captcha-frozen-spec.md b/docs/slider-captcha-frozen-spec.md index 9659969..4f67d12 100644 --- a/docs/slider-captcha-frozen-spec.md +++ b/docs/slider-captcha-frozen-spec.md @@ -207,6 +207,17 @@ Playwright 主引擎 - `CAPTCHA_REAL_MOUSE=true` 在当前 Go/Docker 实现中只记录物理鼠标不可用,并继续备用逻辑;不得假装已启用物理鼠标。 - `CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED` 默认为启用。 - 备用引擎成功返回的引擎标识保持为 `drissionpage`,虽然底层实现是直接 Chromium + CDP。 +- `CAPTCHA_IGNORE_CERT_ERRORS` 默认关闭。仅当运行环境存在 TLS 检查代理、且诊断明确记录 + Alibaba 风控资源出现 `ERR_CERT_AUTHORITY_INVALID` 时,才允许显式设为 `true`;此时主引擎和 + 备用 Chromium 都追加 `--ignore-certificate-errors`,HTTP 客户端仍保持正常证书校验。该开关 + 必须记录在部署配置中,不能默认开启或静默改变。 +- 初始化时必须从随包 Chromium 实测 UA 和 Client Hints。无头上下文只允许把 legacy UA 中的 + `HeadlessChrome/<实际版本>` 规范化为 `Chrome/<相同实际版本>`;不得伪造版本、操作系统或移动端 + 状态。有头上下文不覆盖 Chromium 原生 UA。Playwright 主引擎必须同时使用 context `userAgent` + 和导航前保持连接的页面级 `Emulation.setUserAgentOverride`,后者携带从实际 Chromium 读取并去除 + 无头品牌、去重后的 `userAgentMetadata`;只设置 context `userAgent` 不合格,因为其默认 + `Sec-CH-UA` 和 `navigator.userAgentData` 仍可能包含 `HeadlessChrome`。非浏览器 HTTP 请求使用同一份 + 规范化运行时指纹。 ## 7. 备用引擎行为 @@ -217,6 +228,8 @@ Playwright 主引擎 - 启动前清理现有 singleton 文件和 `DevToolsActivePort`,退出后再次清理 singleton 文件。 - 保留 `--remote-debugging-port=0`、`--window-size=1920,1080`、`--lang=zh-CN`、`--disable-blink-features=AutomationControlled` 等现有启动参数。 - headless 时使用 `--headless=new`。 +- headless 时必须在导航前通过 `--user-agent` 应用同版本、已去除 `HeadlessChrome` 标记的运行时 UA; + 有头模式不得追加该覆盖。Chromium 原生 Client Hints 必须继续保留,且不得出现 `HeadlessChrome`。 - 默认总超时为 `25s`,可由现有环境变量控制;导航超时为 `15s`。 备用距离规则固定如下: @@ -246,6 +259,8 @@ Playwright 主引擎 - 最终 `left`、最终 class 或最终 X 偏移。 - 失败时的按钮 style/class、轨道 class、可见重试选择器和重试文本。 - 恢复方式是 `click` 还是 `reload`、所用选择器以及是否重新归位。 +- 诊断包的 `page_state` 必须保留页面实际看到的 `navigator.userAgent`、`navigator.webdriver`、 + `navigator.userAgentData` 基础字段及可读取的 high-entropy values,用于识别 UA/Client Hints 矛盾。 - 自动滑块最终失败时,错误文本和 `token 风控滑块处理失败` 日志的 `verification_url` 字段必须包含最后实际使用的完整验证地址(包括 query),供用户复制到本机浏览器手动验证。此字段是仅在最终失败时提供的人工接管信息;常规页面/frame 诊断日志仍必须去掉 query 与 fragment。 页面可能被浏览器扩展注入大量无关 DOM。当前仅把下列注入作为诊断信息记录,不允许它们改变滑块定位、距离或成功判定: @@ -276,6 +291,9 @@ go vet ./internal/browser ./internal/engine ./internal/account ./internal/server - 没有可见滑块、只显示直接错误提示的真实 Chromium 页面必须被识别,并且不得进入滑动或备用引擎。 - 标准 `300px` 轨道与 `42px` 按钮得到精确 `258px`。 - 旧 `x5sec` 不得判成功,新 `x5sec` 才能判成功。 +- 主 Playwright 无头上下文和直接 Chromium/CDP 无头上下文的 HTTP `User-Agent`、`Sec-CH-UA`、 + `navigator.userAgent`、`navigator.userAgentData` 都不得出现 `HeadlessChrome`/`headless` 标记,UA 中 + 的 Chrome 完整版本必须与随包 Chromium 一致。 不得删除、跳过、弱化或改写断言来让行为变化通过测试。 @@ -285,6 +303,13 @@ go vet ./internal/browser ./internal/engine ./internal/account ./internal/server 用户明确要求改变“未找到滑块时仍执行失败恢复/备用引擎”和“最终失败日志只保留脱敏页面地址”的既有契约。原因是风控页有时只显示平台错误信息而没有可操作滑块,继续 reload、拖动或切换引擎没有验证意义且会增加风控;而真实滑块自动处理失败时,用户需要完整地址在本机浏览器中接管验证。本规范第 3.1、6、8、9 节已同步纳入新的页面分类、编排、日志和集成验证要求。 +### 2026-08-17 当前授权变更 + +用户明确要求解决无头 Chromium 指纹暴露 `HeadlessChrome` 的问题。此前随包 Chromium 在服务端 +风控页中实测返回 `HeadlessChrome/149.0.7827.55`,会让 HTTP UA 与正常桌面 Chromium 身份不同。 +本规范第 6 至 9 节同步加入了只移除无头产品标记、保留实际版本与 Client Hints、覆盖主/备用引擎、 +并在诊断包及真实 Chromium 集成测试中核验页面实际指纹的契约。 + 只有用户在当前任务中明确点名要求修改滑块认证时,才允许触碰冻结范围。获得授权后也必须在同一个变更中: 1. 说明要改变本文哪一条冻结契约及原因。 diff --git a/frontend/components/Chat.tsx b/frontend/components/Chat.tsx index bdb574b..6f302e9 100644 --- a/frontend/components/Chat.tsx +++ b/frontend/components/Chat.tsx @@ -14,6 +14,20 @@ type SessionsByAccount = Record; const accountStorageKey = 'ydisks.chat.account.v1'; +const unreadLabel = (count: number): string => { + const normalized = Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0; + return normalized > 99 ? '99+' : String(normalized); +}; + +const UnreadBadge: React.FC<{ count: number; className?: string }> = ({ count, className = '' }) => { + if (!Number.isFinite(count) || count <= 0) return null; + return ( + + {unreadLabel(count)} + + ); +}; + const formatClock = (value: number): string => { if (!value) return ''; const date = new Date(value < 10_000_000_000 ? value * 1000 : value); @@ -64,10 +78,17 @@ const Chat: React.FC = () => { const reloadSessions = async (accountID: string) => { const page = await getChatSessionPage(accountID, undefined, undefined, true); - setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions })); + // The session list request can finish after markChatRead during a refresh. + // Keep the currently open conversation locally read so a stale response + // cannot resurrect its red badge. + const sessions = page.sessions.map(session => + accountID === activeAccountRef.current && session.chat_id === activeChatRef.current + ? { ...session, unread_count: 0 } + : session); + setSessionsByAccount(current => ({ ...current, [accountID]: sessions })); setContactCursors(current => ({ ...current, [accountID]: page.next_cursor })); setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more })); - return page.sessions; + return sessions; }; useEffect(() => { @@ -152,11 +173,18 @@ const Chat: React.FC = () => { return; } const controller = new AbortController(); + setSessionsByAccount(current => ({ + ...current, + [activeAccountID]: (current[activeAccountID] || []).map(session => + session.chat_id === activeChatID ? { ...session, unread_count: 0 } : session), + })); setMessagesLoading(true); - void Promise.all([ - getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }), - markChatRead(activeAccountID, activeChatID), - ]).then(([page]) => { + void getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }).then(page => { + const readMessages = page.messages + .filter(message => message.direction === 'incoming' && message.message_type !== 'system' && !message.message_key.startsWith('in-')) + .map(message => ({ messageId: message.message_key, sessionId: activeChatID, cid: `${activeChatID}@goofish`, conversationType: 1 } as any)); + console.info('[聊天已读] 打开会话上报', { accountID: activeAccountID, chatID: activeChatID, messageCount: readMessages.length, messageIds: readMessages.map(item => item.messageId) }); + void markChatRead(activeAccountID, activeChatID, readMessages); setMessages(page.messages); setHasOlder(page.has_more); setHistoryCursor(page.next_cursor); @@ -233,7 +261,7 @@ const Chat: React.FC = () => { ...row, last_message: message.content, last_message_at: message.sent_at, - unread_count: message.direction === 'incoming' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) + unread_count: message.direction === 'incoming' && message.message_type !== 'system' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count, } : row).sort((a, b) => b.last_message_at - a.last_message_at), }; @@ -244,7 +272,11 @@ const Chat: React.FC = () => { if (index >= 0) return current.map((item, i) => i === index ? message : item); return [...current, message]; }); - if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id); + if (message.direction === 'incoming' && message.message_type !== 'system') { + const readMessage = [{ messageId: message.message_key, sessionId: message.chat_id, cid: `${message.chat_id}@goofish`, conversationType: 1 } as any]; + console.info('[聊天已读] 收到实时消息上报', { accountID, chatID: message.chat_id, messageKey: message.message_key, messageType: message.message_type }); + void markChatRead(accountID, message.chat_id, readMessage); + } } } catch { // Ignore malformed non-chat frames and recover from authoritative REST state. @@ -388,7 +420,7 @@ const Chat: React.FC = () => { className={`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${active ? 'border-sky-500 text-sky-700' : 'border-transparent text-slate-500 hover:text-slate-900'}`}> {account.nickname || account.remark || account.id} - {unread > 0 && {unread > 99 ? '99+' : unread}} + ); })} @@ -434,7 +466,7 @@ const Chat: React.FC = () => {
{session.last_message || '暂无消息'} - {session.unread_count > 0 && {session.unread_count}} +
{session.item_title &&
商品 · {session.item_title}
} @@ -501,7 +533,7 @@ const Chat: React.FC = () => { )}
{messageTime(message.sent_at)} - {outgoing && (message.status === 'failed' ? : message.status === 'sent' ? : )} + {outgoing && (message.status === 'failed' ? : message.read_status === 2 ? : message.status === 'sent' ? : )}
{outgoing &&
diff --git a/frontend/services/api.test.ts b/frontend/services/api.test.ts index f294c24..7dd3ff7 100644 --- a/frontend/services/api.test.ts +++ b/frontend/services/api.test.ts @@ -70,7 +70,7 @@ test('chat APIs preserve account and conversation scope', async () => { expect(fetchMock.mock.calls[0][0]).toBe('/api/chat/sessions?account_id=a1'); expect(fetchMock.mock.calls[1][0]).toBe('/api/chat/messages?account_id=a1&chat_id=c1&before_id=9'); expect(JSON.parse(fetchMock.mock.calls[2][1].body)).toMatchObject({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1' }); - expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1' }); + expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1', message_ids: [] }); }); test('account task APIs keep rating and polish account-scoped', async () => { diff --git a/frontend/services/api.ts b/frontend/services/api.ts index 260df0f..9a9247c 100644 --- a/frontend/services/api.ts +++ b/frontend/services/api.ts @@ -148,8 +148,8 @@ export const sendChatImage = async (input: { return postForm('/api/chat/images', form, { timeoutMs: 120_000 }); }; -export const markChatRead = async (accountId: string, chatId: string): Promise => - post('/api/chat/read', { account_id: accountId, chat_id: chatId }); +export const markChatRead = async (accountId: string, chatId: string, messageIds: Array<{messageId: string; sessionId?: string; cid?: string; conversationType?: number}> = []): Promise => + post('/api/chat/read', { account_id: accountId, chat_id: chatId, message_ids: messageIds }); export interface AccountRuntimeStatus { state: NonNullable; diff --git a/frontend/types.ts b/frontend/types.ts index 3371cd6..76a052b 100644 --- a/frontend/types.ts +++ b/frontend/types.ts @@ -111,6 +111,8 @@ export interface ChatMessage { message_type: 'text' | 'image' | 'video' | 'system'; content: string; status: 'received' | 'sending' | 'sent' | 'failed'; + read_status?: number; + read_at?: number; sent_at: number; } diff --git a/internal/adapter/adapter.go b/internal/adapter/adapter.go index 5e6f8e2..e6b7f3e 100644 --- a/internal/adapter/adapter.go +++ b/internal/adapter/adapter.go @@ -22,6 +22,7 @@ import ( "xianyu-go/internal/renewal" "xianyu-go/internal/xianyu/cookierefresh" "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/protocol" xrenew "xianyu-go/internal/xianyu/renew" ) @@ -73,6 +74,17 @@ type Adapter struct { passwordMu sync.Mutex passwordProcessing map[string]struct{} + passwordInFlight map[string]*passwordRenewal +} + +// passwordRenewal represents the result shared by callers that observe the +// same account while its protocol-level credential renewal is running. A +// caller must wait for this result instead of treating the in-flight request +// as an immediate renewal failure; otherwise concurrent API requests turn one +// recoverable expiry into a burst of 502 responses. +type passwordRenewal struct { + done chan struct{} + success bool } // notifyNotifier 是 *notify.Notifier 的最小接口,避免 adapter 直接依赖 notify 包 @@ -99,6 +111,7 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter { captchaReq: mtop.NewClient(), orderMTop: mtop.NewClient(), passwordProcessing: make(map[string]struct{}), + passwordInFlight: make(map[string]*passwordRenewal), } } @@ -140,13 +153,19 @@ func (a *Adapter) HandleChatMessage(ctx context.Context, message engine.ChatMess // Xianyu echoes messages sent by this account back over the same WS. Those // sends are already captured by HandleOutgoingChatMessage; recording the // echo as incoming would put our own bubble on the buyer side and duplicate it. - if strings.TrimSuffix(message.SenderUserID, "@goofish") == strings.TrimSuffix(message.AccountID, "@goofish") { + if selfID := protocol.TransCookies(message.CookieStr)["unb"]; selfID != "" && + strings.TrimSuffix(strings.TrimSpace(message.SenderUserID), "@goofish") == strings.TrimSuffix(strings.TrimSpace(selfID), "@goofish") { + a.logger.Info("忽略账号自身发送的聊天回显", "account", message.AccountID, "chat_id", message.ChatID, "sender_id", message.SenderUserID) return nil } - _, _, err := a.chat.RecordIncoming(ctx, chat.Incoming{ + stored, inserted, err := a.chat.RecordIncoming(ctx, chat.Incoming{ AccountID: message.AccountID, ChatID: message.ChatID, BuyerID: message.SenderUserID, - BuyerName: message.SenderName, Text: message.Text, ItemID: message.ItemID, Raw: message.Raw, + BuyerName: message.SenderName, Text: message.Text, MessageID: message.MessageID, ItemID: message.ItemID, Raw: message.Raw, }) + if stored != nil { + a.logger.Info("实时聊天消息已入库", "account", message.AccountID, "chat_id", message.ChatID, + "message_key", stored.MessageKey, "message_type", stored.MessageType, "inserted", inserted) + } return err } @@ -161,6 +180,21 @@ func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine. return err } +func (a *Adapter) HandleMessageRead(ctx context.Context, event engine.MessageReadEvent) error { + if a.chat == nil { + return nil + } + message, err := a.chat.MarkOutgoingRead(ctx, event.AccountID, event.MessageID, event.ReadAt) + if errors.Is(err, db.ErrNotFound) && event.ChatID != "" { + message, err = a.chat.MarkLatestOutgoingRead(ctx, event.AccountID, event.ChatID, event.ReadAt) + } + if err == nil && message != nil { + a.logger.Info("聊天出站消息已标记已读", "account", event.AccountID, "chat_id", event.ChatID, + "message_id", event.MessageID, "message_key", message.MessageKey, "read_status", message.ReadStatus) + } + return err +} + // OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器, // 推送到该账号已绑定的通知渠道。 func (a *Adapter) OnAccountAlert(ctx context.Context, cookieID, level, title, body string) { @@ -498,10 +532,11 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b return false } if !a.beginPasswordLogin(cookieID) { - a.logger.Warn("协议续期已在处理中", "account", cookieID) - return false + a.logger.Warn("协议续期已在处理中,等待当前结果", "account", cookieID) + return a.waitPasswordLogin(ctx, cookieID) } - defer a.finishPasswordLogin(cookieID) + renewed := false + defer func() { a.finishPasswordLoginResult(cookieID, renewed) }() d, err := a.store.Cookies.GetDetails(ctx, cookieID) if err != nil { @@ -551,13 +586,41 @@ func (a *Adapter) beginPasswordLogin(cookieID string) bool { return false } a.passwordProcessing[cookieID] = struct{}{} + if a.passwordInFlight == nil { + a.passwordInFlight = make(map[string]*passwordRenewal) + } + a.passwordInFlight[cookieID] = &passwordRenewal{done: make(chan struct{})} return true } func (a *Adapter) finishPasswordLogin(cookieID string) { + a.finishPasswordLoginResult(cookieID, false) +} + +func (a *Adapter) finishPasswordLoginResult(cookieID string, success bool) { a.passwordMu.Lock() defer a.passwordMu.Unlock() delete(a.passwordProcessing, cookieID) + if state := a.passwordInFlight[cookieID]; state != nil { + state.success = success + delete(a.passwordInFlight, cookieID) + close(state.done) + } +} + +func (a *Adapter) waitPasswordLogin(ctx context.Context, cookieID string) bool { + a.passwordMu.Lock() + state := a.passwordInFlight[cookieID] + a.passwordMu.Unlock() + if state == nil { + return false + } + select { + case <-state.done: + return state.success + case <-ctx.Done(): + return false + } } func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, userID int64, status, failureReason, message string) { @@ -677,6 +740,16 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDe a.logger.Info("Go 协议续期成功", "account", d.ID) return true, nil } + if err == nil { + message := strings.TrimSpace(res.Message) + if message == "" { + message = "协议续期未通过" + } + return false, errors.New(message) + } + } + if err == nil { + err = errors.New("协议续期未返回结果") } return false, err } diff --git a/internal/adapter/adapter_test.go b/internal/adapter/adapter_test.go index f81a2d2..4ffc957 100644 --- a/internal/adapter/adapter_test.go +++ b/internal/adapter/adapter_test.go @@ -505,6 +505,35 @@ func TestOnPasswordLoginRefreshWaitsForPendingFinalResult(t *testing.T) { } } +func TestOnPasswordLoginRefreshConcurrentCallersShareResult(t *testing.T) { + store, cleanup := newAdapterTestStore(t) + defer cleanup() + renewal.GlobalCooldown.Reset("cid") + if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; havana_lgc_exp=9999999999999"); err != nil { + t.Fatal(err) + } + started := make(chan struct{}) + var once sync.Once + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + once.Do(func() { close(started) }) + time.Sleep(60 * time.Millisecond) + _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`)) + })) + defer srv.Close() + a := New(store, nil, nil) + a.SetRenewService(xrenew.Service{ + HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, + RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond, + }) + first := make(chan bool, 1) + go func() { first <- a.OnPasswordLoginRefresh(context.Background(), "cid") }() + <-started + second := a.OnPasswordLoginRefresh(context.Background(), "cid") + if got := <-first; !got || !second { + t.Fatalf("并发续期调用应共享成功结果: first=%v second=%v", got, second) + } +} + // TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure 接口轻量续期也失败后才因浏览器不可用失败。 func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing.T) { store, cleanup := newAdapterTestStore(t) diff --git a/internal/browser/cookierenew.go b/internal/browser/cookierenew.go index 4fba922..d2f814a 100644 --- a/internal/browser/cookierenew.go +++ b/internal/browser/cookierenew.go @@ -66,7 +66,7 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us var bctx playwright.BrowserContext var lastErr error for attempt := 1; attempt <= 2; attempt++ { - bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless)) + bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless, m.headlessUserAgent())) if err == nil { break } @@ -87,8 +87,8 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us return bctx, release, nil } -func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunchPersistentContextOptions { - return playwright.BrowserTypeLaunchPersistentContextOptions{ +func passwordPersistentContextOptions(headless bool, headlessUserAgent ...*string) playwright.BrowserTypeLaunchPersistentContextOptions { + options := playwright.BrowserTypeLaunchPersistentContextOptions{ Headless: playwright.Bool(headless), Args: chromiumLaunchArgs(), ExecutablePath: chromiumExecutablePath(), @@ -102,6 +102,10 @@ func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunc }, Timeout: playwright.Float(quickRenewTimeoutMS), } + if headless && len(headlessUserAgent) > 0 { + options.UserAgent = headlessUserAgent[0] + } + return options } // BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。 @@ -121,13 +125,14 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki // 解释,避免漏掉或错误映射 Path=/im 的连接凭证。 effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL) - bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, quickRenewHeadless(headless)) + headless = quickRenewHeadless(headless) + bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, headless) if err != nil { return "", nil, err } defer release() - page, err := bctx.NewPage() + page, err := m.newBrowserPage(bctx, headless) if err != nil { return "", nil, fmt.Errorf("新建 page 失败: %w", err) } @@ -180,13 +185,14 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt return "", nil, false, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期") } effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL) - bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, cookiesRefreshHeadless(headless)) + headless = cookiesRefreshHeadless(headless) + bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, headless) if err != nil { return "", nil, false, err } defer release() - page, err := bctx.NewPage() + page, err := m.newBrowserPage(bctx, headless) if err != nil { return "", nil, false, fmt.Errorf("新建 page 失败: %w", err) } @@ -478,7 +484,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki var bctx playwright.BrowserContext var lastErr error for attempt := 1; attempt <= 2; attempt++ { - bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{ + options := playwright.BrowserTypeLaunchPersistentContextOptions{ Headless: playwright.Bool(headless), Args: chromiumLaunchArgs(), ExecutablePath: chromiumExecutablePath(), @@ -486,7 +492,11 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki Locale: playwright.String(defaultLang), TimezoneId: playwright.String(defaultTZ), Timeout: playwright.Float(quickRenewTimeoutMS), - }) + } + if headless { + options.UserAgent = m.headlessUserAgent() + } + bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, options) if err == nil { break } diff --git a/internal/browser/headless_fingerprint_integration_test.go b/internal/browser/headless_fingerprint_integration_test.go new file mode 100644 index 0000000..090600b --- /dev/null +++ b/internal/browser/headless_fingerprint_integration_test.go @@ -0,0 +1,150 @@ +package browser + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "strings" + "testing" + "time" + + "github.com/mxschmitt/playwright-go" +) + +func TestHeadlessFingerprintBrowserIntegration(t *testing.T) { + if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" { + t.Skip("set RUN_BROWSER_INTEGRATION=1 to verify the effective headless browser fingerprint") + } + + requests := make(chan http.Header, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/fingerprint" { + requests <- r.Header.Clone() + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, _ = io.WriteString(w, "fingerprint") + })) + defer server.Close() + + m := NewManager(nil) + defer m.Close() + if err := m.init(); err != nil { + t.Fatal(err) + } + userAgent := m.headlessUserAgent() + if userAgent == nil { + t.Fatal("初始化后无头 UA 为空") + } + + t.Run("playwright-context", func(t *testing.T) { + browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{ + Headless: playwright.Bool(true), + Args: chromiumLaunchArgs(), + ExecutablePath: chromiumExecutablePath(), + }) + if err != nil { + t.Fatal(err) + } + defer func() { _ = browser.Close() }() + bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{UserAgent: userAgent}) + if err != nil { + t.Fatal(err) + } + defer func() { _ = bctx.Close() }() + page, err := m.newBrowserPage(bctx, true) + if err != nil { + t.Fatal(err) + } + verifyEffectiveHeadlessFingerprint(t, page, server.URL+"/fingerprint", requests, *userAgent) + }) + + t.Run("direct-cdp-context", func(t *testing.T) { + profileDir := t.TempDir() + executable := m.pw.Chromium.ExecutablePath() + if configured := chromiumExecutablePath(); configured != nil { + executable = *configured + } + cmd := exec.Command(executable, fallbackChromiumArgs(profileDir, true, userAgent)...) + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + processDone := make(chan error, 1) + go func() { processDone <- cmd.Wait() }() + defer func() { + if cmd.Process != nil { + _ = cmd.Process.Kill() + } + select { + case <-processDone: + case <-time.After(2 * time.Second): + } + }() + + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + endpoint, err := waitForDevToolsEndpoint(ctx, profileDir, processDone, 10*time.Second) + if err != nil { + t.Fatal(err) + } + browser, err := m.pw.Chromium.ConnectOverCDP(endpoint) + if err != nil { + t.Fatal(err) + } + defer func() { _ = browser.Close() }() + contexts := browser.Contexts() + if len(contexts) == 0 { + t.Fatal("直接 CDP 浏览器无默认 context") + } + page, err := m.newBrowserPage(contexts[0], true) + if err != nil { + t.Fatal(err) + } + verifyEffectiveHeadlessFingerprint(t, page, server.URL+"/fingerprint", requests, *userAgent) + }) +} + +func verifyEffectiveHeadlessFingerprint(t *testing.T, page playwright.Page, target string, requests <-chan http.Header, expectedUserAgent string) { + t.Helper() + if _, err := page.Goto(target, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil { + t.Fatal(err) + } + var headers http.Header + select { + case headers = <-requests: + case <-time.After(5 * time.Second): + t.Fatal("等待浏览器指纹请求超时") + } + pageIdentity, err := page.Evaluate(`() => ({ + userAgent: navigator.userAgent, + userAgentData: navigator.userAgentData ? navigator.userAgentData.toJSON() : null + })`) + if err != nil { + t.Fatal(err) + } + t.Logf("effective user-agent=%q sec-ch-ua=%q page=%v", headers.Get("User-Agent"), headers.Get("Sec-CH-UA"), pageIdentity) + for source, value := range map[string]string{ + "http-user-agent": headers.Get("User-Agent"), + "http-sec-ch-ua": headers.Get("Sec-CH-UA"), + "page-identity": fmt.Sprint(pageIdentity), + } { + if strings.Contains(strings.ToLower(value), "headless") { + t.Fatalf("%s 仍暴露 headless 标记: %s", source, value) + } + } + if !strings.Contains(headers.Get("User-Agent"), "Chrome/") { + t.Fatalf("HTTP UA 缺少 Chrome 版本: %q", headers.Get("User-Agent")) + } + if headers.Get("User-Agent") != expectedUserAgent { + t.Fatalf("HTTP UA 与实测 Chromium 版本不一致: got %q want %q", headers.Get("User-Agent"), expectedUserAgent) + } + identity, ok := pageIdentity.(map[string]any) + if !ok || identity["userAgent"] != expectedUserAgent { + t.Fatalf("navigator.userAgent 与实测 Chromium 版本不一致: %#v", pageIdentity) + } +} diff --git a/internal/browser/lifecycle.go b/internal/browser/lifecycle.go index cac268a..d53c276 100644 --- a/internal/browser/lifecycle.go +++ b/internal/browser/lifecycle.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "runtime" + "strconv" "strings" "sync" "time" @@ -35,13 +36,30 @@ const ( // chromiumLaunchArgs 统一 Chromium 启动参数。 func chromiumLaunchArgs() []string { - return []string{ + args := []string{ "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-blink-features=AutomationControlled", "--lang=zh-CN", } + if captchaIgnoreCertificateErrors() { + args = append(args, "--ignore-certificate-errors") + } + return args +} + +// captchaIgnoreCertificateErrors is an explicit escape hatch for environments +// whose TLS inspection proxy replaces Alibaba's certificate chain. It is off +// by default; enabling it is limited to the browser process so the HTTP +// clients and stored credentials keep their normal certificate validation. +func captchaIgnoreCertificateErrors() bool { + value := strings.TrimSpace(os.Getenv("CAPTCHA_IGNORE_CERT_ERRORS")) + if value == "" { + return false + } + parsed, err := strconv.ParseBool(value) + return err == nil && parsed } func chromiumExecutablePath() *string { @@ -107,6 +125,13 @@ type Manager struct { pw *playwright.Playwright logger *slog.Logger + // browserFingerprint is observed from the bundled Chromium once during + // initialization. Headless contexts use the same identity with only the + // HeadlessChrome product token removed; headed contexts keep Chromium's + // native identity. + browserFingerprint xianyu.BrowserFingerprint + userAgentMetadata map[string]any + once sync.Once initErr error installed bool @@ -264,13 +289,185 @@ func (m *Manager) detectBrowserFingerprint() error { if strings.TrimSpace(headers.Get("User-Agent")) == "" { return fmt.Errorf("Chromium 返回空 userAgent") } - xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{ + metadata, err := readUserAgentMetadata(page) + if err != nil { + return fmt.Errorf("读取 Chromium User-Agent Client Hints 失败: %w", err) + } + fingerprint := normalizeBrowserFingerprint(xianyu.BrowserFingerprint{ UserAgent: headers.Get("User-Agent"), SecChUA: headers.Get("sec-ch-ua"), Platform: strings.Trim(headers.Get("sec-ch-ua-platform"), `"`), Mobile: headers.Get("sec-ch-ua-mobile"), }) - m.logger.Info("已读取 Playwright Chromium 原生指纹", "browser_version", b.Version(), "user_agent", headers.Get("User-Agent")) + m.browserFingerprint = fingerprint + m.userAgentMetadata = normalizeUserAgentMetadata(metadata) + xianyu.SetBrowserFingerprint(fingerprint) + m.logger.Info("已读取 Playwright Chromium 浏览器指纹", "browser_version", b.Version(), "user_agent", fingerprint.UserAgent, "headless_token_removed", fingerprint.UserAgent != headers.Get("User-Agent")) + return nil +} + +// normalizeBrowserFingerprint removes the product marker that Chromium adds to +// its legacy UA string in headless mode. It intentionally preserves the +// browser version and all Client Hints observed from the same runtime. +func normalizeBrowserFingerprint(fingerprint xianyu.BrowserFingerprint) xianyu.BrowserFingerprint { + fingerprint.UserAgent = normalizeHeadlessUserAgent(fingerprint.UserAgent) + fingerprint.SecChUA = normalizeSecChUA(fingerprint.SecChUA) + return fingerprint +} + +func normalizeHeadlessUserAgent(userAgent string) string { + return strings.ReplaceAll(strings.TrimSpace(userAgent), "HeadlessChrome/", "Chrome/") +} + +func normalizeSecChUA(value string) string { + parts := strings.Split(value, ",") + result := make([]string, 0, len(parts)) + seen := make(map[string]struct{}, len(parts)) + for _, part := range parts { + part = strings.TrimSpace(strings.ReplaceAll(part, "HeadlessChrome", "Chromium")) + if part == "" { + continue + } + brand := part + if index := strings.IndexByte(brand, ';'); index >= 0 { + brand = strings.TrimSpace(brand[:index]) + } + if _, exists := seen[brand]; exists { + continue + } + seen[brand] = struct{}{} + result = append(result, part) + } + return strings.Join(result, ", ") +} + +func readUserAgentMetadata(page playwright.Page) (map[string]any, error) { + value, err := page.Evaluate(`async () => { + const data = navigator.userAgentData; + if (!data) return null; + const high = await data.getHighEntropyValues([ + 'architecture', 'bitness', 'fullVersionList', 'model', 'platformVersion', 'wow64' + ]); + return { + brands: data.brands, + fullVersionList: high.fullVersionList, + platform: data.platform, + platformVersion: high.platformVersion, + architecture: high.architecture, + model: high.model, + mobile: data.mobile, + bitness: high.bitness, + wow64: high.wow64 + }; + }`) + if err != nil { + return nil, err + } + if value == nil { + return nil, fmt.Errorf("navigator.userAgentData 不可用") + } + metadata, ok := value.(map[string]any) + if !ok { + return nil, fmt.Errorf("navigator.userAgentData 类型异常: %T", value) + } + return metadata, nil +} + +func normalizeUserAgentMetadata(metadata map[string]any) map[string]any { + if len(metadata) == 0 { + return nil + } + result := make(map[string]any, len(metadata)) + for key, value := range metadata { + switch key { + case "brands", "fullVersionList": + result[key] = normalizeUserAgentBrands(value) + default: + result[key] = value + } + } + return result +} + +func normalizeUserAgentBrands(value any) []any { + brands, ok := value.([]any) + if !ok { + return nil + } + result := make([]any, 0, len(brands)) + seen := make(map[string]struct{}, len(brands)) + for _, item := range brands { + brandEntry, ok := item.(map[string]any) + if !ok { + continue + } + brand, _ := brandEntry["brand"].(string) + brand = strings.ReplaceAll(brand, "HeadlessChrome", "Chromium") + if brand == "" { + continue + } + if _, exists := seen[brand]; exists { + continue + } + seen[brand] = struct{}{} + entry := make(map[string]any, len(brandEntry)) + for key, itemValue := range brandEntry { + entry[key] = itemValue + } + entry["brand"] = brand + result = append(result, entry) + } + return result +} + +func (m *Manager) headlessUserAgent() *string { + userAgent := normalizeHeadlessUserAgent(m.browserFingerprint.UserAgent) + if userAgent == "" { + userAgent = normalizeHeadlessUserAgent(xianyu.CurrentBrowserFingerprint().UserAgent) + } + if userAgent == "" { + return nil + } + return playwright.String(userAgent) +} + +func (m *Manager) newBrowserPage(bctx playwright.BrowserContext, headless bool) (playwright.Page, error) { + page, err := bctx.NewPage() + if err != nil { + return nil, err + } + if !headless { + return page, nil + } + if err := m.applyHeadlessFingerprint(page); err != nil { + _ = page.Close() + return nil, err + } + return page, nil +} + +func (m *Manager) applyHeadlessFingerprint(page playwright.Page) error { + userAgent := m.headlessUserAgent() + if userAgent == nil { + return fmt.Errorf("无头 Chromium User-Agent 未初始化") + } + metadata := normalizeUserAgentMetadata(m.userAgentMetadata) + if len(metadata) == 0 { + return fmt.Errorf("无头 Chromium User-Agent Client Hints 未初始化") + } + session, err := page.Context().NewCDPSession(page) + if err != nil { + return fmt.Errorf("创建 Chromium 指纹 CDP 会话: %w", err) + } + if _, err := session.Send("Emulation.setUserAgentOverride", map[string]any{ + "userAgent": *userAgent, + "userAgentMetadata": metadata, + }); err != nil { + _ = session.Detach() + return fmt.Errorf("应用 Chromium 无头指纹: %w", err) + } + // Keep the session attached for the page lifetime. Chromium reverts + // navigator.userAgentData when this target-scoped emulation session detaches. return nil } @@ -303,7 +500,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl if err != nil { return nil, nil, err } - page, err := entry.context.NewPage() + page, err := m.newBrowserPage(entry.context, headless) if err != nil { // context 损坏,丢弃重建一次。 m.releaseEntry(cookieID, entry) @@ -312,7 +509,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl if err != nil { return nil, nil, err } - page, err = entry.context.NewPage() + page, err = m.newBrowserPage(entry.context, headless) if err != nil { m.releaseEntry(cookieID, entry) m.evict(cookieID) @@ -394,11 +591,15 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE if err != nil { return nil, fmt.Errorf("启动 chromium 失败: %w", err) } - context, err := browser.NewContext(playwright.BrowserNewContextOptions{ + contextOptions := playwright.BrowserNewContextOptions{ Viewport: &playwright.Size{Width: defaultW, Height: defaultH}, Locale: playwright.String(defaultLang), TimezoneId: playwright.String(defaultTZ), - }) + } + if headless { + contextOptions.UserAgent = m.headlessUserAgent() + } + context, err := browser.NewContext(contextOptions) if err != nil { _ = browser.Close() return nil, fmt.Errorf("创建 context 失败: %w", err) diff --git a/internal/browser/passwordlogin.go b/internal/browser/passwordlogin.go index 136004e..fb58834 100644 --- a/internal/browser/passwordlogin.go +++ b/internal/browser/passwordlogin.go @@ -64,7 +64,7 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID } defer release() - page, err := bctx.NewPage() + page, err := m.newBrowserPage(bctx, headless) if err != nil { return nil, fmt.Errorf("新建 page 失败: %w", err) } diff --git a/internal/browser/passwordlogin_detect_test.go b/internal/browser/passwordlogin_detect_test.go index 1bd9227..4c5b2b8 100644 --- a/internal/browser/passwordlogin_detect_test.go +++ b/internal/browser/passwordlogin_detect_test.go @@ -79,12 +79,13 @@ func TestPasswordLoginReferenceProfileAndTiming(t *testing.T) { func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) { t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "/opt/chromium") - opts := passwordPersistentContextOptions(true) + userAgent := "Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36" + opts := passwordPersistentContextOptions(true, &userAgent) if opts.Headless == nil || !*opts.Headless { t.Fatal("密码登录应按调用参数使用无头模式") } - if opts.UserAgent != nil { - t.Fatalf("密码登录不应覆盖 Playwright Chromium 原生 UA: %v", *opts.UserAgent) + if opts.UserAgent == nil || *opts.UserAgent != userAgent { + t.Fatalf("无头密码登录应使用去除 HeadlessChrome 的运行时 UA: %v", opts.UserAgent) } if opts.Viewport == nil || opts.Viewport.Width != 1980 || opts.Viewport.Height != 1024 { t.Fatalf("密码登录 viewport=%+v", opts.Viewport) @@ -104,6 +105,10 @@ func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) { if opts.ExecutablePath == nil || *opts.ExecutablePath != "/opt/chromium" { t.Fatalf("Chromium 路径=%v", opts.ExecutablePath) } + headed := passwordPersistentContextOptions(false, &userAgent) + if headed.UserAgent != nil { + t.Fatalf("有头密码登录应保留 Chromium 原生 UA: %v", headed.UserAgent) + } } func TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit(t *testing.T) { diff --git a/internal/browser/pure_extra_test.go b/internal/browser/pure_extra_test.go index 4d25ec9..ee0a82d 100644 --- a/internal/browser/pure_extra_test.go +++ b/internal/browser/pure_extra_test.go @@ -1,6 +1,12 @@ package browser -import "testing" +import ( + "fmt" + "strings" + "testing" + + "xianyu-go/internal/xianyu" +) // TestSanitize 特殊字符替换为下划线(用于 userDataDir 命名)。 func TestSanitize(t *testing.T) { @@ -95,6 +101,77 @@ func TestChromiumExecutablePathFromEnv(t *testing.T) { } } +func TestCaptchaIgnoreCertificateErrors(t *testing.T) { + t.Setenv("CAPTCHA_IGNORE_CERT_ERRORS", "") + if captchaIgnoreCertificateErrors() { + t.Fatal("默认不应忽略证书错误") + } + t.Setenv("CAPTCHA_IGNORE_CERT_ERRORS", "true") + if !captchaIgnoreCertificateErrors() { + t.Fatal("true 应启用 CAPTCHA 证书错误忽略开关") + } + t.Setenv("CAPTCHA_IGNORE_CERT_ERRORS", "not-a-bool") + if captchaIgnoreCertificateErrors() { + t.Fatal("无效值不应启用证书错误忽略开关") + } +} + +func TestNormalizeBrowserFingerprintRemovesOnlyHeadlessMarker(t *testing.T) { + fingerprint := normalizeBrowserFingerprint(xianyu.BrowserFingerprint{ + UserAgent: " Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36 ", + SecChUA: `"HeadlessChrome";v="149", "Chromium";v="149"`, + Platform: "macOS", + Mobile: "?0", + }) + if strings.Contains(fingerprint.UserAgent, "HeadlessChrome") || strings.Contains(fingerprint.SecChUA, "HeadlessChrome") { + t.Fatalf("无头标记未清除: %+v", fingerprint) + } + if !strings.Contains(fingerprint.UserAgent, "Chrome/149.0.7827.55") { + t.Fatalf("Chromium 版本不应变化: %q", fingerprint.UserAgent) + } + if fingerprint.Platform != "macOS" || fingerprint.Mobile != "?0" { + t.Fatalf("非无头字段不应变化: %+v", fingerprint) + } + if strings.Count(fingerprint.SecChUA, `"Chromium"`) != 1 { + t.Fatalf("Client Hints 品牌应去重: %q", fingerprint.SecChUA) + } +} + +func TestNormalizeUserAgentMetadataRemovesAndDeduplicatesHeadlessBrand(t *testing.T) { + metadata := normalizeUserAgentMetadata(map[string]any{ + "brands": []any{ + map[string]any{"brand": "HeadlessChrome", "version": "149"}, + map[string]any{"brand": "Chromium", "version": "149"}, + map[string]any{"brand": "Not)A;Brand", "version": "24"}, + }, + "fullVersionList": []any{ + map[string]any{"brand": "HeadlessChrome", "version": "149.0.7827.55"}, + map[string]any{"brand": "Chromium", "version": "149.0.7827.55"}, + }, + "platform": "macOS", + "mobile": false, + }) + if strings.Contains(strings.ToLower(fmt.Sprint(metadata)), "headless") { + t.Fatalf("User-Agent metadata 仍暴露 headless: %#v", metadata) + } + brands, ok := metadata["brands"].([]any) + if !ok || len(brands) != 2 { + t.Fatalf("brands 未正确去重: %#v", metadata["brands"]) + } + fullVersions, ok := metadata["fullVersionList"].([]any) + if !ok || len(fullVersions) != 1 { + t.Fatalf("fullVersionList 未正确去重: %#v", metadata["fullVersionList"]) + } +} + +func TestManagerHeadlessUserAgentUsesDetectedRuntimeVersion(t *testing.T) { + m := &Manager{browserFingerprint: xianyu.BrowserFingerprint{UserAgent: "Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36"}} + userAgent := m.headlessUserAgent() + if userAgent == nil || *userAgent != "Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36" { + t.Fatalf("headlessUserAgent=%v", userAgent) + } +} + func TestSkipPlaywrightBrowserDownloadFromEnv(t *testing.T) { t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "") if skipPlaywrightBrowserDownload() { diff --git a/internal/browser/qrrefresh.go b/internal/browser/qrrefresh.go index ae3e2e9..63231dc 100644 --- a/internal/browser/qrrefresh.go +++ b/internal/browser/qrrefresh.go @@ -39,6 +39,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU Viewport: &playwright.Size{Width: 1100, Height: 760}, Locale: playwright.String(defaultLang), TimezoneId: playwright.String(defaultTZ), + UserAgent: m.headlessUserAgent(), }) if err != nil { return "", "", fmt.Errorf("创建 context 失败: %w", err) @@ -52,7 +53,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU return "", "", fmt.Errorf("注入临时 cookie 失败: %w", err) } - page, err := bctx.NewPage() + page, err := m.newBrowserPage(bctx, true) if err != nil { return "", "", fmt.Errorf("新建 page 失败: %w", err) } diff --git a/internal/browser/token_captcha.go b/internal/browser/token_captcha.go index ccba55a..2c972d9 100644 --- a/internal/browser/token_captcha.go +++ b/internal/browser/token_captcha.go @@ -174,7 +174,7 @@ func (m *Manager) TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, c ) } -func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (string, error) { +func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (result string, resultErr error) { if strings.TrimSpace(cookieStr) == "" { return "", fmt.Errorf("Cookie为空,无法处理 token 风控验证") } @@ -183,7 +183,8 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c } currentCookies := cookieStr - bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, currentCookies, nil, quickRenewHeadless(headless), true) + headless = quickRenewHeadless(headless) + bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, currentCookies, nil, headless, true) if err != nil { return "", err } @@ -196,11 +197,18 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c } previousX5SecValues := x5SecValues(beforeCookies) - page, err := bctx.NewPage() + page, err := m.newBrowserPage(bctx, headless) if err != nil { return "", fmt.Errorf("新建 page 失败: %w", err) } defer func() { _ = page.Close() }() + diagnostic := newTokenCaptchaDiagnostic(cookieID, "playwright", verificationURL, page, m.logger) + diagnosticSucceeded := false + defer func() { + if diagnostic != nil && !diagnosticSucceeded { + diagnostic.capture(page, "playwright_failed", resultErr) + } + }() if time.Now().After(browserDeadline) { return "", fmt.Errorf("token 风控浏览器验证超过 %s", tokenCaptchaBrowserTTL) @@ -230,6 +238,9 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c m.logger.Warn("token 风控页面没有可验证滑块,停止自动验证", "cookieID", cookieID, "err", pageErr) return "", pageErr } + if diagnostic != nil { + diagnostic.snapshotInitial(page) + } scratch := isScratchCaptcha(content) if err := solveSliderStrict(page, scratch, m.logger, previousX5SecValues, browserDeadline); err != nil { @@ -245,6 +256,7 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c merged[k] = v } m.logger.Info("token风控验证成功", "cookieID", cookieID, "x5_cookie_count", len(x5)) + diagnosticSucceeded = true return cookieMarshal(merged), nil } diff --git a/internal/browser/token_captcha_diagnostic.go b/internal/browser/token_captcha_diagnostic.go new file mode 100644 index 0000000..823ad85 --- /dev/null +++ b/internal/browser/token_captcha_diagnostic.go @@ -0,0 +1,558 @@ +package browser + +// Token CAPTCHA diagnostics are deliberately opt-in. They collect enough +// information to distinguish a page/DOM change from a server-side rejection, +// without changing the frozen slider implementation or writing credentials to +// the normal application log. + +import ( + "archive/zip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "log/slog" + "net/url" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "sync" + "time" + + "github.com/mxschmitt/playwright-go" + + "xianyu-go/internal/logsafe" +) + +const ( + tokenCaptchaDiagnosticDirEnv = "CAPTCHA_DIAGNOSTIC_DIR" + tokenCaptchaDiagnosticSensitiveEnv = "CAPTCHA_DIAGNOSTIC_INCLUDE_SENSITIVE" + tokenCaptchaDiagnosticMaxEvents = 500 +) + +type tokenCaptchaDiagnostic struct { + cookieID string + engine string + requestedURL string + includeSensitive bool + dir string + startedAt time.Time + logger *slog.Logger + + mu sync.Mutex + requests []tokenCaptchaDiagnosticNetworkEvent + responses []tokenCaptchaDiagnosticNetworkEvent + console []tokenCaptchaDiagnosticConsoleEvent + pageError []string + initial tokenCaptchaDiagnosticSnapshot + once sync.Once +} + +type tokenCaptchaDiagnosticSnapshot struct { + CapturedAt string + PageHTML string + Screenshot []byte + FrameHTML map[int]string + Frames []tokenCaptchaDiagnosticFrame + Selectors []tokenCaptchaDiagnosticSelector +} + +type tokenCaptchaDiagnosticNetworkEvent struct { + Kind string `json:"kind"` + At string `json:"at"` + URL string `json:"url"` + Method string `json:"method,omitempty"` + ResourceType string `json:"resource_type,omitempty"` + Navigation bool `json:"navigation,omitempty"` + Status int `json:"status,omitempty"` + ContentType string `json:"content_type,omitempty"` + Failure string `json:"failure,omitempty"` +} + +type tokenCaptchaDiagnosticConsoleEvent struct { + At string `json:"at"` + Type string `json:"type"` + Text string `json:"text"` +} + +type tokenCaptchaDiagnosticFrame struct { + Index int `json:"index"` + Name string `json:"name,omitempty"` + URL string `json:"url"` + ParentURL string `json:"parent_url,omitempty"` + HTMLBytes int `json:"html_bytes,omitempty"` + ContentErr string `json:"content_error,omitempty"` +} + +type tokenCaptchaDiagnosticSelector struct { + FrameIndex int `json:"frame_index"` + FrameURL string `json:"frame_url"` + Selector string `json:"selector"` + Found bool `json:"found"` + Visible bool `json:"visible,omitempty"` + Box string `json:"box,omitempty"` + Error string `json:"error,omitempty"` +} + +type tokenCaptchaDiagnosticManifest struct { + Version int `json:"version"` + CreatedAt string `json:"created_at"` + CookieIDHash string `json:"cookie_id_hash"` + Engine string `json:"engine"` + Phase string `json:"phase"` + Cause string `json:"cause,omitempty"` + RequestedURL string `json:"requested_url"` + CurrentURL string `json:"current_url"` + Title string `json:"title,omitempty"` + IncludeSensitive bool `json:"include_sensitive"` + PageState map[string]any `json:"page_state,omitempty"` + Frames []tokenCaptchaDiagnosticFrame `json:"frames,omitempty"` + Selectors []tokenCaptchaDiagnosticSelector `json:"selectors,omitempty"` + InitialCapturedAt string `json:"initial_captured_at,omitempty"` + InitialFrames []tokenCaptchaDiagnosticFrame `json:"initial_frames,omitempty"` + InitialSelectors []tokenCaptchaDiagnosticSelector `json:"initial_selectors,omitempty"` + Requests []tokenCaptchaDiagnosticNetworkEvent `json:"requests,omitempty"` + Responses []tokenCaptchaDiagnosticNetworkEvent `json:"responses,omitempty"` + Console []tokenCaptchaDiagnosticConsoleEvent `json:"console,omitempty"` + PageErrors []string `json:"page_errors,omitempty"` +} + +func newTokenCaptchaDiagnostic(cookieID, engine, requestedURL string, page playwright.Page, logger *slog.Logger) *tokenCaptchaDiagnostic { + dir := strings.TrimSpace(os.Getenv(tokenCaptchaDiagnosticDirEnv)) + if dir == "" || page == nil { + return nil + } + d := &tokenCaptchaDiagnostic{ + cookieID: cookieID, + engine: engine, + requestedURL: requestedURL, + includeSensitive: diagnosticBoolEnv(tokenCaptchaDiagnosticSensitiveEnv), + dir: dir, + startedAt: time.Now().UTC(), + logger: logger, + } + page.OnRequest(func(request playwright.Request) { + d.recordRequest(request) + }) + page.OnResponse(func(response playwright.Response) { + d.recordResponse(response) + }) + page.OnRequestFailed(func(request playwright.Request) { + d.mu.Lock() + defer d.mu.Unlock() + if len(d.responses) >= tokenCaptchaDiagnosticMaxEvents { + return + } + failure := "" + if err := request.Failure(); err != nil { + failure = err.Error() + } + d.responses = append(d.responses, tokenCaptchaDiagnosticNetworkEvent{ + Kind: "request_failed", + At: time.Now().UTC().Format(time.RFC3339Nano), + URL: d.safeURL(request.URL()), + Method: request.Method(), + ResourceType: request.ResourceType(), + Navigation: request.IsNavigationRequest(), + Failure: failure, + }) + }) + page.OnConsole(func(message playwright.ConsoleMessage) { + d.mu.Lock() + defer d.mu.Unlock() + if len(d.console) >= tokenCaptchaDiagnosticMaxEvents { + return + } + text := message.Text() + if !d.includeSensitive { + text = redactDiagnosticText(text) + } + d.console = append(d.console, tokenCaptchaDiagnosticConsoleEvent{ + At: time.Now().UTC().Format(time.RFC3339Nano), + Type: message.Type(), + Text: text, + }) + }) + page.OnPageError(func(pageErr error) { + d.mu.Lock() + defer d.mu.Unlock() + if pageErr == nil || len(d.pageError) >= tokenCaptchaDiagnosticMaxEvents { + return + } + text := pageErr.Error() + if !d.includeSensitive { + text = redactDiagnosticText(text) + } + d.pageError = append(d.pageError, text) + }) + return d +} + +func diagnosticBoolEnv(name string) bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv(name))) { + case "1", "true", "yes", "on": + return true + default: + return false + } +} + +func (d *tokenCaptchaDiagnostic) recordRequest(request playwright.Request) { + d.mu.Lock() + defer d.mu.Unlock() + if len(d.requests) >= tokenCaptchaDiagnosticMaxEvents { + return + } + d.requests = append(d.requests, tokenCaptchaDiagnosticNetworkEvent{ + Kind: "request", + At: time.Now().UTC().Format(time.RFC3339Nano), + URL: d.safeURL(request.URL()), + Method: request.Method(), + ResourceType: request.ResourceType(), + Navigation: request.IsNavigationRequest(), + }) +} + +func (d *tokenCaptchaDiagnostic) recordResponse(response playwright.Response) { + d.mu.Lock() + defer d.mu.Unlock() + if len(d.responses) >= tokenCaptchaDiagnosticMaxEvents { + return + } + request := response.Request() + contentType := response.Headers()["content-type"] + d.responses = append(d.responses, tokenCaptchaDiagnosticNetworkEvent{ + Kind: "response", + At: time.Now().UTC().Format(time.RFC3339Nano), + URL: d.safeURL(response.URL()), + Method: request.Method(), + ResourceType: request.ResourceType(), + Navigation: request.IsNavigationRequest(), + Status: response.Status(), + ContentType: contentType, + }) +} + +func (d *tokenCaptchaDiagnostic) safeURL(raw string) string { + if d.includeSensitive { + return raw + } + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || u.Scheme == "" || u.Host == "" { + return logsafe.URL(raw) + } + if u.RawQuery == "" && u.Fragment == "" { + return logsafe.URL(raw) + } + values := u.Query() + keys := make([]string, 0, len(values)) + for key := range values { + keys = append(keys, key) + } + sort.Strings(keys) + queryDigest := sha256.Sum256([]byte(u.RawQuery)) + u.RawQuery = "keys=" + strings.Join(keys, ",") + "&query_sha256=" + hex.EncodeToString(queryDigest[:])[:16] + u.Fragment = "" + return u.String() +} + +func (d *tokenCaptchaDiagnostic) capture(page playwright.Page, phase string, cause error) { + if d == nil || page == nil { + return + } + d.once.Do(func() { + path, err := d.writeBundle(page, phase, cause) + if err != nil { + // Diagnostics must never affect the CAPTCHA result path. + fmt.Fprintf(os.Stderr, "token captcha diagnostic capture failed: %v\n", err) + } else if d.logger != nil { + d.logger.Info("token风控诊断包已生成", "cookieID", d.cookieID, "engine", d.engine, "path", path, "include_sensitive", d.includeSensitive) + } + }) +} + +func (d *tokenCaptchaDiagnostic) snapshotInitial(page playwright.Page) { + if d == nil || page == nil { + return + } + d.mu.Lock() + if d.initial.CapturedAt != "" { + d.mu.Unlock() + return + } + d.mu.Unlock() + + snapshot := tokenCaptchaDiagnosticSnapshot{ + CapturedAt: time.Now().UTC().Format(time.RFC3339Nano), + FrameHTML: make(map[int]string), + } + snapshot.PageHTML, _ = page.Content() + snapshot.Screenshot, _ = page.Screenshot(playwright.PageScreenshotOptions{FullPage: playwright.Bool(true), Timeout: playwright.Float(5000)}) + snapshot.Frames, snapshot.Selectors = diagnosticFramesAndSelectors(page, d) + for index, frame := range append([]playwright.Frame{page.MainFrame()}, page.Frames()...) { + if htmlText, err := frame.Content(); err == nil { + snapshot.FrameHTML[index] = htmlText + } + } + d.mu.Lock() + if d.initial.CapturedAt == "" { + d.initial = snapshot + } + d.mu.Unlock() +} + +func (d *tokenCaptchaDiagnostic) writeBundle(page playwright.Page, phase string, cause error) (string, error) { + if err := os.MkdirAll(d.dir, 0o700); err != nil { + return "", err + } + name := fmt.Sprintf("token-captcha-%s-%s-%s.zip", logsafe.ID(d.cookieID), d.startedAt.Format("20060102T150405.000000000Z"), sanitize(d.engine)) + target := filepath.Join(d.dir, name) + tmp, err := os.CreateTemp(d.dir, ".token-captcha-*.zip.tmp") + if err != nil { + return "", err + } + tmpName := tmp.Name() + defer func() { + _ = tmp.Close() + _ = os.Remove(tmpName) + }() + zw := zip.NewWriter(tmp) + closeZip := func(closeErr error) error { + if closeErr != nil { + _ = zw.Close() + return closeErr + } + if err := zw.Close(); err != nil { + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmpName, target) + } + + d.mu.Lock() + requests := append([]tokenCaptchaDiagnosticNetworkEvent(nil), d.requests...) + responses := append([]tokenCaptchaDiagnosticNetworkEvent(nil), d.responses...) + console := append([]tokenCaptchaDiagnosticConsoleEvent(nil), d.console...) + pageErrors := append([]string(nil), d.pageError...) + d.mu.Unlock() + manifest := tokenCaptchaDiagnosticManifest{ + Version: 1, + CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), + CookieIDHash: logsafe.ID(d.cookieID), + Engine: d.engine, + Phase: phase, + RequestedURL: d.safeURL(d.requestedURL), + CurrentURL: d.safeURL(page.URL()), + IncludeSensitive: d.includeSensitive, + Requests: requests, + Responses: responses, + Console: console, + PageErrors: pageErrors, + } + if cause != nil { + manifest.Cause = cause.Error() + } + if title, titleErr := page.Title(); titleErr == nil { + manifest.Title = title + } + manifest.PageState = diagnosticPageState(page, d.includeSensitive) + manifest.Frames, manifest.Selectors = diagnosticFramesAndSelectors(page, d) + d.mu.Lock() + initial := d.initial + initial.FrameHTML = cloneDiagnosticFrameHTML(initial.FrameHTML) + initial.Screenshot = append([]byte(nil), initial.Screenshot...) + d.mu.Unlock() + manifest.InitialCapturedAt = initial.CapturedAt + manifest.InitialFrames = initial.Frames + manifest.InitialSelectors = initial.Selectors + + manifestJSON, err := json.MarshalIndent(manifest, "", " ") + if err != nil { + return "", closeZip(err) + } + if err := writeZipEntry(zw, "manifest.json", manifestJSON); err != nil { + return "", closeZip(err) + } + readme := []byte("This archive was generated by the opt-in token CAPTCHA diagnostic mode.\n" + + "It contains page/frame/selector/network metadata and a screenshot captured on failure.\n" + + "Cookie values and verification query values are redacted unless CAPTCHA_DIAGNOSTIC_INCLUDE_SENSITIVE=1.\n") + if err := writeZipEntry(zw, "README.txt", readme); err != nil { + return "", closeZip(err) + } + if htmlText, htmlErr := page.Content(); htmlErr == nil { + if !d.includeSensitive { + htmlText = redactDiagnosticText(htmlText) + } + if err := writeZipEntry(zw, "page.html", []byte(htmlText)); err != nil { + return "", closeZip(err) + } + } + if initial.PageHTML != "" { + initialHTML := initial.PageHTML + if !d.includeSensitive { + initialHTML = redactDiagnosticText(initialHTML) + } + if err := writeZipEntry(zw, "initial/page.html", []byte(initialHTML)); err != nil { + return "", closeZip(err) + } + } + for index, frameHTML := range initial.FrameHTML { + if !d.includeSensitive { + frameHTML = redactDiagnosticText(frameHTML) + } + if err := writeZipEntry(zw, fmt.Sprintf("initial/frames/frame-%02d.html", index), []byte(frameHTML)); err != nil { + return "", closeZip(err) + } + } + if len(initial.Screenshot) > 0 { + if err := writeZipEntry(zw, "initial/page.png", initial.Screenshot); err != nil { + return "", closeZip(err) + } + } + for index, frame := range append([]playwright.Frame{page.MainFrame()}, page.Frames()...) { + frameHTML, frameErr := frame.Content() + if frameErr != nil { + continue + } + if !d.includeSensitive { + frameHTML = redactDiagnosticText(frameHTML) + } + if err := writeZipEntry(zw, fmt.Sprintf("frames/frame-%02d.html", index), []byte(frameHTML)); err != nil { + return "", closeZip(err) + } + } + if screenshot, screenshotErr := page.Screenshot(playwright.PageScreenshotOptions{FullPage: playwright.Bool(true), Timeout: playwright.Float(5000)}); screenshotErr == nil { + if err := writeZipEntry(zw, "page.png", screenshot); err != nil { + return "", closeZip(err) + } + } + if err := closeZip(nil); err != nil { + return "", err + } + return target, nil +} + +func cloneDiagnosticFrameHTML(input map[int]string) map[int]string { + if len(input) == 0 { + return nil + } + output := make(map[int]string, len(input)) + for index, htmlText := range input { + output[index] = htmlText + } + return output +} + +func writeZipEntry(zw *zip.Writer, name string, data []byte) error { + writer, err := zw.Create(name) + if err != nil { + return err + } + _, err = writer.Write(data) + return err +} + +func diagnosticPageState(page playwright.Page, includeSensitive bool) map[string]any { + value, err := page.Evaluate(`async () => { + let userAgentData = null; + if (navigator.userAgentData) { + userAgentData = { + brands: navigator.userAgentData.brands, + mobile: navigator.userAgentData.mobile, + platform: navigator.userAgentData.platform + }; + try { + userAgentData.high_entropy = await navigator.userAgentData.getHighEntropyValues([ + 'architecture', 'bitness', 'fullVersionList', 'model', 'platformVersion', 'wow64' + ]); + } catch (error) { + userAgentData.high_entropy_error = String(error); + } + } + return { + ready_state: document.readyState, + location_path: window.location.pathname, + location_query_present: Boolean(window.location.search), + inner_width: window.innerWidth, + inner_height: window.innerHeight, + device_pixel_ratio: window.devicePixelRatio, + user_agent: navigator.userAgent, + user_agent_data: userAgentData, + webdriver: navigator.webdriver, + has_nc_container: Boolean(document.querySelector('.nc-container')), + has_errloading: Boolean(document.querySelector('.errloading')), + body_text: (document.body && document.body.innerText || '').slice(0, 1200) + }; + }`) + if err != nil { + return map[string]any{"error": err.Error()} + } + if state, ok := value.(map[string]any); ok { + if body, ok := state["body_text"].(string); ok && !includeSensitive { + state["body_text"] = redactDiagnosticText(body) + } + return state + } + return map[string]any{"value": value} +} + +func diagnosticFramesAndSelectors(page playwright.Page, d *tokenCaptchaDiagnostic) ([]tokenCaptchaDiagnosticFrame, []tokenCaptchaDiagnosticSelector) { + frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...) + frameMetadata := make([]tokenCaptchaDiagnosticFrame, 0, len(frames)) + selectors := append([]string{}, sliderButtonSelectors...) + selectors = append(selectors, sliderTrackSelectors...) + selectors = append(selectors, sliderRetrySelectors...) + for index, frame := range frames { + parentURL := "" + if parent := frame.ParentFrame(); parent != nil { + parentURL = d.safeURL(parent.URL()) + } + metadata := tokenCaptchaDiagnosticFrame{Index: index, Name: frame.Name(), URL: d.safeURL(frame.URL()), ParentURL: parentURL} + if htmlText, err := frame.Content(); err == nil { + metadata.HTMLBytes = len(htmlText) + } else { + metadata.ContentErr = err.Error() + } + frameMetadata = append(frameMetadata, metadata) + } + selectorRecords := make([]tokenCaptchaDiagnosticSelector, 0, len(frames)*len(selectors)) + for index, frame := range frames { + frameURL := d.safeURL(frame.URL()) + for _, selector := range selectors { + entry := tokenCaptchaDiagnosticSelector{FrameIndex: index, FrameURL: frameURL, Selector: selector} + el, err := frame.QuerySelector(selector) + if err != nil { + entry.Error = err.Error() + } else if el != nil { + entry.Found = true + entry.Visible = elementVisible(el) + if box, boxErr := el.BoundingBox(); boxErr == nil { + entry.Box = formatBoundingBox(box) + } + } + selectorRecords = append(selectorRecords, entry) + } + } + return frameMetadata, selectorRecords +} + +func redactDiagnosticText(text string) string { + for _, key := range []string{"x5secdata", "x5sec", "_m_h5_tk", "_m_h5_tk_enc", "token", "sign"} { + text = redactDiagnosticKey(text, key) + } + return text +} + +func redactDiagnosticKey(text, key string) string { + pattern := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(key) + `=[^&'"<>\s\\` + "`" + `)]*`) + return pattern.ReplaceAllStringFunc(text, func(match string) string { + if index := strings.IndexByte(match, '='); index >= 0 { + return match[:index+1] + "" + } + return match + }) +} diff --git a/internal/browser/token_captcha_diagnostic_test.go b/internal/browser/token_captcha_diagnostic_test.go new file mode 100644 index 0000000..0b16fc6 --- /dev/null +++ b/internal/browser/token_captcha_diagnostic_test.go @@ -0,0 +1,117 @@ +package browser + +import ( + "archive/zip" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/mxschmitt/playwright-go" +) + +func TestTokenCaptchaDiagnosticRedactsSensitiveValues(t *testing.T) { + d := &tokenCaptchaDiagnostic{includeSensitive: false} + got := d.safeURL("https://example.test/punish?x5secdata=secret-value&action=captcha#fragment") + if strings.Contains(got, "secret-value") || strings.Contains(got, "fragment") { + t.Fatalf("safeURL leaked sensitive data: %q", got) + } + if !strings.Contains(got, "x5secdata") || !strings.Contains(got, "query_sha256") { + t.Fatalf("safeURL lost query diagnostics: %q", got) + } + text := `x5secdata=secret-value&token=another-secret sign=third-secret` + redacted := redactDiagnosticText(text) + if strings.Contains(redacted, "secret-value") || strings.Contains(redacted, "another-secret") || strings.Contains(redacted, "third-secret") { + t.Fatalf("redactDiagnosticText leaked sensitive data: %q", redacted) + } +} + +func TestTokenCaptchaDiagnosticBundleBrowserIntegration(t *testing.T) { + if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" { + t.Skip("set RUN_BROWSER_INTEGRATION=1 to exercise token CAPTCHA diagnostics") + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, _ = io.WriteString(w, `诊断验证码 +
+`) + })) + defer server.Close() + + dir := t.TempDir() + t.Setenv(tokenCaptchaDiagnosticDirEnv, dir) + t.Setenv(tokenCaptchaDiagnosticSensitiveEnv, "") + m := NewManager(nil) + defer m.Close() + if err := m.init(); err != nil { + t.Fatal(err) + } + browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{ + Headless: playwright.Bool(true), + Args: chromiumLaunchArgs(), + }) + if err != nil { + t.Fatal(err) + } + defer func() { _ = browser.Close() }() + bctx, err := browser.NewContext() + if err != nil { + t.Fatal(err) + } + defer func() { _ = bctx.Close() }() + page, err := bctx.NewPage() + if err != nil { + t.Fatal(err) + } + diagnostic := newTokenCaptchaDiagnostic("diagnostic-account", "playwright", server.URL+"/punish?x5secdata=secret", page, m.logger) + if _, err := page.Goto(server.URL+"/punish?x5secdata=secret", playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil { + t.Fatal(err) + } + diagnostic.snapshotInitial(page) + diagnostic.capture(page, "test_failure", io.ErrUnexpectedEOF) + + archives, err := filepath.Glob(filepath.Join(dir, "*.zip")) + if err != nil || len(archives) != 1 { + t.Fatalf("diagnostic archive count=%d err=%v", len(archives), err) + } + archive, err := zip.OpenReader(archives[0]) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + entries := make(map[string][]byte) + for _, file := range archive.File { + reader, readErr := file.Open() + if readErr != nil { + t.Fatal(readErr) + } + data, readErr := io.ReadAll(reader) + _ = reader.Close() + if readErr != nil { + t.Fatal(readErr) + } + entries[file.Name] = data + } + for _, name := range []string{"README.txt", "manifest.json", "page.html", "page.png", "initial/page.html", "initial/page.png", "frames/frame-00.html", "initial/frames/frame-00.html"} { + if len(entries[name]) == 0 { + t.Fatalf("diagnostic archive missing %s", name) + } + } + var manifest tokenCaptchaDiagnosticManifest + if err := json.Unmarshal(entries["manifest.json"], &manifest); err != nil { + t.Fatal(err) + } + if manifest.Phase != "test_failure" || manifest.Engine != "playwright" { + t.Fatalf("unexpected manifest: %+v", manifest) + } + if manifest.InitialCapturedAt == "" || len(manifest.InitialFrames) == 0 || len(manifest.InitialSelectors) == 0 { + t.Fatalf("initial snapshot metadata missing: %+v", manifest) + } + if strings.Contains(string(entries["page.html"]), "secret") { + t.Fatalf("page HTML leaked query value") + } +} diff --git a/internal/browser/token_captcha_fallback.go b/internal/browser/token_captcha_fallback.go index fc1ed11..5839597 100644 --- a/internal/browser/token_captcha_fallback.go +++ b/internal/browser/token_captcha_fallback.go @@ -22,7 +22,7 @@ var fallbackTrackSelectors = []string{ // tokenCaptchaCDPFallback 直接启动 Chromium 并通过 CDP 连接,复现参考项目的 // DrissionPage 第二引擎:它不复用 Playwright launch 协议,使用同一持久化目录和另一套轨迹。 -func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (string, error) { +func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (result string, resultErr error) { if strings.TrimSpace(cookieStr) == "" || strings.TrimSpace(verificationURL) == "" { return "", fmt.Errorf("备用滑块引擎参数不完整") } @@ -52,7 +52,7 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS if strings.TrimSpace(executable) == "" { return "", fmt.Errorf("备用滑块引擎未找到 Chromium") } - args := fallbackChromiumArgs(profileDir, headless) + args := fallbackChromiumArgs(profileDir, headless, m.headlessUserAgent()) cmd := exec.Command(executable, args...) cmd.Stdout = io.Discard cmd.Stderr = io.Discard @@ -96,11 +96,18 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS return "", fmt.Errorf("备用滑块引擎读取旧 Cookie: %w", err) } previousX5 := x5SecValues(before) - page, err := bctx.NewPage() + page, err := m.newBrowserPage(bctx, headless) if err != nil { return "", fmt.Errorf("备用滑块引擎创建页面: %w", err) } defer func() { _ = page.Close() }() + diagnostic := newTokenCaptchaDiagnostic(cookieID, "drissionpage", verificationURL, page, m.logger) + diagnosticSucceeded := false + defer func() { + if diagnostic != nil && !diagnosticSucceeded { + diagnostic.capture(page, "drissionpage_failed", resultErr) + } + }() deadline := time.Now().Add(drissionFallbackTimeout()) if _, err := page.Goto(verificationURL, playwright.PageGotoOptions{ @@ -116,6 +123,9 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS m.logger.Warn("备用滑块引擎页面没有可验证滑块,停止自动验证", "cookieID", cookieID, "err", pageErr) return "", pageErr } + if diagnostic != nil { + diagnostic.snapshotInitial(page) + } for attempt := 0; attempt < 3; attempt++ { if err := contextDeadlineError(ctx, deadline); err != nil { @@ -175,6 +185,7 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS merged[name] = value } m.logger.Info("备用滑块引擎验证成功", "cookieID", cookieID, "attempt", attempt+1) + diagnosticSucceeded = true return cookieMarshal(merged), nil } logSliderFailureState(m.logger, page, attempt+1) @@ -189,7 +200,7 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS return "", fmt.Errorf("备用滑块引擎 3 次均失败") } -func fallbackChromiumArgs(profileDir string, headless bool) []string { +func fallbackChromiumArgs(profileDir string, headless bool, headlessUserAgent ...*string) []string { args := []string{ "--user-data-dir=" + profileDir, "--remote-debugging-port=0", @@ -200,8 +211,16 @@ func fallbackChromiumArgs(profileDir string, headless bool) []string { "--no-first-run", "--window-size=1920,1080", "--lang=zh-CN", - "about:blank", } + if captchaIgnoreCertificateErrors() { + args = append(args, "--ignore-certificate-errors") + } + if headless && len(headlessUserAgent) > 0 && headlessUserAgent[0] != nil { + if userAgent := normalizeHeadlessUserAgent(*headlessUserAgent[0]); userAgent != "" { + args = append(args, "--user-agent="+userAgent) + } + } + args = append(args, "about:blank") if headless { args = append([]string{"--headless=new"}, args...) } diff --git a/internal/browser/token_captcha_orchestrator_test.go b/internal/browser/token_captcha_orchestrator_test.go index 0c7c903..d01d2cc 100644 --- a/internal/browser/token_captcha_orchestrator_test.go +++ b/internal/browser/token_captcha_orchestrator_test.go @@ -259,12 +259,16 @@ func TestFallbackUsableDistanceMatchesStandardNCDOM(t *testing.T) { } func TestFallbackChromiumArgsUsePersistentCDPProfile(t *testing.T) { - args := strings.Join(fallbackChromiumArgs("/tmp/profile", true), " ") - for _, want := range []string{"--headless=new", "--user-data-dir=/tmp/profile", "--remote-debugging-port=0", "--window-size=1920,1080", "--disable-blink-features=AutomationControlled"} { + userAgent := "Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36" + args := strings.Join(fallbackChromiumArgs("/tmp/profile", true, &userAgent), " ") + for _, want := range []string{"--headless=new", "--user-data-dir=/tmp/profile", "--remote-debugging-port=0", "--window-size=1920,1080", "--disable-blink-features=AutomationControlled", "--user-agent=Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36"} { if !strings.Contains(args, want) { t.Fatalf("args 缺少 %q: %s", want, args) } } + if strings.Contains(args, "HeadlessChrome") { + t.Fatalf("备用 Chromium 参数仍暴露 HeadlessChrome: %s", args) + } } func TestWaitForDevToolsEndpoint(t *testing.T) { diff --git a/internal/chat/service.go b/internal/chat/service.go index bf834a5..927c702 100644 --- a/internal/chat/service.go +++ b/internal/chat/service.go @@ -113,9 +113,10 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st if lastMessageAt <= 0 { lastMessageAt = modifyTime } + unreadCount := s.conversationUnreadCount(ctx, accountID, cid, peerID, conv, last, summary) session := db.ChatSession{CookieID: accountID, ChatID: cid, BuyerID: peerID, BuyerName: peerName, BuyerAvatar: avatar, ItemID: cleanNilString(ext["itemId"]), ItemTitle: cleanNilString(ext["itemTitle"]), LastMessage: summary, - LastMessageAt: lastMessageAt, UnreadCount: int(int64Value(conv["redPoint"]))} + LastMessageAt: lastMessageAt, UnreadCount: unreadCount} if err := s.store.Chats.UpsertSession(ctx, session); err != nil { return page, err } @@ -126,6 +127,69 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st return page, nil } +// conversationUnreadCount keeps redPoint as the platform's authoritative +// signal, while using our message-level state for the number shown in the UI. +// redPoint counts every unread item in a conversation, including trade cards +// and official notices; only incoming non-system messages are user unread. +func (s *Service) conversationUnreadCount(ctx context.Context, accountID, chatID, peerID string, conv, last map[string]any, summary string) int { + official := int(int64Value(conv["redPoint"])) + if official < 0 { + official = 0 + } + if official == 0 { + return 0 + } + + if local, err := s.store.Chats.CountUnreadUserMessages(ctx, accountID, chatID); err == nil && local > 0 { + // A stale local event must not make the badge exceed the official + // conversation signal. In normal operation these values are equal. + if local > official { + return official + } + return local + } + + if !historyMessageIsSystem(last, summary) { + // No message-level row exists yet (for example immediately after a + // fresh login), so retain the official count as a safe fallback. + return official + } + + // 闲小蜜会话只包含平台消息,永远不能制造用户红点。 + if strings.TrimSuffix(strings.TrimSpace(peerID), "@goofish") == "1400" { + return 0 + } + + // The official last-message envelope exposes unreadCount/readStatus for + // that item. Subtract that system portion from redPoint; when older server + // responses omit the fields, conservatively remove one system item. + systemUnread := int(int64Value(last["unreadCount"])) + readStatus := int64Value(last["readStatus"]) + if systemUnread <= 0 && readStatus != 2 { + systemUnread = 1 + } + if systemUnread > official { + systemUnread = official + } + return official - systemUnread +} + +func historyMessageIsSystem(last map[string]any, summary string) bool { + extension := mapValue(last["extension"]) + senderID := cleanNilString(extension["senderUserId"]) + content := map[string]any{} + if contentMap, ok := last["content"].(map[string]any); ok { + if custom, ok := contentMap["custom"].(map[string]any); ok { + if encoded := cleanNilString(custom["data"]); encoded != "" { + if raw, err := base64.StdEncoding.DecodeString(encoded); err == nil { + _ = json.Unmarshal(raw, &content) + } + } + } + } + return isOfficialSystemMessage(content, senderID, summary) +} + var invalidNicknames = map[string]struct{}{ "交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {}, "快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {}, @@ -164,6 +228,7 @@ type Incoming struct { BuyerID string BuyerName string Text string + MessageID string ItemID string Raw map[string]any } @@ -243,7 +308,10 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess if sentAt == 0 { sentAt = time.Now().UTC().UnixMilli() } - key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid") + key := strings.TrimSpace(in.MessageID) + if key == "" { + key = extractString(in.Raw, "messageId", "message_id", "msgId", "uuid") + } if key == "" { raw, _ := json.Marshal(in.Raw) digest := sha256.Sum256([]byte(in.AccountID + "\x00" + in.ChatID + "\x00" + in.BuyerID + "\x00" + in.Text + "\x00" + string(raw))) @@ -263,7 +331,10 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess } message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID, SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt} - stored, inserted, err := s.store.Chats.SaveMessage(ctx, session, message, true) + // Official notices may still reach this side channel when protocol fields + // vary. They are rendered as system messages and must never create a user + // unread badge. + stored, inserted, err := s.store.Chats.SaveMessage(ctx, session, message, messageType != "system") if err == nil && inserted { s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session}) } @@ -527,6 +598,23 @@ func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status return message, err } +// MarkOutgoingRead records the platform's read receipt for an outgoing message. +func (s *Service) MarkOutgoingRead(ctx context.Context, accountID, key string, readAt int64) (*db.ChatMessage, error) { + message, err := s.store.Chats.MarkMessageRead(ctx, accountID, key, readAt) + if err == nil { + s.Publish(accountID, Event{Type: "message.updated", Message: message}) + } + return message, err +} + +func (s *Service) MarkLatestOutgoingRead(ctx context.Context, accountID, chatID string, readAt int64) (*db.ChatMessage, error) { + message, err := s.store.Chats.MarkLatestOutgoingRead(ctx, accountID, chatID, readAt) + if err == nil { + s.Publish(accountID, Event{Type: "message.updated", Message: message}) + } + return message, err +} + func randomID() string { var value [16]byte if _, err := rand.Read(value[:]); err == nil { @@ -562,6 +650,16 @@ func extractString(value any, keys ...string) string { return text } } + case string: + // Live WS envelopes often keep extJson/bizTag as an encoded JSON + // string. Decode it so messageId is preserved instead of falling + // back to a local in-* key. + var decoded any + if json.Unmarshal([]byte(x), &decoded) == nil { + if text := walk(decoded); text != "" { + return text + } + } } return "" } diff --git a/internal/chat/service_test.go b/internal/chat/service_test.go index 4cc28b3..ff0ae77 100644 --- a/internal/chat/service_test.go +++ b/internal/chat/service_test.go @@ -106,6 +106,24 @@ func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) { } } +func TestRecordIncomingExtractsMessageIDFromEncodedExtension(t *testing.T) { + store, cleanup := chatTestStore(t) + defer cleanup() + service := New(store) + message, _, err := service.RecordIncoming(context.Background(), Incoming{ + AccountID: "account-1", ChatID: "live", BuyerID: "peer", BuyerName: "对方", Text: "实时消息", + Raw: map[string]any{"1": map[string]any{"10": map[string]any{ + "extJson": `{"messageId":"live-123"}`, + }}}, + }) + if err != nil { + t.Fatal(err) + } + if message.MessageKey != "live-123" { + t.Fatalf("实时消息未提取平台 messageId: %+v", message) + } +} + func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) { store, cleanup := chatTestStore(t) defer cleanup() @@ -157,6 +175,7 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "singleChatConversation": map[string]any{"cid": "platform@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "900"}}}}, map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "modifyTime": float64(123), "singleChatConversation": map[string]any{"cid": "xiaomi@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "1400"}}, + "redPoint": float64(3), "lastMessage": map[string]any{"message": map[string]any{"extension": map[string]any{"senderUserId": "1400@goofish", "reminderTitle": "闲小蜜发来一条新消息"}, "content": map[string]any{"custom": map[string]any{"summary": "邀您填写售后问卷"}}}}}}, }} if _, err := service.RecordConversationPage(ctx, "account-1", "self", body); err != nil { @@ -167,11 +186,61 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t if err != nil { t.Fatal(err) } - if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar { + if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar || rows[0].UnreadCount != 0 { t.Fatalf("unexpected sessions: %+v", rows) } } +func TestConversationUnreadCountUsesRedPointButFiltersSystemMessages(t *testing.T) { + store, cleanup := chatTestStore(t) + defer cleanup() + service := New(store) + + systemCard := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26}`)) + systemLast := map[string]any{ + "extension": map[string]any{"senderUserId": "peer@goofish"}, + "content": map[string]any{"custom": map[string]any{"summary": "[交易通知]", "data": systemCard}}, + "unreadCount": float64(1), "readStatus": float64(1), + } + if got := service.conversationUnreadCount(context.Background(), "account-1", "system-last", "peer", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 2 { + t.Fatalf("系统未读未从 redPoint 扣除: got=%d", got) + } + if got := service.conversationUnreadCount(context.Background(), "account-1", "xiaomi", "1400", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 0 { + t.Fatalf("闲小蜜全是系统消息时仍显示红点: got=%d", got) + } + + if _, _, err := service.RecordIncoming(context.Background(), Incoming{ + AccountID: "account-1", ChatID: "real", BuyerID: "peer", BuyerName: "真实用户", Text: "未读消息", + MessageID: "real-unread", Raw: map[string]any{"messageId": "real-unread"}, + }); err != nil { + t.Fatal(err) + } + userLast := map[string]any{ + "extension": map[string]any{"senderUserId": "peer@goofish"}, + "content": map[string]any{"custom": map[string]any{"summary": "未读消息"}}, + } + if got := service.conversationUnreadCount(context.Background(), "account-1", "real", "peer", map[string]any{"redPoint": float64(3)}, userLast, "未读消息"); got != 1 { + t.Fatalf("未使用消息级真实未读数: got=%d", got) + } +} + +func TestHistoryMessageIsSystem(t *testing.T) { + encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{}}`)) + last := map[string]any{ + "extension": map[string]any{"senderUserId": "peer@goofish"}, + "content": map[string]any{"custom": map[string]any{"data": encoded}}, + } + if !historyMessageIsSystem(last, "[我已拍下,待付款]") { + t.Fatal("交易卡片应被识别为系统消息") + } + if historyMessageIsSystem(map[string]any{ + "extension": map[string]any{"senderUserId": "peer@goofish"}, + "content": map[string]any{"custom": map[string]any{"summary": "你好"}}, + }, "你好") { + t.Fatal("真实用户文本不应被识别为系统消息") + } +} + func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) { store, cleanup := chatTestStore(t) defer cleanup() diff --git a/internal/db/chat.go b/internal/db/chat.go index 8999162..297b461 100644 --- a/internal/db/chat.go +++ b/internal/db/chat.go @@ -33,6 +33,8 @@ type ChatMessage struct { MessageType string `json:"message_type"` Content string `json:"content"` Status string `json:"status"` + ReadStatus int `json:"read_status"` + ReadAt int64 `json:"read_at,omitempty"` SentAt int64 `json:"sent_at"` } @@ -135,6 +137,13 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag if message.SentAt <= 0 { message.SentAt = time.Now().UTC().UnixMilli() } + // read_status is also used for incoming messages: only a newly received + // real-user message starts unread. Imported history and official system + // notices must never contribute to the chat badge. + if message.Direction == "incoming" && (!unread || message.MessageType == "system") { + message.ReadStatus = 2 + message.ReadAt = time.Now().UTC().UnixMilli() + } message.CookieID, message.ChatID = session.CookieID, session.ChatID now := time.Now().UTC().Unix() tx, err := s.DB.BeginTx(ctx, nil) @@ -155,11 +164,11 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag prefix := dialectInsertIgnorePrefix(s.Dialect) query := prefix + ` INTO chat_messages - (cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at,created_at) - VALUES(?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"}) + (cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,read_status,read_at,sent_at,created_at) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"}) res, err := tx.ExecContext(ctx, query, message.CookieID, message.ChatID, message.MessageKey, message.Direction, message.SenderID, message.SenderName, message.MessageType, message.Content, - message.Status, message.SentAt, now) + message.Status, message.ReadStatus, message.ReadAt, message.SentAt, now) if err != nil { return nil, false, fmt.Errorf("保存聊天消息: %w", err) } @@ -188,10 +197,10 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag func (s *ChatStore) GetMessageByKey(ctx context.Context, cookieID, key string) (*ChatMessage, error) { var m ChatMessage - err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at + err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,read_status,read_at,sent_at FROM chat_messages WHERE cookie_id=? AND message_key=?`, cookieID, key).Scan( &m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID, &m.SenderName, - &m.MessageType, &m.Content, &m.Status, &m.SentAt) + &m.MessageType, &m.Content, &m.Status, &m.ReadStatus, &m.ReadAt, &m.SentAt) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } @@ -234,7 +243,7 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch if limit <= 0 || limit > 200 { limit = 50 } - query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.sent_at + query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.read_status,m.read_at,m.sent_at FROM chat_messages m JOIN cookies c ON c.id=m.cookie_id WHERE c.user_id=? AND m.cookie_id=? AND m.chat_id=?` args := []any{userID, cookieID, chatID} @@ -254,7 +263,7 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch for rows.Next() { var m ChatMessage if err := rows.Scan(&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID, - &m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.SentAt); err != nil { + &m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.ReadStatus, &m.ReadAt, &m.SentAt); err != nil { return nil, err } result = append(result, m) @@ -267,15 +276,56 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch } func (s *ChatStore) MarkRead(ctx context.Context, userID int64, cookieID, chatID string) error { + now := time.Now().UTC() + if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET read_status=2,read_at=? + WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND message_type<>'system' AND read_status<>2`, + now.UnixMilli(), cookieID, chatID); err != nil { + return err + } _, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET unread_count=0,updated_at=? WHERE cookie_id=? AND chat_id=? AND EXISTS(SELECT 1 FROM cookies c WHERE c.id=chat_sessions.cookie_id AND c.user_id=?)`, - time.Now().UTC().Unix(), cookieID, chatID, userID) + now.Unix(), cookieID, chatID, userID) return err } +// CountUnreadUserMessages returns the message-level unread count used by the +// UI badge. It deliberately excludes official/system messages and relies on +// read_status rather than the conversation summary counter. +func (s *ChatStore) CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error) { + var count int + err := s.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM chat_messages + WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND message_type<>'system' AND read_status<>2`, cookieID, chatID).Scan(&count) + return count, err +} + func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*ChatMessage, error) { if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET status=? WHERE cookie_id=? AND message_key=?`, status, cookieID, key); err != nil { return nil, err } return s.GetMessageByKey(ctx, cookieID, key) } + +func (s *ChatStore) MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*ChatMessage, error) { + if readAt <= 0 { + readAt = time.Now().UTC().UnixMilli() + } + if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET read_status=2,read_at=? WHERE cookie_id=? AND message_key=? AND direction='outgoing'`, readAt, cookieID, key); err != nil { + return nil, err + } + return s.GetMessageByKey(ctx, cookieID, key) +} + +func (s *ChatStore) MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*ChatMessage, error) { + if readAt <= 0 { + readAt = time.Now().UTC().UnixMilli() + } + var key string + err := s.DB.QueryRowContext(ctx, `SELECT message_key FROM chat_messages WHERE cookie_id=? AND chat_id=? AND direction='outgoing' AND status='sent' AND read_status<>2 ORDER BY sent_at DESC,id DESC LIMIT 1`, cookieID, chatID).Scan(&key) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return s.MarkMessageRead(ctx, cookieID, key, readAt) +} diff --git a/internal/db/migrate_test.go b/internal/db/migrate_test.go index f487672..56f48ec 100644 --- a/internal/db/migrate_test.go +++ b/internal/db/migrate_test.go @@ -128,8 +128,9 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) { t.Fatalf("goose dialect: %v", err) } goose.SetBaseFS(migrationsFS) - // 依次回滚最新版本到 13,再整体升级。 - for i := 0; i < 15; i++ { + // 依次回滚最新版本到 13,再整体升级。00029/00030 是聊天已读 + // 状态迁移,因此需要额外回滚两次才能到达原有的 migration 14 检查点。 + for i := 0; i < 17; i++ { if err := goose.Down(d, "migrations/sqlite"); err != nil { t.Fatalf("down migration #%d: %v", i+1, err) } diff --git a/internal/db/migrations/mysql/00029_chat_read_status.sql b/internal/db/migrations/mysql/00029_chat_read_status.sql new file mode 100644 index 0000000..1ff3aac --- /dev/null +++ b/internal/db/migrations/mysql/00029_chat_read_status.sql @@ -0,0 +1,6 @@ +-- +goose Up +ALTER TABLE chat_messages ADD COLUMN read_status INT NOT NULL DEFAULT 0; +ALTER TABLE chat_messages ADD COLUMN read_at BIGINT NOT NULL DEFAULT 0; +-- +goose Down +ALTER TABLE chat_messages DROP COLUMN read_at; +ALTER TABLE chat_messages DROP COLUMN read_status; diff --git a/internal/db/migrations/mysql/00030_chat_unread_state.sql b/internal/db/migrations/mysql/00030_chat_unread_state.sql new file mode 100644 index 0000000..77e072b --- /dev/null +++ b/internal/db/migrations/mysql/00030_chat_unread_state.sql @@ -0,0 +1,6 @@ +-- +goose Up +UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN UNIX_TIMESTAMP(CURRENT_TIMESTAMP) * 1000 ELSE read_at END +WHERE direction='incoming' AND read_status=0; + +-- +goose Down +-- No safe reverse: the previous schema had no per-message read boundary. diff --git a/internal/db/migrations/postgres/00029_chat_read_status.sql b/internal/db/migrations/postgres/00029_chat_read_status.sql new file mode 100644 index 0000000..54336b1 --- /dev/null +++ b/internal/db/migrations/postgres/00029_chat_read_status.sql @@ -0,0 +1,6 @@ +-- +goose Up +ALTER TABLE chat_messages ADD COLUMN read_status INTEGER NOT NULL DEFAULT 0; +ALTER TABLE chat_messages ADD COLUMN read_at BIGINT NOT NULL DEFAULT 0; +-- +goose Down +ALTER TABLE chat_messages DROP COLUMN read_at; +ALTER TABLE chat_messages DROP COLUMN read_status; diff --git a/internal/db/migrations/postgres/00030_chat_unread_state.sql b/internal/db/migrations/postgres/00030_chat_unread_state.sql new file mode 100644 index 0000000..90e334a --- /dev/null +++ b/internal/db/migrations/postgres/00030_chat_unread_state.sql @@ -0,0 +1,6 @@ +-- +goose Up +UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN (EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000)::BIGINT ELSE read_at END +WHERE direction='incoming' AND read_status=0; + +-- +goose Down +-- No safe reverse: the previous schema had no per-message read boundary. diff --git a/internal/db/migrations/sqlite/00029_chat_read_status.sql b/internal/db/migrations/sqlite/00029_chat_read_status.sql new file mode 100644 index 0000000..dd72cc5 --- /dev/null +++ b/internal/db/migrations/sqlite/00029_chat_read_status.sql @@ -0,0 +1,6 @@ +-- +goose Up +ALTER TABLE chat_messages ADD COLUMN read_status INTEGER NOT NULL DEFAULT 0; +ALTER TABLE chat_messages ADD COLUMN read_at INTEGER NOT NULL DEFAULT 0; +-- +goose Down +ALTER TABLE chat_messages DROP COLUMN read_at; +ALTER TABLE chat_messages DROP COLUMN read_status; diff --git a/internal/db/migrations/sqlite/00030_chat_unread_state.sql b/internal/db/migrations/sqlite/00030_chat_unread_state.sql new file mode 100644 index 0000000..5923059 --- /dev/null +++ b/internal/db/migrations/sqlite/00030_chat_unread_state.sql @@ -0,0 +1,8 @@ +-- +goose Up +-- Messages already stored before message-level read tracking was introduced +-- are history snapshots, not newly received unread messages. +UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN strftime('%s','now') * 1000 ELSE read_at END +WHERE direction='incoming' AND read_status=0; + +-- +goose Down +-- No safe reverse: the previous schema had no per-message read boundary. diff --git a/internal/db/multidb_test.go b/internal/db/multidb_test.go index 510da1d..ceaad44 100644 --- a/internal/db/multidb_test.go +++ b/internal/db/multidb_test.go @@ -771,7 +771,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) { t.Fatalf("set goose dialect: %v", err) } goose.SetBaseFS(migrationsFS) - for i := 0; i < 15; i++ { + for i := 0; i < 17; i++ { if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil { t.Fatalf("migration down #%d: %v", i+1, err) } diff --git a/internal/engine/account.go b/internal/engine/account.go index a8053d1..98420dd 100644 --- a/internal/engine/account.go +++ b/internal/engine/account.go @@ -83,6 +83,19 @@ type Handler interface { OnAccountAlert(ctx context.Context, cookieID, level, title, body string) } +// MessageReadHandler receives platform read receipts. It is optional so older +// integrations and tests remain valid. +type MessageReadHandler interface { + HandleMessageRead(context.Context, MessageReadEvent) error +} + +type MessageReadEvent struct { + AccountID string + ChatID string + MessageID string + ReadAt int64 +} + type accountEventHandler interface { OnAccountEvent(ctx context.Context, cookieID, eventType, level, title, body string) } @@ -121,6 +134,7 @@ type ChatMessage struct { SenderUserID string SenderName string Text string + MessageID string ItemID string Raw map[string]any // 解密后的完整消息 } @@ -1799,6 +1813,22 @@ func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) e return nil } +func (a *Account) MarkChatRead(ctx context.Context, chatID string, messageIDs []map[string]any) error { + conn, _, err := a.currentSenderState() + if err != nil { + return err + } + readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + reader, ok := conn.(interface { + MarkChatRead(context.Context, string, []map[string]any) error + }) + if !ok { + return fmt.Errorf("当前 WebSocket 不支持已读上报") + } + return reader.MarkChatRead(readCtx, chatID, messageIDs) +} + // SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。 func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error { imageURL = strings.TrimSpace(imageURL) diff --git a/internal/engine/dispatch.go b/internal/engine/dispatch.go index 0c92ba5..ed987e0 100644 --- a/internal/engine/dispatch.go +++ b/internal/engine/dispatch.go @@ -3,11 +3,14 @@ package engine import ( "context" "encoding/json" + "fmt" + "net/url" "sort" "strings" "time" "xianyu-go/internal/automation" + "xianyu-go/internal/xianyu/protocol" ) // dispatch 是 ws.ReceiveLoop 的回调,对每条解密后的消息做: @@ -59,6 +62,17 @@ func (a *Account) handleMessage(decrypted map[string]any) { } func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string]any) { + if receipt, ok := extractMessageReadEvent(decrypted); ok { + receipt.AccountID = a.CookieID + if h, ok := a.handler.(MessageReadHandler); ok { + if err := h.HandleMessageRead(ctx, receipt); err != nil { + a.logger.Warn("处理聊天已读回执失败", "err", err, "message_id", receipt.MessageID) + } + } else { + a.logger.Debug("收到聊天已读回执,但未接入处理器", "message_id", receipt.MessageID) + } + return + } // 第一优先级:系统卡片和平台通知进入自动化中心。 // 这里不判断具体业务,只做“平台事件”事实解析;系统消息永远不进入 AI 回复范围。 if task := automation.ExtractTaskFromWS(a.CookieID, a.currentCookieStr(), decrypted); task != nil { @@ -69,6 +83,10 @@ func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string } return } + if senderUserID := extractChatSenderUserID(decrypted); isSelfUserID(senderUserID, protocol.TransCookies(a.currentCookieStr())["unb"]) { + a.logger.Info("忽略账号自身发送的 WebSocket 聊天回显", "chat_id", extractChatID(decrypted), "sender_id", senderUserID) + return + } chat := extractChatMessage(decrypted, a.CookieID, a.currentCookieStr()) if chat != nil && chat.Text != "" { @@ -82,6 +100,89 @@ func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string } } +func extractMessageReadEvent(v map[string]any) (MessageReadEvent, bool) { + // 40103 解密后不会保留外层 objectType,只剩下固定的紧凑字段: + // 1=PNM 消息 ID、2=状态(2=已读)、4=会话 ID、6=事件时间。 + // 不能只在解密后的 map 里继续寻找 "bizType":40103,否则真实回执 + // 会被当成普通消息静默丢弃。 + messageID := strings.TrimSpace(toString(v["1"])) + if ids, ok := v["1"].([]any); ok && len(ids) > 0 { + messageID = strings.TrimSpace(toString(ids[0])) + } + if strings.HasSuffix(messageID, ".PNM") && toString(v["2"]) == "2" { + chatID := strings.TrimSpace(toString(v["4"])) + if !strings.Contains(chatID, "@goofish") { + chatID = strings.TrimSpace(toString(v["3"])) + } + chatID = strings.TrimSuffix(chatID, "@goofish") + return MessageReadEvent{ChatID: chatID, MessageID: messageID, ReadAt: time.Now().UTC().UnixMilli()}, true + } + var found bool + var ev MessageReadEvent + var walk func(any) + walk = func(x any) { + if found { + return + } + switch m := x.(type) { + case map[string]any: + for k, val := range m { + lk := strings.ToLower(k) + if lk == "biztype" || lk == "biz_type" || lk == "type" { + if toString(val) == "40103" { + found = true + } + } + } + if found { + ev.MessageID = extractNestedString(m, "messageid", "message_id") + ev.ChatID = extractNestedString(m, "cid", "chatid", "chat_id") + if ev.MessageID == "" { + ev.MessageID = extractNestedString(m, "id") + } + return + } + for _, child := range m { + walk(child) + } + case []any: + for _, child := range m { + walk(child) + } + case string: + // Some sync envelopes carry the event body as an escaped JSON + // string instead of an already-decoded object. + var decoded any + if json.Unmarshal([]byte(m), &decoded) == nil { + walk(decoded) + } + } + } + walk(v) + if !found || ev.MessageID == "" { + return MessageReadEvent{}, false + } + return ev, true +} + +func extractNestedString(m map[string]any, keys ...string) string { + for k, v := range m { + for _, want := range keys { + if strings.EqualFold(k, want) && strings.TrimSpace(toString(v)) != "" { + return strings.TrimSpace(toString(v)) + } + } + } + for _, v := range m { + if child, ok := v.(map[string]any); ok { + if s := extractNestedString(child, keys...); s != "" { + return s + } + } + } + return "" +} + // markAndCheckDedup 提取消息 ID,检查 1 小时内是否已处理;未处理则标记。 // 返回 true 表示应继续处理。移植自 _schedule_debounced_reply 的去重段。 func (a *Account) markAndCheckDedup(decrypted map[string]any, chat *ChatMessage) bool { @@ -183,13 +284,21 @@ func (a *Account) scheduleDebouncedReply(chat ChatMessage) { }) } -// extractMessageID 从 message["1"]["10"]["bizTag"] 或 extJson 中提取 messageId。 -// 移植自 _extract_message_id。 +// extractMessageID 提取闲鱼消息状态接口使用的消息 ID。 +// +// 实时 WS 聊天消息同时包含两种 ID:message["1"]["3"] 是消息在 IM +// 服务中的 PNM ID,/r/MessageStatus/read 使用的正是这个 ID;10.bizTag、 +// extJson 和 reminderUrl 里的 messageId 是通知/推送侧的关联 ID,不能用来 +// 上报会话已读。历史消息接口也返回 PNM ID,因此优先使用字段 3,其他 +// 字段只作为兼容旧消息或缺失字段 3 的兜底。 func extractMessageID(decrypted map[string]any) string { m1, ok := decrypted["1"].(map[string]any) if !ok { return "" } + if id := strings.TrimSpace(toString(m1["3"])); id != "" && id != "" { + return id + } m10, ok := m1["10"].(map[string]any) if !ok { return "" @@ -205,6 +314,43 @@ func extractMessageID(decrypted map[string]any) string { return id } } + if reminderURL, _ := m10["reminderUrl"].(string); reminderURL != "" { + if parsed, err := url.Parse(reminderURL); err == nil { + if id := strings.TrimSpace(parsed.Query().Get("messageId")); id != "" { + return id + } + } + } + return findMessageID(decrypted) +} + +func findMessageID(value any) string { + switch x := value.(type) { + case map[string]any: + for key, child := range x { + if strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id") { + if id := strings.TrimSpace(fmt.Sprint(child)); id != "" && id != "" { + return id + } + } + } + for _, child := range x { + if id := findMessageID(child); id != "" { + return id + } + } + case []any: + for _, child := range x { + if id := findMessageID(child); id != "" { + return id + } + } + case string: + var decoded any + if json.Unmarshal([]byte(x), &decoded) == nil { + return findMessageID(decoded) + } + } return "" } @@ -241,7 +387,13 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) * if i := strings.Index(chatID, "@"); i >= 0 { chatID = chatID[:i] } - senderUserID, _ := m10["senderUserId"].(string) + senderUserID := extractChatSenderUserIDFromMaps(m1, m10) + if isSelfUserID(senderUserID, protocol.TransCookies(cookieStr)["unb"]) { + // The official client echoes messages sent by this account over the + // same WebSocket. They are delivery observations, not new buyer input, + // and must never enter the automatic-reply pipeline. + return nil + } senderName, _ := m10["senderNick"].(string) if strings.TrimSpace(senderName) == "" { senderName, _ = m10["reminderTitle"].(string) @@ -255,11 +407,47 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) * SenderUserID: senderUserID, SenderName: senderName, Text: reminder, + MessageID: extractMessageID(decrypted), ItemID: itemID, Raw: decrypted, } } +func extractChatSenderUserID(decrypted map[string]any) string { + m1, _ := decrypted["1"].(map[string]any) + if m1 == nil { + return "" + } + m10, _ := m1["10"].(map[string]any) + return extractChatSenderUserIDFromMaps(m1, m10) +} + +func extractChatSenderUserIDFromMaps(m1, m10 map[string]any) string { + if m10 != nil { + if sender := strings.TrimSpace(toString(m10["senderUserId"])); sender != "" { + return sender + } + } + // Some echoed messages omit 10.senderUserId but retain the sender in the + // compact 1.1 envelope. + if sender, ok := m1["1"].(map[string]any); ok { + return strings.TrimSpace(toString(sender["1"])) + } + return "" +} + +func extractChatID(decrypted map[string]any) string { + m1, _ := decrypted["1"].(map[string]any) + chatID := strings.TrimSpace(toString(m1["2"])) + return strings.TrimSuffix(chatID, "@goofish") +} + +func isSelfUserID(senderUserID, selfUserID string) bool { + sender := strings.TrimSuffix(strings.TrimSpace(senderUserID), "@goofish") + self := strings.TrimSuffix(strings.TrimSpace(selfUserID), "@goofish") + return sender != "" && self != "" && sender == self +} + // isNonUserChatNotice 判断闲鱼 IM 中不应进入自动回复的系统提示或交易卡片。 // 典型样本: // - contentType=14:“有蚂蚁森林能量可领”“不想宝贝被砍价?设置不砍价回复”“退款成功” diff --git a/internal/engine/dispatch_extra_test.go b/internal/engine/dispatch_extra_test.go index 8e8be9a..e40b921 100644 --- a/internal/engine/dispatch_extra_test.go +++ b/internal/engine/dispatch_extra_test.go @@ -135,6 +135,22 @@ func TestHandleMessage_DedupSkipsRepeat(t *testing.T) { } } +func TestHandleMessage_IgnoresOwnWebSocketEcho(t *testing.T) { + acc, h, _, cleanup := newAccountForTest(t) + defer cleanup() + defer acc.Stop() + + // newAccountForTest 使用 unb=123;模拟同一账号在闲鱼官方客户端发出的 + // 消息回显,不能进入自动回复或业务消息处理链。 + acc.handleMessage(plainChatMessage(t, "官方客户端发送", "123", "chat-own")) + time.Sleep(MessageDebounceDelay + 200*time.Millisecond) + h.mu.Lock() + defer h.mu.Unlock() + if len(h.chats) != 0 { + t.Fatalf("账号自身消息回显不应触发自动回复,got %d", len(h.chats)) + } +} + // TestHandleMessage_NoReminderNoOp 无 reminderContent 的消息不进入回复链也不报错。 func TestHandleMessage_NoReminderNoOp(t *testing.T) { acc, h, _, cleanup := newAccountForTest(t) @@ -522,3 +538,19 @@ func plainChatMessage(t *testing.T, text, senderUserID, chatID string) map[strin } return m } + +func TestExtractMessageReadEvent40103(t *testing.T) { + event, ok := extractMessageReadEvent(map[string]any{ + "1": "4263141580162.PNM", "2": 2, "3": 0, + "4": "64725235816@goofish", "5": 1, "6": 1786945729928, + }) + if !ok || event.MessageID != "4263141580162.PNM" || event.ChatID != "64725235816" || event.ReadAt <= 0 { + t.Fatalf("40103 event=%+v ok=%v", event, ok) + } + batch, ok := extractMessageReadEvent(map[string]any{ + "1": []any{"4263107993838.PNM"}, "2": 2, "3": "64725235816@goofish", "4": 1, + }) + if !ok || batch.MessageID != "4263107993838.PNM" || batch.ChatID != "64725235816" { + t.Fatalf("40103 batch event=%+v ok=%v", batch, ok) + } +} diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index b9175d5..9fffaee 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -102,6 +102,16 @@ func TestExtractChatMessageUsesReminderTitleAsNickname(t *testing.T) { } } +func TestExtractChatMessageIgnoresOwnWebSocketEcho(t *testing.T) { + decrypted := map[string]any{"1": map[string]any{ + "2": "chat-1@goofish", + "10": map[string]any{"reminderContent": "我在官方客户端发送的消息", "senderUserId": "self-1", "senderNick": "我"}, + }} + if chat := extractChatMessage(decrypted, "account-1", "unb=self-1;"); chat != nil { + t.Fatalf("账号自身发送的 WS 回显不应进入自动回复链: %+v", chat) + } +} + func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) { decrypted := mustRefundTradeCard(t) if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil { diff --git a/internal/engine/reply_extra_test.go b/internal/engine/reply_extra_test.go index 835d666..22696e2 100644 --- a/internal/engine/reply_extra_test.go +++ b/internal/engine/reply_extra_test.go @@ -216,17 +216,18 @@ func TestParseMessageIDFromJSON(t *testing.T) { } } -// TestExtractMessageID 优先 bizTag,其次 extJson,无则空。 +// TestExtractMessageID 优先实时消息的 PNM ID,其次兼容 bizTag/extJson,无则空。 func TestExtractMessageID(t *testing.T) { if got := extractMessageID(map[string]any{ "1": map[string]any{ + "3": "4263141580162.PNM", "10": map[string]any{ "bizTag": `{"messageId":"biz-id"}`, "extJson": `{"messageId":"ext-id"}`, }, }, - }); got != "biz-id" { - t.Errorf("bizTag 优先: got %q", got) + }); got != "4263141580162.PNM" { + t.Errorf("PNM 优先: got %q", got) } if got := extractMessageID(map[string]any{ "1": map[string]any{ diff --git a/internal/server/chat_account_tasks_test.go b/internal/server/chat_account_tasks_test.go index 0e42b8d..b45f963 100644 --- a/internal/server/chat_account_tasks_test.go +++ b/internal/server/chat_account_tasks_test.go @@ -121,3 +121,34 @@ func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) { } } } + +func TestFindChatPlatformMessageID(t *testing.T) { + raw := map[string]any{ + "1": map[string]any{ + "2": "64725235816@goofish", + "3": "4263141580162.PNM", + "10": map[string]any{ + "extJson": `{"messageId":"f87f8f6dabca4eff940863ef72a393f7"}`, + }, + }, + } + if got := findChatPlatformMessageID(raw, "64725235816", "f87f8f6dabca4eff940863ef72a393f7"); got != "4263141580162.PNM" { + t.Fatalf("platform message id=%q", got) + } + if got := findChatPlatformMessageID(raw, "other-chat", "f87f8f6dabca4eff940863ef72a393f7"); got != "" { + t.Fatalf("跨会话错误匹配: %q", got) + } +} + +func TestResolveChatReadMessageIDsMigratesLegacyID(t *testing.T) { + srv, store, cleanup := newTestServer(t) + defer cleanup() + raw := `{"1":{"2":"64725235816@goofish","3":"4263141580162.PNM","10":{"extJson":"{\"messageId\":\"f87f8f6dabca4eff940863ef72a393f7\"}"}}}` + if err := store.WSMessages.Add(context.Background(), db.WSMessage{CookieID: "acc1", Direction: "in", ParsedJSON: raw, ParseStatus: "decrypted"}); err != nil { + t.Fatal(err) + } + got := srv.resolveChatReadMessageIDs(context.Background(), "acc1", "64725235816", []map[string]any{{"messageId": "f87f8f6dabca4eff940863ef72a393f7"}}) + if len(got) != 1 || got[0]["messageId"] != "4263141580162.PNM" { + t.Fatalf("resolved=%+v", got) + } +} diff --git a/internal/server/chat_handlers.go b/internal/server/chat_handlers.go index 7068be7..355ff4a 100644 --- a/internal/server/chat_handlers.go +++ b/internal/server/chat_handlers.go @@ -2,7 +2,10 @@ package server import ( "context" + "encoding/json" + "fmt" "io" + "log/slog" "net/http" "strconv" "strings" @@ -367,8 +370,9 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) { func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) { var input struct { - AccountID string `json:"account_id"` - ChatID string `json:"chat_id"` + AccountID string `json:"account_id"` + ChatID string `json:"chat_id"` + MessageIDs []map[string]any `json:"message_ids"` } if decodeJSON(r, &input) != nil || input.ChatID == "" { writeErr(w, http.StatusBadRequest, "请求格式错误") @@ -378,14 +382,162 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusForbidden, "无权操作该账号") return } + slog.Info("收到聊天已读请求", "account", input.AccountID, "chat_id", input.ChatID, "message_count", len(input.MessageIDs)) + if len(input.MessageIDs) == 0 { + // 兼容只传会话 ID 的调用方:从本地最近消息补齐平台消息 ID。 + userID := auth.SessionFromContext(r.Context()).UserID + if rows, err := s.Store.Chats.ListMessages(r.Context(), userID, input.AccountID, input.ChatID, 0, 200); err == nil { + for _, row := range rows { + if row.Direction == "incoming" && row.MessageType != "system" { + input.MessageIDs = append(input.MessageIDs, map[string]any{"messageId": row.MessageKey}) + } + } + } + } + // 旧版本把实时 WS 通知里的 bizTag/extJson messageId 当成了平台消息 + // ID,数据库里会留下 32 位关联 ID。闲鱼的 read 接口实际要求 1.3 的 + // PNM ID;这里从已保存的解密 WS 诊断帧把旧 ID 转回 PNM,避免升级后 + // 仍有历史实时消息无法被标记已读。 + input.MessageIDs = s.resolveChatReadMessageIDs(r.Context(), input.AccountID, input.ChatID, input.MessageIDs) sess := auth.SessionFromContext(r.Context()) if err := s.Store.Chats.MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil { writeErr(w, http.StatusInternalServerError, "更新已读状态失败") return } + if s.Manager != nil { + if sender, ok := s.Manager.GetInstance(input.AccountID); ok { + if reader, ok := sender.(interface { + MarkChatRead(context.Context, string, []map[string]any) error + }); ok { + if err := reader.MarkChatRead(r.Context(), input.ChatID, input.MessageIDs); err != nil { + slog.Warn("上报闲鱼已读状态失败", "account", input.AccountID, "chat_id", input.ChatID, "err", err) + } + } + } + } writeJSON(w, http.StatusOK, map[string]any{"success": true}) } +func (s *Server) resolveChatReadMessageIDs(ctx context.Context, accountID, chatID string, messageIDs []map[string]any) []map[string]any { + if s == nil || s.Store == nil || s.Store.DB == nil { + return messageIDs + } + resolved := make([]map[string]any, 0, len(messageIDs)) + seen := make(map[string]struct{}, len(messageIDs)) + for _, item := range messageIDs { + id := strings.TrimSpace(fmt.Sprint(item["messageId"])) + if id == "" || id == "" { + continue + } + if !strings.HasSuffix(id, ".PNM") { + if platformID := s.lookupChatPlatformMessageID(ctx, accountID, chatID, id); platformID != "" { + slog.Info("已将旧聊天消息 ID 转换为平台 PNM", "account", accountID, "chat_id", chatID, "old_message_id", id, "message_id", platformID) + id = platformID + } else { + slog.Warn("未找到旧聊天消息对应的 PNM,跳过已读上报", "account", accountID, "chat_id", chatID, "message_id", id) + continue + } + } + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + copyItem := make(map[string]any, len(item)+1) + for key, value := range item { + copyItem[key] = value + } + copyItem["messageId"] = id + resolved = append(resolved, copyItem) + } + return resolved +} + +func (s *Server) lookupChatPlatformMessageID(ctx context.Context, accountID, chatID, legacyID string) string { + rows, err := s.Store.DB.QueryContext(ctx, `SELECT parsed_json FROM ws_messages + WHERE cookie_id=? AND direction='in' AND parse_status='decrypted' AND parsed_json LIKE ? + ORDER BY id DESC LIMIT 20`, accountID, "%"+legacyID+"%") + if err != nil { + return "" + } + defer rows.Close() + for rows.Next() { + var raw string + if rows.Scan(&raw) != nil { + continue + } + var decoded any + if json.Unmarshal([]byte(raw), &decoded) != nil { + continue + } + if platformID := findChatPlatformMessageID(decoded, chatID, legacyID); platformID != "" { + return platformID + } + } + return "" +} + +func findChatPlatformMessageID(value any, chatID, legacyID string) string { + var walk func(any) string + walk = func(current any) string { + switch typed := current.(type) { + case map[string]any: + if m10, ok := typed["10"]; ok && chatReadValueContainsID(m10, legacyID) { + if candidate := strings.TrimSpace(fmt.Sprint(typed["3"])); strings.HasSuffix(candidate, ".PNM") { + if cid := strings.TrimSuffix(strings.TrimSpace(fmt.Sprint(typed["2"])), "@goofish"); cid == "" || cid == chatID { + return candidate + } + } + } + for _, child := range typed { + if candidate := walk(child); candidate != "" { + return candidate + } + } + case []any: + for _, child := range typed { + if candidate := walk(child); candidate != "" { + return candidate + } + } + case string: + var nested any + if json.Unmarshal([]byte(typed), &nested) == nil { + return walk(nested) + } + } + return "" + } + return walk(value) +} + +func chatReadValueContainsID(value any, legacyID string) bool { + switch typed := value.(type) { + case map[string]any: + for key, child := range typed { + if strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id") { + if strings.TrimSpace(fmt.Sprint(child)) == legacyID { + return true + } + } + if chatReadValueContainsID(child, legacyID) { + return true + } + } + case []any: + for _, child := range typed { + if chatReadValueContainsID(child, legacyID) { + return true + } + } + case string: + var nested any + if json.Unmarshal([]byte(typed), &nested) == nil { + return chatReadValueContainsID(nested, legacyID) + } + } + return false +} + func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) { if s.chat == nil { writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用") diff --git a/internal/server/item_handlers.go b/internal/server/item_handlers.go index 5105626..4dcbc46 100644 --- a/internal/server/item_handlers.go +++ b/internal/server/item_handlers.go @@ -110,7 +110,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { defer cancel() client := s.mtopClient() mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest) - res, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{ + publishReq := mtop.PublishItemRequest{ Title: title, Description: description, PriceCents: priceCents, @@ -121,7 +121,8 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { Virtual: true, Location: selectedLocation, Images: images, - }) + } + res, callErr := client.PublishItem(mtopCtx, cookieValue, publishReq) runtimeCookie := "" runtimeCookieChanged := false var responseCookieErr error @@ -151,25 +152,47 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { if responseCookieErr != nil { callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", responseCookieErr)) } - s.recoverExpiredMTOPSession(r.Context(), cookieID, callErr) - var perr *mtop.PublishError - if errors.As(callErr, &perr) { - status := http.StatusBadGateway - msg := perr.Error() - if perr.Code == mtop.PublishErrorStockPermissionMissing { - status = http.StatusForbidden - msg = "该账号没有库存发布权限,无法按库存数量发布商品" + // Session 失效是账号级凭证问题。续期成功后,当前发布请求仍然 + // 可以安全重试一次:平台已经明确拒绝了这次业务调用,不会把 + // 同一商品重复发布。重试前重新读取 Cookie,避免继续使用旧会话。 + if mtop.IsSessionExpiredErr(callErr) && s.recoverExpiredMTOPSession(r.Context(), cookieID, callErr) { + retryRes, retryErr, retryCookieErr, credentialChanged := s.retryPublishItemAfterRenewal(ctx, cookieID, userID, publishReq) + if credentialChanged { + writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") + return } - writeJSON(w, status, map[string]any{ - "success": false, - "code": perr.Code, - "message": msg, - "ret": perr.Ret, - }) + if retryErr == nil && retryRes != nil { + res = retryRes + callErr = nil + responseCookieErr = retryCookieErr + } else if retryErr != nil { + callErr = retryErr + responseCookieErr = retryCookieErr + } + } + if callErr == nil { + // The renewed attempt succeeded; continue through the normal local + // persistence and success response path below. + } else { + var perr *mtop.PublishError + if errors.As(callErr, &perr) { + status := http.StatusBadGateway + msg := perr.Error() + if perr.Code == mtop.PublishErrorStockPermissionMissing { + status = http.StatusForbidden + msg = "该账号没有库存发布权限,无法按库存数量发布商品" + } + writeJSON(w, status, map[string]any{ + "success": false, + "code": perr.Code, + "message": msg, + "ret": perr.Ret, + }) + return + } + writeErr(w, http.StatusBadGateway, callErr.Error()) return } - writeErr(w, http.StatusBadGateway, callErr.Error()) - return } if res == nil || strings.TrimSpace(res.ItemID) == "" { writeJSON(w, http.StatusBadGateway, map[string]any{ @@ -233,6 +256,51 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { }) } +// retryPublishItemAfterRenewal re-reads the account credential after a +// successful Session renewal and repeats one rejected publish attempt. The +// caller already owns the parsed images and request payload, so this method +// deliberately does not re-parse the multipart body. +func (s *Server) retryPublishItemAfterRenewal( + ctx context.Context, + cookieID string, + userID int64, + req mtop.PublishItemRequest, +) (result *mtop.PublishItemResult, callErr, cookieErr error, credentialChanged bool) { + credentialUnlock := s.Store.LockAccountCredentials(cookieID) + defer credentialUnlock() + latest, err := s.Store.Cookies.GetDetails(ctx, cookieID) + if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) { + return nil, nil, nil, true + } + cookieValue := latest.Value + mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest) + result, callErr = s.mtopClient().PublishItem(mtopCtx, cookieValue, req) + value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession) + if persistErr != nil { + cookieErr = persistErr + if s.Logger != nil { + s.Logger.Error("保存重试发布响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr) + } + } else if handled { + if valueChanged { + s.updateRunningCookie(ctx, cookieID, value) + } + } else if callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != cookieValue { + if err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, result.UpdatedCookies, userID); err != nil { + cookieErr = err + if s.Logger != nil { + s.Logger.Error("保存重试发布响应 Cookie 失败", "cookie_id", cookieID, "err", err) + } + } else { + s.updateRunningCookie(ctx, cookieID, result.UpdatedCookies) + } + } + if cookieErr != nil && callErr != nil { + callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", cookieErr)) + } + return result, callErr, cookieErr, false +} + func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, error) { if r.MultipartForm == nil || r.MultipartForm.File == nil { return nil, errors.New("至少上传 1 张商品图片") diff --git a/internal/server/item_handlers_test.go b/internal/server/item_handlers_test.go index 0cfb259..2d88435 100644 --- a/internal/server/item_handlers_test.go +++ b/internal/server/item_handlers_test.go @@ -317,6 +317,33 @@ func TestPublishItemReportsRemoteSuccessLocalSaveFailure(t *testing.T) { } } +func TestRetryPublishItemAfterRenewalUsesFreshCredential(t *testing.T) { + srv, store, cleanup := newTestServer(t) + defer cleanup() + admin, err := store.Users.GetByUsername(context.Background(), "admin") + if err != nil { + t.Fatal(err) + } + if err := store.Cookies.UpdateValueExisting(context.Background(), "acc1", "unb=123; fresh=1"); err != nil { + t.Fatal(err) + } + var gotCookies string + srv.MTop = &stubPublishMTop{publish: func(_ context.Context, cookies string, _ mtop.PublishItemRequest) (*mtop.PublishItemResult, error) { + gotCookies = cookies + return &mtop.PublishItemResult{ItemID: "retry-item", Title: "重试商品"}, nil + }} + result, callErr, cookieErr, changed := srv.retryPublishItemAfterRenewal( + context.Background(), "acc1", admin.ID, + mtop.PublishItemRequest{Title: "重试商品", PriceCents: 100, Quantity: 1}, + ) + if changed || callErr != nil || cookieErr != nil || result == nil || result.ItemID != "retry-item" { + t.Fatalf("重试结果异常: result=%+v callErr=%v cookieErr=%v changed=%v", result, callErr, cookieErr, changed) + } + if !strings.Contains(gotCookies, "fresh=1") { + t.Fatalf("重试未读取续期后的 Cookie: %q", gotCookies) + } +} + // TestPublishItemStockPermissionMissing 库存权限缺失应 403。 func TestPublishItemStockPermissionMissing(t *testing.T) { srv, _, cleanup := newTestServer(t) diff --git a/internal/webui/static/assets/index-CHuZDt8D.js b/internal/webui/static/assets/index-CHuZDt8D.js deleted file mode 100644 index 88fb845..0000000 --- a/internal/webui/static/assets/index-CHuZDt8D.js +++ /dev/null @@ -1,19 +0,0 @@ -import{j as e,r,c as ys,b as qe,d as Ua}from"./react-vendor-C_od1ZSF.js";import{L as Wa,U as ha,M as is,C as os,B as ga,S as ba,Z as cs,a as jt,b as js,G as As,c as _s,d as Ns,e as Ja,f as rt,A as $s,D as Va,g as Ps,P as fa,h as qt,E as ya,T as Qa,i as Ga,j as Pe,X as Me,k as Ka,l as Ha,m as vs,n as ja,o as He,Q as Xt,p as xt,q as Ke,r as yt,s as Tt,t as Rs,R as ze,u as _a,v as Za,w as Qe,K as Ya,x as dt,y as lt,z as et,F as Es,H as Nt,I as _t,J as Dt,N as Na,O as Xa,V as Ds,W as Ts,Y as el,_ as tl,$ as sl,a0 as al,a1 as es,a2 as Bt,a3 as ds,a4 as ll,a5 as rl,a6 as xs,a7 as Ms,a8 as nl,a9 as il,aa as Mt,ab as qs,ac as Gt,ad as va,ae as ol,af as cl,ag as Zt,ah as wa,ai as dl,aj as xl,ak as ml,al as pl,am as ul,an as hl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as gl,X as Bs,Y as zs,T as Ut,a as bl,C as ts,A as fl,b as yl,c as jl,P as Us,d as Ws,L as _l}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const _ of m)if(_.type==="childList")for(const N of _.addedNodes)N.tagName==="LINK"&&N.rel==="modulepreload"&&i(N)}).observe(document,{childList:!0,subtree:!0});function l(m){const _={};return m.integrity&&(_.integrity=m.integrity),m.referrerPolicy&&(_.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?_.credentials="include":m.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function i(m){if(m.ep)return;m.ep=!0;const _=l(m);fetch(m.href,_)}})();const Nl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,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"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="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 ${t} 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:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),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(Nl,{className:a})})]})]}),vl=({activeTab:t,isAdmin:a=!1,collapsed:l,onToggleCollapsed:i,onNavigate:m,onLogout:_})=>{const[N,I]=r.useState({version:"dev",commit:"unknown"});r.useEffect(()=>{const j=new AbortController;return fetch("/health",{signal:j.signal}).then(F=>F.ok?F.json():Promise.reject(new Error("health request failed"))).then(F=>I({version:String(F.version||"dev"),commit:String(F.commit||"unknown")})).catch(F=>{F instanceof DOMException&&F.name}),()=>j.abort()},[]);const g=[{id:"dashboard",icon:Wa,label:"仪表盘"},{id:"accounts",icon:ha,label:"账号管理"},{id:"chat",icon:is,label:"在线聊天"},{id:"cards",icon:os,label:"卡密库存"},{id:"items",icon:ga,label:"商品列表"},{id:"orders",icon:ba,label:"订单管理"},{id:"rules",icon:cs,label:"自动化规则"},{id:"notifications",icon:jt,label:"通知设置"},...a?[{id:"settings",icon:js,label:"系统与AI"}]:[]],C=/^\d+\.\d+\.\d+$/.test(N.version)?`v${N.version}`:N.version;return e.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${l?"w-16":"w-64"}`,children:[e.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${l?"justify-center px-2":"gap-3 px-5"}`,children:[e.jsx(ms,{sizeClass:"h-10 w-10"}),!l&&e.jsxs("div",{className:"min-w-0 leading-tight",children:[e.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),e.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),e.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${l?"px-2":"px-3"}`,"aria-label":"主导航",children:g.map(j=>{const F=j.icon,G=t===j.id;return e.jsx(ys.Fragment,{children:e.jsxs("button",{type:"button",title:l?j.label:void 0,"aria-label":j.label,"aria-current":G?"page":void 0,onClick:()=>m(j.id),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${l?"justify-center":"gap-3 px-3.5"} ${G?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(F,{className:`h-[19px] w-[19px] shrink-0 ${G?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!l&&e.jsx("span",{className:"truncate text-sm font-bold",children:j.label}),G&&!l&&e.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},j.id)})}),e.jsxs("div",{children:[e.jsx("div",{title:l?`版本 ${N.version} · ${N.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${l?"flex justify-center px-1":"px-6"}`,children:l?e.jsx(As,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${N.version}`}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[e.jsx(As,{className:"h-3.5 w-3.5"}),"运行版本"]}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[e.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:C}),e.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:N.commit})]})]})}),e.jsxs("div",{className:`space-y-2 p-2 ${l?"":"p-3"}`,children:[e.jsxs("button",{type:"button",onClick:i,title:l?"展开侧边栏":"收起侧边栏","aria-label":l?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${l?"justify-center":"gap-3 px-3"}`,children:[l?e.jsx(_s,{className:"h-5 w-5"}):e.jsx(Ns,{className:"h-5 w-5"}),!l&&e.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),e.jsxs("button",{type:"button",onClick:_,title:l?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${l?"justify-center":"gap-3 px-3"}`,children:[e.jsx(Ja,{className:"h-5 w-5"}),!l&&e.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},wl=3e4,kl=10*6e4;let ss=!1;const ka=()=>{ss||typeof window>"u"||(ss=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{ss=!1}))},Cl=t=>{if(!t)return"";const a=new URLSearchParams;for(const[i,m]of Object.entries(t))m!=null&&a.set(i,String(m));const l=a.toString();return l?`?${l}`:""},Yt=async(t,a,l={})=>{var C;const i=Cl(l.params),m=`${a}${i}`,_=Ca(l.signal,l.timeoutMs??wl);let N;try{N=await fetch(m,{method:t,credentials:"include",signal:_.signal,headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)})}catch(j){throw _.signal.aborted?new Error((C=l.signal)!=null&&C.aborted?"请求已取消":"请求超时,请稍后重试"):j}finally{_.cleanup()}const g=(N.headers.get("content-type")||"").includes("application/json");if(!N.ok){N.status===401&&!l.skipAuthLogout&&ka();const j=g?await N.json().catch(()=>{}):await N.text().catch(()=>{}),F=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(F||`请求失败: ${N.status}`)}return g?await N.json():await N.text()},Le=async(t,a,l)=>Yt("GET",t,{params:a,...l}),Ce=async(t,a,l)=>Yt("POST",t,{body:a,...l}),Be=async(t,a,l)=>Yt("PUT",t,{body:a,...l}),Ze=async(t,a,l)=>Yt("DELETE",t,{params:a,...l}),wt=async(t,a,l={})=>{var g;const i=Ca(l.signal,l.timeoutMs??kl);let m;try{m=await fetch(t,{method:"POST",credentials:"include",signal:i.signal,body:a})}catch(C){throw i.signal.aborted?new Error((g=l.signal)!=null&&g.aborted?"请求已取消":"上传超时,请稍后重试"):C}finally{i.cleanup()}const I=(m.headers.get("content-type")||"").includes("application/json")?await m.json().catch(()=>{}):await m.text().catch(()=>{});if(!m.ok){m.status===401&&ka();const C=typeof I=="string"?I:(I==null?void 0:I.detail)||(I==null?void 0:I.message)||(I==null?void 0:I.msg),j=new Error(C||"请求失败: "+m.status);throw j.payload=I,j}return I},Ca=(t,a)=>{const l=new AbortController,i=()=>l.abort(t==null?void 0:t.reason);t!=null&&t.aborted?i():t==null||t.addEventListener("abort",i,{once:!0});const m=globalThis.setTimeout(()=>l.abort(new DOMException("timeout","TimeoutError")),Math.max(1,a));return{signal:l.signal,cleanup:()=>{globalThis.clearTimeout(m),t==null||t.removeEventListener("abort",i)}}},Kt=t=>{const a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${a}-${l}-${i}`},ws=(t,a)=>{const l=new Date(t);return l.setHours(12,0,0,0),l.setDate(l.getDate()+a),l},ps=(t,a)=>({startDate:Kt(ws(t,-(a-1))),endDate:Kt(t)}),Js=(t,a=new Date,l="",i="")=>{if(t==="custom"&&l&&i){if(l>i)throw new Error("开始日期不能晚于结束日期");return{startDate:l,endDate:i}}return t==="yesterday"?ps(ws(a,-1),1):ps(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Sl=t=>{const a=new Date(`${t.startDate}T12:00:00`),l=new Date(`${t.endDate}T12:00:00`),i=Math.round((l.getTime()-a.getTime())/864e5)+1,m=ws(a,-1);return ps(m,i)},Ll=t=>{const a={...t};if("renewal_log_retention_days"in a){const l=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(l)?l:10}return a},Ol=async t=>Ce("/login",t,{skipAuthLogout:!0}),Il=async t=>Ce("/initialize",{password:t},{skipAuthLogout:!0}),Sa=async()=>Le("/verify"),Al=async()=>Ce("/logout",{}),$l=async t=>Be("/account/credentials",t),Pl=(t,a)=>{const l=t.avatar_url||"";if(!l)return"";try{const i=new URL(l,window.location.origin);return i.hostname.endsWith("alicdn.com")&&i.searchParams.set("_v",a),i.toString()}catch{return l}},Ft=async t=>{const a=await Le("/cookies/details",void 0,t),l=Date.now().toString();return a.map(i=>({id:i.id,value:"",cookie:"",enabled:i.enabled,auto_confirm:i.auto_confirm,remark:i.remark,note:i.remark,pause_duration:i.pause_duration,paused_until:Number(i.paused_until||0),paused:i.paused===!0,username:i.username||"",login_password:"",show_browser:i.show_browser===!0||i.show_browser===1||i.show_browser==="1"||i.show_browser==="true",nickname:i.nickname||i.remark||`账号 ${i.id.substring(0,6)}`,avatar_url:Pl(i,l),profile_error:i.profile_error||"",ai_enabled:!1,auto_rate_enabled:i.auto_rate_enabled===!0||i.auto_rate_enabled===1,rate_content:i.rate_content||"不错的买家,交易愉快",auto_polish_enabled:i.auto_polish_enabled===!0||i.auto_polish_enabled===1,polish_time:i.polish_time||"03:00",last_rate_scan_at:Number(i.last_rate_scan_at||0),last_polish_date:i.last_polish_date||"",last_polish_at:Number(i.last_polish_at||0)}))},Rl=async t=>Le(`/api/account-tasks/${t}`),Vs=async(t,a)=>Be(`/api/account-tasks/${t}`,a),El=async(t,a)=>Ce(`/api/account-tasks/${t}/run`,{task_type:a},{timeoutMs:12e4}),as=async(t,a,l,i=!1)=>{const m=await Le("/api/chat/sessions",{account_id:t,cursor:a,refresh:i?1:void 0},i?{timeoutMs:6e4,...l}:l);return{sessions:m.sessions||[],has_more:m.has_more===!0,next_cursor:m.next_cursor}},us=async(t,a,l,i,m)=>{const _=await Le("/api/chat/messages",{account_id:t,chat_id:a,cursor:l,before_id:i},m);return{messages:_.messages||[],has_more:_.has_more===!0,next_cursor:_.next_cursor,session:_.session}},Dl=async(t,a,l,i)=>(await us(t,a,void 0,l,i)).messages,Tl=async t=>Ce("/api/chat/messages",t),Ml=async t=>{const a=new FormData;return Object.entries(t).forEach(([l,i])=>a.append(l,i)),wt("/api/chat/images",a,{timeoutMs:12e4})},Qs=async(t,a)=>Ce("/api/chat/read",{account_id:t,chat_id:a}),hs=async t=>Le("/cookies/runtime-status",void 0,t),ql=async t=>Ce("/qr-login/generate",void 0,{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),Fl=async(t,a)=>Le(`/qr-login/check/${t}`,void 0,{signal:a,timeoutMs:1e4}),Bl=async(t,a)=>Ce(`/qr-login/complete-verification/${t}`,{target_account_id:a||""}),zl=async(t,a)=>Be(`/cookies/${t}/status`,{enabled:a}),Ul=async t=>Ze(`/cookies/${t}`),Wl=async(t,a)=>Be(`/cookies/${t}/pause-duration`,{pause_duration:a}),Jl=async(t,a)=>Be(`/cookies/${t}/settings`,a),Vl=async t=>Le(`/cookies/${t}/long-login`),Ql=async(t,a)=>Be(`/cookies/${t}/long-login`,{enabled:a}),Gl=async t=>Ce("/password-login",t),Kl=async(t,a)=>Le(`/password-login/check/${t}`,void 0,{signal:a,timeoutMs:1e4}),Hl=async t=>Ze(`/password-login/cancel/${t}`),Zl=async t=>Ce(`/cookies/${t}/refresh-profile`,{}),Yl=async t=>Le("/ai-reply-settings",void 0,t),La=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Xl=async(t,a,l=1,i=20,m)=>{const _={page:l,page_size:i};t&&(_.cookie_id=t),a&&a!=="all"&&(_.status=a),m!=null&&m.trim()&&(_.search=m.trim());const N=await Le("/api/orders",_),g=(N.orders||N.data||[]).map(C=>({...C,id:C.id||C.order_id,status:La(C.status||C.order_status),quantity:Number(C.quantity||1)}));return{success:!0,data:g,total:N.total||g.length,page:N.page||l,page_size:N.page_size||i,total_pages:N.total_pages||1}},er=async(t,a)=>Be(`/api/orders/${t}`,a),tr=async t=>Ze(`/api/orders/${t}`),sr=async(t,a)=>{const l=new FormData;return t&&l.append("cookie_id",t),a&&l.append("status",a),wt("/api/orders/refresh",l)},ar=async t=>Ce(`/api/orders/${t}/refresh`),lr=async(t,a)=>Ce("/api/orders/manual-ship",{order_ids:t,ship_mode:a}),rr=async t=>t instanceof FormData?wt("/api/orders/import",t):Ce("/api/orders/import",t),nr=async()=>Le("/dashboard/stats"),Gs=async(t=7)=>{let a;if(typeof t=="number"){const l=new Date,i=new Date;i.setDate(i.getDate()-t),a={start_date:Kt(i),end_date:Kt(l)}}else a=t;return Le("/analytics/orders",{...a,timezone_offset_minutes:-new Date().getTimezoneOffset()})},ir=async t=>{const a=await Le("/analytics/orders/valid",{start_date:t.start_date,end_date:t.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()}),i=(Array.isArray(a)?a:a.orders||[]).map(m=>({...m,id:m.id||m.order_id,status:La(m.status||m.order_status),quantity:Number(m.quantity||1)}));return{orders:i,total:Array.isArray(a)?i.length:Number(a.total??i.length),truncated:Array.isArray(a)?!1:a.truncated===!0}},or=t=>{let a=t.api_config;if(typeof a=="string"&&a.trim())try{a=JSON.parse(a)}catch{a=void 0}return{...t,api_config:a||void 0}},Oa=t=>({...t,api_config:t.api_config?JSON.stringify(t.api_config):""}),Xe=async()=>{const t=await Le("/cards");return(Array.isArray(t)?t:(t==null?void 0:t.cards)||[]).map(or)},cr=async t=>Ce("/cards",Oa(t)),Ks=async(t,a)=>Be(`/cards/${t}`,Oa(a)),dr=async t=>Ze(`/cards/${t}`),xr=async t=>{const a=new FormData;return a.append("file",t),wt("/cards/batch",a)},mr=async(t,a)=>Ce(`/cards/${t}/append-data`,{content:a}),ls=t=>t===!0||t===1||t==="1",vt=async t=>{const a=await Le("/items",void 0);return(Array.isArray(a)?a:a.items||[]).map(i=>({...i,id:i.id||`${i.cookie_id}-${i.item_id}`,is_multi_spec:ls(i.is_multi_spec),is_multi_qty_ship:ls(i.is_multi_qty_ship??i.multi_quantity_delivery),multi_quantity_delivery:ls(i.multi_quantity_delivery??i.is_multi_qty_ship)}))},pr=async t=>Ce("/items/get-all-from-account",{cookie_id:t}),ur=async(t,a)=>Ze(`/items/${t}/${a}`),hr=async(t,a)=>Ce(`/items/${t}`,a),gr=async t=>{const a=new FormData;a.set("cookie_id",t.cookie_id),a.set("title",t.title),a.set("description",t.description),a.set("price",t.price),a.set("original_price",t.original_price||""),a.set("quantity",String(t.quantity)),a.set("postage_mode",t.postage_mode),a.set("postage",t.postage||""),t.location&&a.set("location",JSON.stringify(t.location));for(const l of t.images)a.append("images",l);return wt("/items/publish",a)},br=async(t,a)=>Ce("/items/publish-categories/recommend",{cookie_id:t,keyword:a}),fr=async t=>{const a=new FormData;return a.set("file",t.file),t.imagesZip&&a.set("images_zip",t.imagesZip),t.defaultCookieId&&a.set("default_cookie_id",t.defaultCookieId),a.set("fallback_category_id",t.fallbackCategory.catId),a.set("fallback_category_name",t.fallbackCategory.catName),a.set("fallback_channel_category_id",t.fallbackCategory.channelCatId||""),a.set("fallback_tb_category_id",t.fallbackCategory.tbCatId||""),t.location&&a.set("location",JSON.stringify(t.location)),wt("/items/publish-batches/preview",a)},yr=async t=>Ce("/items/publish-batches",{preview_id:t}),bt=async t=>Le(`/items/publish-batches/${t}`),Hs=async(t=20)=>{const a=await Le("/items/publish-batches",{limit:t});return Array.isArray(a)?a:a.batches||[]},jr=async t=>Ze(`/items/publish-batches/${t}`),_r=async t=>Ce(`/items/publish-batches/${t}/cancel`,{}),Nr=async t=>Ce(`/items/publish-batches/${t}/retry-failed`,{}),vr=async(t,a,l)=>Be(`/items/${t}/${a}`,l),Ia=t=>t.map(a=>{var l,i;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((l=(a.actions||[]).find(m=>m.action_type==="send_card"))==null?void 0:l.card_id)||0),card_group_name:((i=(a.actions||[]).find(m=>m.action_type==="send_card"))==null?void 0:i.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(m=>({id:m.id?String(m.id):void 0,action_type:m.action_type,card_id:Number(m.card_id||0),card_name:m.card_name||"",delivery_count:Number(m.delivery_count||1),message_template:m.message_template||"",delay_seconds:Number(m.delay_seconds||0),config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:Number(m.sort_order||0)})),variants:(a.actions||[]).filter(m=>m.action_type==="send_card").map(m=>{let _={};try{_=JSON.parse(m.config_json||"{}")}catch{}return{id:m.id?String(m.id):void 0,spec_name:_.spec_name||"",spec_value:_.spec_value||"",card_id:Number(m.card_id||0),card_name:m.card_name||"",delivery_count:Number(m.delivery_count||1),enabled:m.enabled!==!1,delay_override:_.delay_override===!0,delay_seconds:Number(m.delay_seconds||0),config_json:m.config_json||"{}"}})}}),gs=async()=>{const t=await Le("/automation-rules"),a=Array.isArray(t)?t:t.data||t.rules||[];return Ia(a)},wr=async({cookieId:t,triggerType:a,enabled:l,search:i,page:m=1,pageSize:_=10}={})=>{const N=await Le("/automation-rules",{page:m,page_size:_,cookie_id:t||void 0,trigger_type:a||void 0,enabled:l,search:(i==null?void 0:i.trim())||void 0}),I=Ia(Array.isArray(N)?N:N.data||N.rules||[]);return{success:!0,data:I,total:Number(N.total??I.length),page:Number(N.page??m),page_size:Number(N.page_size??_),total_pages:Number(N.total_pages??(I.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(N.trigger_counts||{}).map(([g,C])=>[g,Number(C)]))}},kr=(t,a)=>{if(t!=="order_paid")return a.map((m,_)=>({...m,sort_order:m.sort_order||_+1}));const l=a.filter(m=>m.action_type==="send_card").map((m,_)=>({...m,sort_order:_+1})),i=a.filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment");return[...l,...i.map((m,_)=>({...m,sort_order:l.length+_+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:l.length+i.length+1}]},Zs=async t=>{const a=t.trigger_type||"order_paid",i=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[a]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),m=(t.actions||[]).filter(g=>g.action_type!=="send_card"&&g.action_type!=="confirm_shipment"),_=t.variants&&t.variants.length>0?[...t.variants.map((g,C)=>({action_type:"send_card",card_id:g.card_id,delivery_count:g.delivery_count||1,enabled:g.enabled!==!1,sort_order:C+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})})),...m]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],N=kr(a,_),I={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||i||"自动化规则",trigger_type:a,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:N.map((g,C)=>({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||C+1}))};return t.id?Be(`/automation-rules/${t.id}`,I):Ce("/automation-rules",I)},Cr=async t=>Ze(`/automation-rules/${t}`),Sr=async()=>{const t=await Le("/automation-issues");return{runs:Array.isArray(t==null?void 0:t.runs)?t.runs:[],pending_tasks:Array.isArray(t==null?void 0:t.pending_tasks)?t.pending_tasks:[]}},Lr=async(t,a)=>Ce(`/automation-runs/${t}/resolve`,{resolution:a}),Or=async(t,a)=>Ce(`/automation-pending-tasks/${t}/resolve`,{resolution:a}),Ir=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Ar=async t=>{const a=await Le(`/keywords-with-type/${t}`);return Array.isArray(a)?a.map(Ir):[]},$r=async t=>t?(await Ar(t)).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||""})):[],Pr=async(t,a)=>{const l=t.type||"text",i={keyword:t.keyword||"",reply:l==="text"&&t.reply_content||"",item_id:t.item_id||"",type:l,image_url:l==="image"&&t.image_url||""};return t.id?Be(`/keywords-with-type/${a}/${t.id}`,i):Ce(`/keywords-with-item-id/${a}`,i)},Rr=async(t,a)=>Ze(`/keywords-with-type/${a}/${t}`),Aa=async()=>{const t=await Le("/system-settings");return Ll(t.data||t)},$a=async t=>{const a=Object.fromEntries(Object.entries(t).filter(([,l])=>l!=null));return Be("/system-settings",a)},Er=async(t,a)=>Le(`/ai-reply-settings/${t}`,void 0,a),Dr=async(t,a)=>{const l={ai_enabled:a.ai_enabled??!1,max_discount_percent:a.max_discount_percent??10,max_discount_amount:a.max_discount_amount??100,max_bargain_rounds:a.max_bargain_rounds??3,custom_prompts:a.custom_prompts??""};return Be(`/ai-reply-settings/${t}`,l)},Tr=async(t,a="")=>(await Ce("/ai-models",{base_url:t,api_key:a})).models||[],Mr=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const a=JSON.parse(t);if(Array.isArray(a))return a.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(a=>a.trim()).filter(Boolean)},Pa=t=>{const a=Array.from(new Set((t||[]).filter(Boolean)));return a.length>0?JSON.stringify(a):""},Ra=async t=>({success:!0,data:(await Le("/notification-channels",void 0,t)||[]).map(i=>{let m;try{m=typeof i.config=="string"?JSON.parse(i.config):i.config}catch{m={}}return{id:String(i.id),name:i.name,type:i.type==="ding_talk"?"dingtalk":i.type==="lark"?"feishu":i.type,config:m,event_types:Mr(i.event_types),enabled:i.enabled,created_at:i.created_at,updated_at:i.updated_at}})}),qr=async t=>Ce("/notification-channels",{...t,config:JSON.stringify(t.config),event_types:Pa(t.event_types)}),Ys=async(t,a)=>{const l={...a};return"config"in a&&(l.config=JSON.stringify(a.config)),"event_types"in a&&(l.event_types=Pa(a.event_types)),Be(`/notification-channels/${t}`,l)},Fr=async t=>Ze(`/notification-channels/${t}`),Br=async(t,a)=>{const l=await Le(`/message-notifications/${t}`,void 0,a);return(l==null?void 0:l.channel_ids)||[]},zr=async t=>Ce(`/notification-channels/${t}/test`,{}),Xs=async()=>Le("/api/default-replies"),Ur=async t=>{const a=await Le(`/api/default-reply/${t}`);return{cookie_id:t,enabled:a.enabled||!1,reply_content:a.reply_content||"",reply_once:a.reply_once||!1,reply_image_url:a.reply_image_url||""}},Wr=async(t,a)=>Be(`/api/default-reply/${t}`,{enabled:a.enabled??!1,reply_content:a.reply_content||"",reply_once:a.reply_once??!1,reply_image_url:a.reply_image_url||""}),Jr=async t=>Ze(`/api/default-reply/${t}`),Vr=async t=>Ce(`/api/default-reply/${t}/clear-records`,{}),At=t=>String(t).padStart(2,"0"),bs=t=>{if(t==null||t==="")return"-";const a=t instanceof Date?t:new Date(t);return Number.isNaN(a.getTime())?"-":[a.getFullYear(),At(a.getMonth()+1),At(a.getDate())].join("-")+" "+[At(a.getHours()),At(a.getMinutes()),At(a.getSeconds())].join(":")},Ne=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Qr=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand 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:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},Wt=({title:t,value:a,icon:l,colorClass:i,trend:m})=>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 ${i} 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 ${i} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(l,{className:`w-6 h-6 ${i.replace("bg-","text-")}`})}),m&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(Qa,{className:"w-3 h-3"})," ",m]})]}),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:a}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),rs=()=>{var V,X;const[t,a]=r.useState(null),[l,i]=r.useState(null),[m,_]=r.useState(""),[N,I]=r.useState("7days"),[g,C]=r.useState(""),[j,F]=r.useState(""),[G,me]=r.useState(null),[oe,v]=r.useState(""),[q,ce]=r.useState([]),[Q,ee]=r.useState(0),[B,ge]=r.useState(!1),[ue,k]=r.useState(!1),[Z,se]=r.useState([]),[K,ve]=r.useState({}),J=r.useRef(0),A=[Ne("brand"),Ne("brand-highlight"),Ne("success-500"),Ne("warning-500"),Ne("accent-500")],E=c=>`¥${Number(c||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`,P=async c=>{let d;try{d=Js(c,new Date,g,j)}catch(Se){_(Se instanceof Error?Se.message:"日期范围无效");return}const{startDate:D,endDate:S}=d,Y={start_date:D,end_date:S},O=Sl(d),de=++J.current;k(!0),_("");try{const[Se,fe,Oe]=await Promise.all([Gs(Y),Gs({start_date:O.startDate,end_date:O.endDate}),ir(Y)]);if(de!==J.current)return;i(Se),me(fe),ce(Oe.orders),ee(Oe.total),ge(Oe.truncated)}catch(Se){de===J.current&&_(Se instanceof Error?Se.message:"经营数据加载失败")}finally{de===J.current&&k(!1)}},be=()=>{if(!l||!G)return null;const c=l.revenue_stats.total_amount,d=G.revenue_stats.total_amount;if(d===0)return c>0?"+100%":"0%";const D=(c-d)/d*100;return`${D>=0?"+":""}${D.toFixed(1)}%`};if(r.useEffect(()=>{let c=!1;return Promise.all([nr(),vt()]).then(([d,D])=>{if(c)return;a(d),se(D);const S={};D.forEach(Y=>{S[Y.item_id]=Y.item_title||Y.item_id}),ve(S)}).catch(d=>{c||_(d instanceof Error?d.message:"概览加载失败")}),()=>{c=!0}},[]),r.useEffect(()=>{N!=="custom"&&P(N)},[N]),m&&(!t||!l))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(rt,{className:"w-8 h-8"}),e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:()=>window.location.reload(),children:"重新加载"})]});if(!t||!l)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx($s,{className:"w-8 h-8 animate-spin text-brand"})});const Re=((V=l.daily_stats)==null?void 0:V.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})))||[],ae=l.item_stats||[],T=l.revenue_stats.total_orders||0,p=l.revenue_stats.total_amount||0,b=ae.length>0?ae.map(c=>({name:(K[c.item_id]||c.item_id).length>12?(K[c.item_id]||c.item_id).substring(0,12)+"...":K[c.item_id]||c.item_id,sales:c.order_count})).sort((c,d)=>d.sales-c.sales).slice(0,10):[],U=Math.max(...b.map(c=>c.sales),1),M=ae.length>0?ae.map(c=>({name:(K[c.item_id]||c.item_id).length>10?(K[c.item_id]||c.item_id).substring(0,10)+"...":K[c.item_id]||c.item_id,value:c.order_count,percent:T>0?c.order_count/T*100:0})).sort((c,d)=>d.value-c.value).slice(0,6).map((c,d)=>({...c,color:A[d%A.length]})):[],ne=ae.length>0?ae.map(c=>({name:(K[c.item_id]||c.item_id).length>12?(K[c.item_id]||c.item_id).substring(0,12)+"...":K[c.item_id]||c.item_id,value:c.total_amount,orderCount:c.order_count,percentage:p>0?c.total_amount/p*100:0})).sort((c,d)=>d.value-c.value).slice(0,5).map((c,d)=>({...c,color:A[d%A.length],percentage:c.percentage.toFixed(1)})):[],he=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}],ye=((X=he.find(c=>c.key===N))==null?void 0:X.label)||"所选范围";let Ee;try{Ee=Js(N,new Date,g,j)}catch{Ee={startDate:g,endDate:j}}const ke=oe.trim().toLowerCase(),x=q.filter(c=>{var d,D,S,Y;return((d=c.order_id)==null?void 0:d.toLowerCase().includes(ke))||((D=c.item_id)==null?void 0:D.toLowerCase().includes(ke))||((S=c.item_title)==null?void 0:S.toLowerCase().includes(ke))||((Y=c.buyer_id)==null?void 0:Y.toLowerCase().includes(ke))});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:[he.map(c=>e.jsx("button",{onClick:()=>I(c.key),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${N===c.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:c.label},c.key)),N==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:g,onChange:c=>C(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:j,onChange:c=>F(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:()=>{try{_(""),P("custom")}catch(c){_(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(Wt,{title:"累计营收 (CNY)",value:`¥${l.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:Va,colorClass:"bg-blue-400",trend:be()||void 0}),e.jsx(Wt,{title:"活跃账号 / 总数",value:`${t.active_cookies} / ${t.total_cookies}`,icon:ha,colorClass:"bg-blue-500"}),e.jsx(Wt,{title:"订单数",value:l.revenue_stats.total_orders.toLocaleString(),icon:Ps,colorClass:"bg-blue-500"}),e.jsx(Wt,{title:"库存卡密余量",value:t.available_card_stock,icon:fa,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:[ye,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:Re.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(Ps,{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:"所选时间范围内暂无订单记录"})]}):Re.length<=2?e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(gl,{data:Re,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Bs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:Ne("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(zs,{axisLine:!1,tickLine:!1,tick:{fill:Ne("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:c=>`¥${c}`}),e.jsx(Ut,{contentStyle:{backgroundColor:Ne("white"),borderRadius:"8px",border:`1px solid ${Ne("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:Ne("neutral-500"),fontWeight:500},itemStyle:{color:Ne("brand"),fontWeight:600},cursor:{fill:Ne("brand",.08)},formatter:c=>[`¥${Number(c).toFixed(2)}`,"营收"]}),e.jsx(bl,{dataKey:"amount",fill:Ne("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:Re.map((c,d)=>e.jsx(ts,{fill:Ne("brand"),stroke:"none",strokeWidth:0},`cell-${d}`))})]})}):e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(fl,{data:Re,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:Ne("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:Ne("brand"),stopOpacity:0})]})}),e.jsx(Bs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:Ne("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(zs,{axisLine:!1,tickLine:!1,tick:{fill:Ne("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(yl,{vertical:!1,stroke:Ne("neutral-100"),strokeDasharray:"3 3"}),e.jsx(Ut,{contentStyle:{backgroundColor:Ne("white"),borderRadius:"8px",border:`1px solid ${Ne("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:Ne("neutral-500"),fontWeight:500},itemStyle:{color:Ne("brand"),fontWeight:600},cursor:{stroke:Ne("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(jl,{type:"monotone",dataKey:"amount",stroke:Ne("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:Ne("white"),stroke:Ne("brand"),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:b.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:b.map((c,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 ${d<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:d+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-brand",style:{width:`${Math.max(8,c.sales/U*100)}%`}})})]},`${c.name}-${d}`))})})]}),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:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${T} 单`,children:M.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(Us,{accessibilityLayer:!1,children:[e.jsx(Ws,{data:M,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:M.map((c,d)=>e.jsx(ts,{fill:c.color},`cell-${d}`))}),e.jsx(Ut,{formatter:c=>`${Number(c||0)} 单`,wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:Ne("white"),border:`1px solid ${Ne("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(_l,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:c=>e.jsx("span",{style:{color:Ne("neutral-500"),fontWeight:500},children:c})})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:T}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),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-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),B&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",q.length," / ",Q," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:oe,onChange:c=>v(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:ue?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx($s,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):x.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(qt,{className:"w-7 h-7 text-gray-300"})}),ke?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:["当前共有 ",q.length," 单参与统计,但没有订单号、商品、买家匹配“",oe,"”。"]})]}):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:["日期范围:",Ee.startDate," 至 ",Ee.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",l.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] 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 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:x.map(c=>e.jsxs("tr",{className:"hover:bg-warning-50/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(qt,{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:bs(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 whitespace-nowrap",children:e.jsx(Qr,{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(ya,{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)"}),ne.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${E(p)}`,children:[e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(Us,{accessibilityLayer:!1,children:[e.jsx(Ws,{data:ne,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:ne.map((c,d)=>e.jsx(ts,{fill:c.color||A[d%A.length]},`cell-${d}`))}),e.jsx(Ut,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:Ne("white"),border:`1px solid ${Ne("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:c=>`¥${Number(c||0).toLocaleString()}`})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:E(p)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:ne.map(c=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:c.color||A[ne.indexOf(c)%A.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:c.name,children:c.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",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))})]})]})]})]})},Gr=(t,a)=>{const l=a.pause_duration||0;return t!==l},Kr=(t,a)=>{const l=a.username!==(t.username||""),i=a.show_browser!==(t.show_browser||!1),m=a.login_password!=="",_=a.clear_password===!0;if(!l&&!i&&!m&&!_)return null;const N={username:a.username,show_browser:a.show_browser};return _?N.clear_password=!0:m&&(N.login_password=a.login_password),N},Hr=(t,a)=>t&&a,Zr=(t,a)=>{if(!t||!a)return!1;const l=Date.parse(t),i=Date.parse(a);return Number.isFinite(l)&&Number.isFinite(i)&&it.map(l=>{const i=a[l.id];return!i||Zr(l.runtime_updated_at,i.updated_at)?l:{...l,runtime_state:i.state,runtime_message:i.message||"",runtime_connected:i.connected,runtime_updated_at:i.updated_at}}),Xr=new Set(["expired","cancelled","error","not_found"]),Jt=()=>{let t=0;return{next:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:a=>a===t}},en=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let a=null,l=null,i=-1,m=0;const _=()=>{m+=1,l==null||l.abort(),l=null,a!==null&&(t.clearInterval(a),a=null)};return{start:(I,g,C,j=2e3)=>{_();const F=m;l=new AbortController;const G=l.signal;a=t.setInterval(()=>{i===F||F!==m||(i=F,(async()=>{var me,oe;try{const v=await g(I,G);if(v.status==="success"){_(),await C.onSuccess(v);return}if(v.status==="scanned"){(me=C.onScanned)==null||me.call(C,v);return}if(v.status==="verification_required"){(oe=C.onVerificationRequired)==null||oe.call(C,v);return}v.status&&Xr.has(v.status)&&(_(),C.onTerminalError(v))}catch(v){if(G.aborted||F!==m)return;_(),C.onPollError(v)}finally{i===F&&(i=-1)}})())},j)},stop:_,isActive:()=>a!==null}},tn=({faceQrUrl:t,verificationScreenshot:a})=>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(Ga,{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:t?e.jsx("img",{src:t,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):a?e.jsx("img",{src:a,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(Pe,{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:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),ea=({src:t,alt:a,className:l=""})=>e.jsx("img",{src:t,alt:a,className:`block aspect-square h-auto w-full object-contain ${l}`.trim()}),ta=({checked:t,onChange:a,label:l})=>e.jsx("button",{type:"button","aria-label":l,"aria-pressed":t,onClick:a,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-6":""}`})}),sn=({account:t,onClose:a,onSaved:l})=>{const[i,m]=r.useState({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),[_,N]=r.useState(!1),[I,g]=r.useState(""),[C,j]=r.useState(""),[F,G]=r.useState(null),me=async()=>{N(!0),j("");try{const v=await Vs(t.id,i);m(v),l(v)}catch(v){j(v instanceof Error?v.message:"保存失败")}finally{N(!1)}},oe=async v=>{g(v),j(""),G(null);try{await Vs(t.id,i);const q=await El(t.id,v),ce=await Rl(t.id);G(q.summary),m(ce),l(ce)}catch(q){j(q instanceof Error?q.message:"任务执行失败")}finally{g("")}};return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:a,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(Me,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(Ka,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(ta,{checked:i.auto_rate_enabled,onChange:()=>m(v=>({...v,auto_rate_enabled:!v.auto_rate_enabled})),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:i.rate_content,maxLength:500,onChange:v=>m(q=>({...q,rate_content:v.target.value})),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",i.last_rate_scan_at?new Date(i.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:I!==""||!t.enabled,onClick:()=>void oe("auto_rate"),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[I==="auto_rate"?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(Ha,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(vs,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(ta,{checked:i.auto_polish_enabled,onChange:()=>m(v=>({...v,auto_polish_enabled:!v.auto_polish_enabled})),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:i.polish_time,onChange:v=>m(q=>({...q,polish_time:v.target.value})),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:I!==""||!t.enabled,onClick:()=>void oe("auto_polish"),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[I==="auto_polish"?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(ja,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",i.last_polish_at?new Date(i.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),F&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",F.found," 项,成功 ",F.success,",失败 ",F.failed,",跳过 ",F.skipped,"。",F.message||""]}),C&&e.jsx("div",{className:"rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:C})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:a,disabled:_||I!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:()=>void me(),disabled:_||I!==""||i.auto_rate_enabled&&!i.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[_?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(He,{className:"h-4 w-4"}),"保存"]})]})})]})})},an=()=>{const[t,a]=r.useState([]),[l,i]=r.useState(!0),[m,_]=r.useState(""),[N,I]=r.useState(""),[g,C]=r.useState(""),[j,F]=r.useState(null),[G,me]=r.useState(""),[oe,v]=r.useState(!1),[q,ce]=r.useState(""),[Q,ee]=r.useState("pending"),[B,ge]=r.useState(""),[ue,k]=r.useState(""),[Z,se]=r.useState(""),[K,ve]=r.useState(null),[J,A]=r.useState(null),[E,P]=r.useState(null),[be,Re]=r.useState(null),[ae,T]=r.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[p,b]=r.useState([]),[U,M]=r.useState([]),[ne,he]=r.useState(!1),[ye,Ee]=r.useState(!1),[ke,x]=r.useState(!1),[V,X]=r.useState(""),[c,d]=r.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),[D,S]=r.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[Y,O]=r.useState(!1),[de,Se]=r.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),fe=r.useRef(null),Oe=r.useRef(null),re=r.useRef(null),h=r.useRef(null),f=r.useRef(null),R=r.useRef(null),z=r.useRef(null),Ie=r.useRef(null),Ae=r.useRef(null),we=r.useRef(null),De=r.useRef(null),te=r.useRef(null),je=r.useRef(0);fe.current===null&&(fe.current=en()),Oe.current===null&&(Oe.current=Jt()),re.current===null&&(re.current=Jt()),h.current===null&&(h.current=Jt()),f.current===null&&(f.current=Jt());const u=()=>{De.current!==null&&(window.clearTimeout(De.current),De.current=null)},L=()=>{te.current!==null&&(window.clearTimeout(te.current),te.current=null)},le=()=>{var s;(s=fe.current)==null||s.stop()},_e=()=>{var s,o;(s=Ae.current)==null||s.abort(),(o=Oe.current)==null||o.cancel(),le(),u(),v(!1)},Ue=()=>{u(),De.current=window.setTimeout(()=>{De.current=null,v(!1),Fe()},1e3)},Fe=async()=>{var y,$,W,pe,xe;const s=re.current.next();(y=R.current)==null||y.abort();const o=new AbortController;R.current=o,i(!0);try{const $e={signal:o.signal},[ie,Ye]=await Promise.allSettled([Ft($e),Yl($e)]);if(!(($=re.current)!=null&&$.isCurrent(s)))return;if(ie.status==="rejected")throw ie.reason;const Ve=ie.value,It=Ye.status==="fulfilled"?Ye.value:{};Ye.status==="rejected"&&console.error("Failed to load AI settings:",Ye.reason);const za=Ve.map(gt=>{var Cs,Ss,Ls,Os,Is;return{...gt,ai_enabled:((Cs=It[gt.id])==null?void 0:Cs.ai_enabled)??!1,max_discount_percent:((Ss=It[gt.id])==null?void 0:Ss.max_discount_percent)??10,max_discount_amount:((Ls=It[gt.id])==null?void 0:Ls.max_discount_amount)??100,max_bargain_rounds:((Os=It[gt.id])==null?void 0:Os.max_bargain_rounds)??3,custom_prompts:((Is=It[gt.id])==null?void 0:Is.custom_prompts)??""}});(W=re.current)!=null&&W.isCurrent(s)&&a(za)}catch($e){(pe=re.current)!=null&&pe.isCurrent(s)&&!o.signal.aborted&&console.error("Failed to load accounts:",$e)}finally{(xe=re.current)!=null&&xe.isCurrent(s)&&i(!1)}};r.useEffect(()=>{let s=!1,o=null;const y=new AbortController,$=async()=>{try{const W=await hs({signal:y.signal,timeoutMs:1e4});s||a(pe=>Yr(pe,W))}catch(W){s||console.error("Failed to load account runtime statuses:",W)}finally{s||(o=window.setTimeout(()=>void $(),2e3))}};return Fe().finally(()=>{s||$()}),()=>{s=!0,y.abort(),o!==null&&window.clearTimeout(o)}},[]),r.useEffect(()=>()=>{var s,o,y,$,W,pe,xe,$e,ie;le(),(s=Oe.current)==null||s.cancel(),(o=re.current)==null||o.cancel(),(y=h.current)==null||y.cancel(),($=f.current)==null||$.cancel(),(W=R.current)==null||W.abort(),(pe=z.current)==null||pe.abort(),(xe=Ie.current)==null||xe.abort(),($e=Ae.current)==null||$e.abort(),(ie=we.current)==null||ie.abort(),u(),je.current+=1,L()},[]);const tt=s=>{if(!s.enabled||s.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(s.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"}}},kt=async(s,o)=>{await zl(s,!o),Fe()},Je=s=>{g||(me(""),F(s))},We=()=>{g||(me(""),F(null))},Ct=async()=>{const s=j;if(!(!s||g)){C(s.id),me("");try{await Ul(s.id),a(o=>o.filter(y=>y.id!==s.id)),F(null)}catch(o){console.error("删除账号失败:",o),me((o==null?void 0:o.message)||"删除账号失败,请稍后重试")}finally{C("")}}},St=async s=>{I(s.id);try{const o=await Zl(s.id);o!=null&&o.profile_error&&alert("资料刷新失败:"+o.profile_error),await Fe()}catch(o){console.error("刷新账号资料失败:",o),alert((o==null?void 0:o.message)||"刷新账号资料失败,请先重新授权该账号")}finally{I("")}},mt=async s=>{var pe,xe;const o=h.current.next();(pe=z.current)==null||pe.abort();const y=new AbortController;z.current=y,Ee(!0),he(!1),x(!1),X("");const[$,W]=await Promise.allSettled([Ra({signal:y.signal}),Br(s,{signal:y.signal})]);(xe=h.current)!=null&&xe.isCurrent(o)&&($.status==="fulfilled"?b($.value.data||[]):(b([]),X("通知渠道列表加载失败,请重试")),W.status==="fulfilled"?(M(W.value||[]),he(!0)):(M([]),X("通知绑定加载失败;本次保存不会修改现有绑定")),Ee(!1))},Lt=async s=>{var y;je.current+=1,(y=we.current)==null||y.abort(),L(),Se({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),P(s),d({remark:s.remark||s.note||"",cookie:s.cookie||s.value||"",auto_confirm:s.auto_confirm||!1,pause_duration:s.pause_duration||0,username:s.username||"",login_password:s.login_password||"",show_browser:s.show_browser||!1,showLoginPassword:!1,clear_password:!1}),A("edit"),T({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,o]=await Promise.allSettled([mt(s.id),Vl(s.id)]);o.status==="fulfilled"?T({loading:!1,saving:!1,canOpen:o.value.can_open_long_login,enabled:o.value.enabled,error:""}):T({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"})},nt=async()=>{if(!E||ae.loading||ae.saving||!ae.canOpen)return;const s=!ae.enabled;T(o=>({...o,saving:!0,error:""}));try{const o=await Ql(E.id,s);T({loading:!1,saving:!1,canOpen:o.can_open_long_login,enabled:o.enabled,error:""})}catch(o){T(y=>({...y,saving:!1,error:o instanceof Error?o.message:"保存登录信息设置失败"}))}},it=async s=>{var $,W,pe,xe;const o=f.current.next();($=Ie.current)==null||$.abort();const y=new AbortController;Ie.current=y,P(s),A("ai-settings"),O(!0);try{const $e=await Er(s.id,{signal:y.signal});if(!((W=f.current)!=null&&W.isCurrent(o)))return;S({ai_enabled:$e.ai_enabled??!1,max_discount_percent:$e.max_discount_percent??10,max_discount_amount:$e.max_discount_amount??100,max_bargain_rounds:$e.max_bargain_rounds??3,custom_prompts:$e.custom_prompts??""})}catch($e){(pe=f.current)!=null&&pe.isCurrent(o)&&console.error("Failed to load AI settings:",$e)}finally{(xe=f.current)!=null&&xe.isCurrent(o)&&O(!1)}},Ot=async()=>{if(E){O(!0);try{const s={};c.remark!==(E.remark||E.note||"")&&(s.remark=c.remark),c.cookie&&c.cookie!==(E.cookie||E.value||"")&&(s.cookie=c.cookie),c.auto_confirm!==E.auto_confirm&&(s.auto_confirm=c.auto_confirm),Gr(c.pause_duration,E)&&(s.pause_duration=c.pause_duration);const o=Kr(E,c);o&&Object.assign(s,o),Hr(ne,ke)&&(s.channel_ids=U),Object.keys(s).length>0&&await Jl(E.id,s),A(null),Fe()}catch(s){console.error("更新账号失败:",s),alert("更新失败,请重试")}finally{O(!1)}}},pt=async()=>{if(!(!E||c.pause_duration<=0)){O(!0);try{const s=await Wl(E.id,c.pause_duration);P({...E,pause_duration:c.pause_duration,paused:(s==null?void 0:s.paused)===!0,paused_until:Number((s==null?void 0:s.paused_until)||0)}),await Fe()}catch(s){alert(s instanceof Error?s.message:"重新暂停失败")}finally{O(!1)}}},ut=async()=>{if(E){O(!0);try{await Dr(E.id,D),A(null),Fe()}catch(s){console.error("更新AI设置失败:",s),alert("更新失败,请重试")}finally{O(!1)}}},st=async(s,o)=>{var $;($=we.current)==null||$.abort();const y=new AbortController;we.current=y;try{const W=await Kl(s,y.signal);if(o!==je.current)return;if(W.status==="success"){L(),Se({sessionId:s,status:"success",message:W.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}),d(pe=>({...pe,login_password:"",showLoginPassword:!1})),await Fe();return}if(W.status==="processing"||W.status==="verification_required"){Se({sessionId:s,status:W.status,message:W.message||(W.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:W.qr_code_url||""}),L(),te.current=window.setTimeout(()=>void st(s,o),1500);return}L(),Se({sessionId:s,status:"failed",message:W.error||W.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""})}catch(W){if(o!==je.current)return;L(),Se({sessionId:s,status:"failed",message:W instanceof Error?W.message:"查询密码登录状态失败",qrCodeUrl:""})}},ht=async()=>{var y;if(!E)return;const s=c.username.trim();if(!s||!c.login_password){alert("请先填写登录账号和本次登录密码");return}L(),(y=we.current)==null||y.abort();const o=++je.current;Se({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const $=await Gl({account_id:E.id,account:s,password:c.login_password,show_browser:c.show_browser});if(o!==je.current)return;if(!$.success||!$.session_id)throw new Error($.message||"无法启动密码登录");Se({sessionId:$.session_id,status:"processing",message:$.message||"登录处理中",qrCodeUrl:""}),await st($.session_id,o)}catch($){if(o!==je.current)return;Se({sessionId:"",status:"failed",message:$ instanceof Error?$.message:"启动密码登录失败",qrCodeUrl:""})}},Ge=async()=>{var o;const s=de.sessionId;if(je.current+=1,(o=we.current)==null||o.abort(),L(),s)try{await Hl(s)}catch(y){console.error("取消密码登录失败",y)}Se({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},ot=async()=>{var s,o;(s=h.current)==null||s.cancel(),(o=z.current)==null||o.abort(),(de.status==="processing"||de.status==="verification_required")&&await Ge(),A(null)},n=()=>{var s,o;(s=f.current)==null||s.cancel(),(o=Ie.current)==null||o.abort(),A(null)},w=async(s,o)=>{const y=await Bl(s,o==null?void 0:o.id);if(!y.success||!y.account_id)throw new Error(y.message||"保存扫码授权失败");return y.account_id},H=async s=>{var W,pe,xe,$e;le(),(W=Ae.current)==null||W.abort();const o=new AbortController;Ae.current=o;const y=Oe.current.next();u();const $=s||null;ve($),v(!0),ee("loading"),ge(""),ce(""),k(""),se("");try{const ie=await ql({signal:o.signal});if(!((pe=Oe.current)!=null&&pe.isCurrent(y)))return;if(!ie.success||!ie.qr_code_url||!ie.session_id)throw new Error(ie.message||"闲鱼未返回可用的登录二维码");if(ie.success&&ie.qr_code_url&&ie.session_id){const Ye=ie.session_id;ce(ie.qr_code_url),ee("waiting"),(xe=fe.current)==null||xe.start(Ye,Fl,{onSuccess:async()=>{try{if(!await w(Ye,$)){ee("error");return}}catch(Ve){console.error("保存扫码授权失败",Ve),ee("error");return}ee("success"),Ue()},onScanned:()=>{ee("waiting")},onTerminalError:()=>{ee("error")},onPollError:Ve=>{console.error("轮询扫码状态失败",Ve),ee("error")},onVerificationRequired:Ve=>{ee("verification"),Ve.face_qr_url&&se(Ve.face_qr_url),Ve.verification_screenshot&&k(Ve.verification_screenshot)}})}}catch(ie){if(!(($e=Oe.current)!=null&&$e.isCurrent(y)))return;ge(ie instanceof Error?ie.message:"二维码获取失败,请稍后重试"),ee("error")}finally{Ae.current===o&&(Ae.current=null)}};if(l)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(Pe,{className:"w-8 h-8 text-brand animate-spin"})});const Te=t.filter(s=>{const o=m.trim().toLowerCase();return o?[s.id,s.nickname,s.remark,s.note,s.username,s.runtime_message].some(y=>(y||"").toLowerCase().includes(o)):!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:m,onChange:s=>_(s.target.value),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:()=>H(),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(Xt,{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:["当前显示 ",Te.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[Te.map(s=>{const o=tt(s),y=s.runtime_state==="auth_expired"||s.runtime_state==="verification_required";return e.jsx("div",{className:"ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-5 sm:gap-8",children:[e.jsxs("div",{className:"relative",children:[s.avatar_url?e.jsx("img",{src:s.avatar_url,alt:s.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(xt,{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 ${o.dot}`,children:s.runtime_state==="online"&&e.jsx(Ke,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:s.nickname||s.remark||`账号 ${s.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${o.badge}`,children:o.label}),s.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(yt,{className:"w-3 h-3"})," AI"]}),s.auto_rate_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700",children:[e.jsx(Tt,{className:"h-3 w-3"})," 自动评价"]}),s.auto_polish_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700",children:[e.jsx(vs,{className:"h-3 w-3"})," 每日擦亮"]}),s.auto_confirm&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700",children:[e.jsx(Ke,{className:"h-3 w-3"})," 自动确认发货"]}),s.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:s.profile_error,children:[e.jsx(rt,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"text-sm font-medium text-gray-500",children:[e.jsx("p",{children:s.remark||s.note||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",s.id]})]}),s.runtime_message&&s.runtime_state!=="online"&&s.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${y?"text-red-700":"text-amber-700"}`,children:[e.jsx(rt,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:s.runtime_message}),y&&e.jsxs("button",{type:"button",onClick:()=>H(s),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(Xt,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),s.paused&&e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700",children:[e.jsx(Rs,{className:"h-3 w-3"})," 暂停处理中"]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>St(s),disabled:N===s.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(ze,{className:`w-5 h-5 ${N===s.id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>H(s),className:`p-3 rounded-xl transition-colors ${y?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(Xt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Lt(s),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(_a,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>it(s),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(yt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Re(s),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(ja,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>kt(s.id,s.enabled),className:`p-3 rounded-xl transition-colors ${s.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:s.enabled?"停用账号":"启用账号",children:e.jsx(Za,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Je(s),disabled:g!=="",className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:g===s.id?"删除中…":`删除账号 ${s.nickname||s.remark||s.id}`,children:g===s.id?e.jsx(Pe,{className:"w-5 h-5 animate-spin"}):e.jsx(Qe,{className:"w-5 h-5"})})]})]})]})]})},s.id)}),t.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(xt,{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:"请点击右上角扫码添加您的闲鱼账号"})]}),t.length>0&&Te.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。"})]})]}),be&&qe.createPortal(e.jsx(sn,{account:be,onClose:()=>Re(null),onSaved:s=>{a(o=>o.map(y=>y.id===be.id?{...y,auto_rate_enabled:s.auto_rate_enabled,rate_content:s.rate_content,auto_polish_enabled:s.auto_polish_enabled,polish_time:s.polish_time,last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}:y))}}),document.body),j&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",role:"presentation",children:e.jsxs("div",{className:"h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal",role:"dialog","aria-modal":"true","aria-labelledby":"delete-account-title","aria-describedby":"delete-account-description",children:[e.jsxs("div",{className:"relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5",children:[e.jsx("div",{className:"absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl"}),e.jsxs("div",{className:"relative flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200",children:e.jsx(Qe,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{id:"delete-account-title",className:"text-lg font-extrabold tracking-tight text-gray-950",children:"删除这个账号?"}),e.jsx("p",{id:"delete-account-description",className:"mt-1 text-xs leading-5 text-gray-600",children:"删除后,该账号的关联配置也会一并清理,此操作无法撤销。"})]}),e.jsx("button",{type:"button",onClick:We,disabled:g!=="",className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"关闭删除确认",children:e.jsx(Me,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:j.nickname||j.remark||"未命名账号"}),j.remark&&j.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",j.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",j.id]})]}),g===j.id&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(Pe,{className:"h-5 w-5 flex-shrink-0 animate-spin text-brand"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-blue-950",children:"正在删除账号"}),e.jsx("div",{className:"mt-0.5 text-xs text-blue-700",children:"正在清理关联数据,请保持页面打开…"})]})]}),G&&e.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3",role:"alert",children:[e.jsx(rt,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-red-800",children:"删除失败"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-red-700",children:G})]})]})]}),e.jsxs("div",{className:"flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4",children:[e.jsx("button",{type:"button",onClick:We,disabled:g!=="",className:"flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50",children:"取消"}),e.jsx("button",{type:"button",onClick:()=>void Ct(),disabled:g!=="",className:"flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400",children:g===j.id?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),oe&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:_e,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(Me,{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:K?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:K?`请用闲鱼APP扫码,为「${K.nickname||K.remark||K.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${Q==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[Q==="loading"&&e.jsx(Pe,{className:"w-10 h-10 text-brand animate-spin"}),Q==="waiting"&&e.jsx(ea,{src:q,alt:"闲鱼登录二维码",className:"p-2"}),Q==="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(Ke,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),Q==="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:B||"请关闭窗口后重新发起扫码登录。"})]}),Q==="verification"&&e.jsx(tn,{faceQrUrl:Z,verificationScreenshot:ue})]}),Q!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),J==="edit"&&E&&qe.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:E.nickname||E.remark||E.id})]}),e.jsx("button",{onClick:()=>void ot(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Me,{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:E.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:c.remark,onChange:s=>d({...c,remark:s.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:c.cookie,onChange:s=>d({...c,cookie:s.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长度: ",c.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(Ke,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:()=>d({...c,auto_confirm:!c.auto_confirm}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${c.auto_confirm?"bg-brand":"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 ${c.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(Rs,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:c.pause_duration,onChange:s=>d({...c,pause_duration:parseInt(s.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:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),c.pause_duration>0&&!E.paused&&c.pause_duration===(E.pause_duration||0)&&e.jsx("button",{type:"button",disabled:Y,onClick:()=>void pt(),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(Ya,{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:"状态直接读取并修改闲鱼官方长登录设置"}),ae.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:ae.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:ae.loading||ae.saving||!ae.canOpen,onClick:()=>void nt(),className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${ae.enabled?"bg-brand":"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 ${ae.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:c.username,onChange:s=>d({...c,username:s.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:c.showLoginPassword?"text":"password",value:c.login_password,onChange:s=>d({...c,login_password:s.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:()=>d({...c,showLoginPassword:!c.showLoginPassword}),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:c.showLoginPassword?e.jsx(dt,{className:"w-5 h-5"}):e.jsx(lt,{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:c.clear_password,onChange:s=>d({...c,clear_password:s.target.checked,login_password:s.target.checked?"":c.login_password}),className:"w-4 h-4 accent-brand"}),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:()=>d({...c,show_browser:!c.show_browser}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${c.show_browser?"bg-brand":"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 ${c.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 和保存的登录信息。"})]}),de.status==="processing"||de.status==="verification_required"?e.jsx("button",{type:"button",onClick:Ge,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:ht,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),de.message&&e.jsx("div",{className:`text-sm font-medium ${de.status==="failed"?"text-red-700":de.status==="success"?"text-green-700":"text-blue-800"}`,children:de.message}),de.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 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),de.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(ea,{src:de.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(p.length>0||ye||V)&&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(jt,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),ye&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Pe,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),V&&!ye&&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:V}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:()=>mt(E.id),children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:p.map(s=>{const o=U.includes(Number(s.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:()=>{ne&&(M(y=>o?y.filter($=>$!==Number(s.id)):[...y,Number(s.id)]),x(!0))},disabled:!ne,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${o?"bg-brand border-brand":"bg-white border-gray-300"}`,children:o&&e.jsx(Ke,{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:s.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[s.type,s.enabled?"":" · 已停用"]})]})]},s.id)})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>void ot(),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Y,children:"取消"}),e.jsxs("button",{onClick:Ot,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Y,children:[Y?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),Y?"保存中...":"保存"]})]})})]})}),document.body),J==="ai-settings"&&E&&qe.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(yt,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:E.nickname||E.remark||E.id})]}),e.jsx("button",{onClick:n,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Me,{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(yt,{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:()=>S({...D,ai_enabled:!D.ai_enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${D.ai_enabled?"bg-brand":"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 ${D.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:D.max_discount_percent,onChange:s=>S({...D,max_discount_percent:parseInt(s.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:D.max_discount_amount,onChange:s=>S({...D,max_discount_amount:parseInt(s.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:D.max_bargain_rounds,onChange:s=>S({...D,max_bargain_rounds:parseInt(s.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:D.custom_prompts,onChange:s=>S({...D,custom_prompts:s.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(js,{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:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Y,children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Y,children:[Y?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),Y?"保存中...":"保存"]})]})})]})}),document.body)]})},ln=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(a=>({order_id:String((a==null?void 0:a.order_id)||"unknown"),success:(a==null?void 0:a.success)===!0,message:String((a==null?void 0:a.message)||"")})):[]}),rn=t=>(t==null?void 0:t.results.filter(a=>!a.success))||[],sa=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand 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 ${a[t]||a.cancelled}`,children:l[t]||t})},nn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState([]),[m,_]=r.useState([]),[N,I]=r.useState({}),[g,C]=r.useState("all"),[j,F]=r.useState(""),[G,me]=r.useState(""),[oe,v]=r.useState(""),q=r.useRef(0),[ce,Q]=r.useState(1),[ee,B]=r.useState(1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState(!1),[ve,J]=r.useState(!1),[A,E]=r.useState(null),[P,be]=r.useState(null),[Re,ae]=r.useState({}),[T,p]=r.useState(!1),[b,U]=r.useState(""),[M,ne]=r.useState(!1),[he,ye]=r.useState(null),[Ee,ke]=r.useState(null),[x,V]=r.useState(null),[X,c]=r.useState(!1),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=async()=>{const u=++q.current;ue(!0);try{const L=await Xl(j||void 0,g,ce,20,oe);if(u!==q.current)return;a(L.data),B(L.total_pages)}catch(L){console.error("加载订单失败:",L)}finally{u===q.current&&ue(!1)}},de=(u,L,le)=>{if(le&&le.trim())return le;if(N[`${u}:${L}`])return N[`${u}:${L}`];const _e=l.find(Ue=>{if(le&&Ue.item_title){const Fe=le.toLowerCase(),tt=Ue.item_title.toLowerCase();return tt.includes(Fe)||Fe.includes(tt)}return!1});return _e!=null&&_e.item_title?_e.item_title:"未知商品"},Se=u=>{const L={};u.forEach(le=>{le.item_id&&(L[`${le.cookie_id}:${le.item_id}`]=le.item_title||le.item_id)}),I(L)};r.useEffect(()=>{const u=window.setTimeout(()=>{Q(1),v(G.trim())},300);return()=>window.clearTimeout(u)},[G]),r.useEffect(()=>{O()},[j,g,ce,oe]),r.useEffect(()=>{Promise.all([Ft(),vt()]).then(([u,L])=>{_(u),i(L),Se(L)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const fe=r.useMemo(()=>new Map(m.map(u=>[u.id,u])),[m]),Oe=u=>{const L=fe.get(u),le=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return le?`${le} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},re=u=>{const L=fe.get(u);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"},h=async()=>{ue(!0);try{const u=await sr(j||void 0,g);await O(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{ue(!1)}},f=u=>{U(u),ye(null),p(!0)},R=async u=>{var L;ne(!0),ye(null);try{const le=await lr([b],u),_e=(L=le==null?void 0:le.results)==null?void 0:L[0];_e!=null&&_e.success?(ye({success:!0,message:_e.message}),O()):ye({success:!1,message:(_e==null?void 0:_e.message)||"发货失败"})}catch(le){ye({success:!1,message:(le==null?void 0:le.message)||"请求失败"})}finally{ne(!1)}},z=u=>{E(u),Z(!0)},Ie=u=>{be({...u}),K(!0)},Ae=async()=>{if(!(!P||!P.order_id))try{const u={};P.status!==void 0&&(u.order_status=P.status),P.buyer_id!==void 0&&(u.buyer_id=P.buyer_id),P.amount!==void 0&&(u.amount=P.amount),P.receiver_name!==void 0&&(u.receiver_name=P.receiver_name),P.receiver_phone!==void 0&&(u.receiver_phone=P.receiver_phone),P.receiver_address!==void 0&&(u.receiver_address=P.receiver_address),P.item_id!==void 0&&(u.item_id=P.item_id),P.quantity!==void 0&&(u.quantity=P.quantity),P.item_title!==void 0&&(u.item_title=P.item_title),await er(P.order_id,u),K(!1),be(null),O()}catch(u){console.error("更新订单失败:",u),alert("更新失败,请重试")}},we=async()=>{if(Ee){c(!0);try{const u=new FormData;u.append("file",Ee);const L=ln(await rr(u));V(L),ke(null),await O(),L.failed_count===0&&(J(!1),V(null),alert(`订单导入成功,共 ${L.success_count} 条`))}catch(u){alert((u==null?void 0:u.message)||"导入失败,请检查文件格式")}finally{c(!1)}}},De=()=>{X||(J(!1),ke(null),V(null))},te=async u=>{D(u);try{const L=await ar(u);L.success?await O():alert(L.message||"同步失败")}catch(L){console.error("同步订单失败:",L),alert((L==null?void 0:L.message)||"同步失败,请重试")}finally{D(null)}},je=async u=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){Y(u);try{await tr(u),t.length===1&&ce>1?Q(L=>L-1):await O()}catch(L){console.error("删除订单失败:",L),alert((L==null?void 0:L.message)||"删除失败,请重试"),await O()}finally{Y(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:O,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(ze,{className:`w-5 h-5 ${ge?"animate-spin":""}`})}),e.jsxs("button",{onClick:()=>{V(null),J(!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(et,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:h,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(Es,{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-surface-muted",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(u=>e.jsx("button",{onClick:()=>{C(u.k),Q(1),me("")},className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${g===u.k?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:u.v},u.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(xt,{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:u=>{F(u.target.value),Q(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:"全部账号"}),m.map(u=>e.jsx("option",{value:u.id,children:Oe(u.id)},u.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(Nt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:G,onChange:u=>{me(u.target.value),Q(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:t.map(u=>e.jsxs("tr",{className:"hover:bg-warning-50/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:u.item_image?e.jsx("img",{src:u.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(qt,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:de(u.cookie_id,u.item_id,u.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:re(u.cookie_id),children:[e.jsx(xt,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:re(u.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",u.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",u.quantity," • ",bs(u.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:u.buyer_id}),u.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:u.receiver_name})]}),u.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:u.receiver_phone})]}),u.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:u.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:u.amount?`¥${u.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(sa,{status:u.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[u.status==="pending_ship"&&e.jsx("button",{onClick:()=>f(u.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=${u.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(ya,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>z(u),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(lt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Ie(u),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(_t,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>te(u.order_id),disabled:d===u.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(ze,{className:`w-4 h-4 ${d===u.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>je(u.order_id),disabled:S===u.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(Qe,{className:"w-4 h-4"})})]})]},u.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:["第 ",ce," 页 / 共 ",ee," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:ce<=1,onClick:()=>Q(u=>u-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(Ns,{className:"w-5 h-5"})}),e.jsx("button",{disabled:ce>=ee,onClick:()=>Q(u=>u+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(_s,{className:"w-5 h-5"})})]})]})]}),k&&A&&qe.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:()=>Z(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:re(A.cookie_id),children:re(A.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(sa,{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:bs(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:de(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:()=>Z(!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:()=>{Z(!1),f(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),ve&&qe.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:De,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:u=>{var L;return ke(((L=u.target.files)==null?void 0:L[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 格式"})]}),Ee&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:Ee.name})]})}),x&&x.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:["导入完成:成功 ",x.success_count," 条,失败 ",x.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:rn(x).map((u,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:u.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:u.message||"导入失败"})]},`${u.order_id}-${L}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:De,disabled:X,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:we,disabled:!Ee||X,className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:X?"正在导入…":"导入订单"})]})})]})}),document.body),T&&qe.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:()=>{p(!1),ye(null)},className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:()=>R("status_only"),disabled:M,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(Es,{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:()=>R("full_delivery"),disabled:M,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand 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(qt,{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:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),M&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(ze,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),he&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${he.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[he.success?"✓ ":"✗ ",he.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:()=>{p(!1),ye(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:he!=null&&he.success?"完成":"取消"})})]})}),document.body),se&&P&&qe.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:()=>K(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:P.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:P.status,onChange:u=>be({...P,status:u.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:P.buyer_id,onChange:u=>be({...P,buyer_id:u.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:P.amount,onChange:u=>be({...P,amount:u.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:P.receiver_name||"",onChange:u=>be({...P,receiver_name:u.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:P.receiver_phone||"",onChange:u=>be({...P,receiver_phone:u.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:P.receiver_address||"",onChange:u=>be({...P,receiver_address:u.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:P.item_title||"",onChange:u=>be({...P,item_title:u.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:()=>K(!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(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},on=(t,a,l)=>{const i=l.trim().toLocaleLowerCase();return t.filter(m=>(!a||m.type===a)&&(!i||m.name.toLocaleLowerCase().includes(i)))},aa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),cn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState(!1),[m,_]=r.useState(!1),[N,I]=r.useState(null),[g,C]=r.useState({}),[j,F]=r.useState(aa),[G,me]=r.useState(!1),[oe,v]=r.useState("create"),[q,ce]=r.useState(null),[Q,ee]=r.useState(null),[B,ge]=r.useState(!1),[ue,k]=r.useState(""),[Z,se]=r.useState(""),[K,ve]=r.useState(null),[J,A]=r.useState(""),[E,P]=r.useState("");r.useEffect(()=>{Xe().then(a)},[]);const be=({type:x})=>{switch(x){case"text":return e.jsx(Ds,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Ts,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(sl,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(os,{className:"w-5 h-5 text-gray-500"})}},Re=x=>{var V,X,c,d,D;I(x),C({id:x.id,name:x.name||"",type:x.type||"text",api_url:((V=x.api_config)==null?void 0:V.url)||"",api_method:((X=x.api_config)==null?void 0:X.method)||"GET",api_timeout:((c=x.api_config)==null?void 0:c.timeout)||10,api_headers:((d=x.api_config)==null?void 0:d.headers)||"",api_params:((D=x.api_config)==null?void 0:D.params)||"",text_content:x.text_content||"",data_content:x.data_content||"",image_url:x.image_url||"",delay_seconds:x.delay_seconds||0,description:x.description||"",enabled:x.enabled}),i(!0)},ae=async()=>{var x,V,X,c,d,D,S,Y;if(N){if(!((x=g.name)!=null&&x.trim())){alert("请输入卡密名称");return}if(!g.type){alert("请选择卡密类型");return}try{const O={name:g.name.trim(),type:g.type,description:(V=g.description)==null?void 0:V.trim(),delay_seconds:g.delay_seconds||0,enabled:g.enabled??!0};g.type==="api"?O.api_config={url:((X=g.api_url)==null?void 0:X.trim())||"",method:g.api_method,timeout:g.api_timeout||10,headers:((c=g.api_headers)==null?void 0:c.trim())||void 0,params:((d=g.api_params)==null?void 0:d.trim())||void 0}:g.type==="text"?O.text_content=((D=g.text_content)==null?void 0:D.trim())||"":g.type==="data"?O.data_content=((S=g.data_content)==null?void 0:S.trim())||"":g.type==="image"&&(O.image_url=((Y=g.image_url)==null?void 0:Y.trim())||""),await Ks(N.id,O),i(!1),Xe().then(a)}catch(O){console.error("更新卡密失败:",O),alert("更新失败,请重试")}}},T=async x=>{if(confirm("确认删除该卡密吗?"))try{await dr(x),Xe().then(a)}catch(V){console.error("删除卡密失败:",V),alert("删除失败,请重试")}},p=async()=>{if(!j.name.trim()){alert("请输入卡密名称");return}if(!j.content.trim()){alert(j.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const x={name:j.name.trim(),type:j.type,description:j.description.trim(),enabled:j.enabled,delay_seconds:j.delay_seconds};j.type==="text"&&(x.text_content=j.content.trim()),j.type==="data"&&(x.data_content=j.content.trim()),j.type==="image"&&(x.image_url=j.content.trim()),j.type==="api"&&(x.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 cr(x),_(!1),F(aa()),Xe().then(a)}catch(x){console.error("添加卡密失败:",x),alert("添加失败,请重试")}},b=async x=>{try{await Ks(x.id,{...x,enabled:!x.enabled}),Xe().then(a)}catch(V){console.error("切换状态失败:",V)}},U=async x=>{try{await navigator.clipboard.writeText(String(x)),alert(`已复制卡密组ID:${x}`)}catch{prompt("复制卡密组ID",String(x))}},M=t.filter(x=>x.type==="data"),ne=r.useMemo(()=>on(t,J,E),[t,E,J]),he=()=>{const X=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 -VIP-MONTH-002 -VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(S=>S.map(Y=>`"${String(Y).replace(/"/g,'""')}"`).join(",")).join(` -`),c=new Blob(["\uFEFF"+X],{type:"text/csv;charset=utf-8"}),d=URL.createObjectURL(c),D=document.createElement("a");D.href=d,D.download="卡密组批量导入模板.csv",document.body.appendChild(D),D.click(),D.remove(),URL.revokeObjectURL(d)},ye=async()=>{if(q){ge(!0),ee(null);try{const x=await xr(q);if(ee(x),x.created>0){const V=await Xe();a(V)}}catch(x){ee({error:(x==null?void 0:x.message)||"上传失败"})}finally{ge(!1)}}},Ee=async()=>{if(!(!ue||!Z.trim())){ge(!0),ve(null);try{const x=await mr(ue,Z);ve({added:x.added}),se("");const V=await Xe();a(V)}catch(x){alert("追加失败:"+((x==null?void 0:x.message)||"未知错误"))}finally{ge(!1)}}},ke=()=>{var x;v("create"),ce(null),ee(null),k((x=M[0])!=null&&x.id?String(M[0].id):""),se(""),ve(null),me(!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:ke,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(Dt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>_(!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(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:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted 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(Na,{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:J,onChange:x=>A(x.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(Nt,{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:E,onChange:x=>P(x.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:["显示 ",ne.length," / ",t.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:ne.map(x=>{let V="";return x.type==="data"&&x.data_content?V=`库存: ${x.data_content.split(` -`).filter(c=>c.trim()).length} 条`:x.type==="text"&&x.text_content?V=x.text_content:x.type==="api"&&x.api_config?V=x.api_config.url:x.type==="image"&&x.image_url&&(V="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/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(be,{type:x.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:x.name,children:x.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>U(x.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:x.id}),e.jsx(Xa,{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 ${x.type==="text"?"bg-blue-50 text-blue-600":x.type==="data"?"bg-purple-50 text-purple-600":x.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:x.type==="text"?"文本":x.type==="data"?"批量":x.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:V,children:V})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:x.description||"-",children:x.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>b(x),className:`w-12 h-8 rounded-full relative transition-colors ${x.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 ${x.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:()=>Re(x),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(_t,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>T(x.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Qe,{className:"h-4 w-4"})})]})})]},x.id)})})]})}),ne.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(fa,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&N&&qe.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:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Me,{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:x=>C({...g,name:x.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:x=>C({...g,type:x.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:"批量数据"}),(N==null?void 0:N.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:x=>C({...g,api_url:x.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:x=>C({...g,api_method:x.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:x=>C({...g,api_timeout:parseInt(x.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:x=>C({...g,api_headers:x.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:x=>C({...g,api_params:x.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:x=>C({...g,text_content:x.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:x=>C({...g,data_content:x.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(x=>x.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:x=>C({...g,image_url:x.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:x=>{x.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:x=>C({...g,delay_seconds:parseInt(x.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:x=>C({...g,description:x.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:()=>C({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-brand":"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:()=>i(!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(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),m&&qe.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:()=>_(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Me,{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:x=>F({...j,name:x.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:()=>F({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ds,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ts,{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:x=>F({...j,content:x.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:x=>F({...j,content:x.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:x=>F({...j,content:x.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-brand",children:j.content.split(` -`).filter(x=>x.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:x=>F({...j,api_method:x.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:x=>F({...j,api_timeout:parseInt(x.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:x=>F({...j,api_headers:x.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:x=>F({...j,api_params:x.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:x=>F({...j,description:x.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:x=>F({...j,delay_seconds:parseInt(x.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:()=>_(!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:p,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),G&&qe.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:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Me,{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:()=>v("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 ${oe==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(el,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>v("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 ${oe==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Dt,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),oe==="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:he,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(tl,{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(Dt,{className:"w-4 h-4"}),q?q.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:x=>{var V;return ce(((V=x.target.files)==null?void 0:V[0])||null)}})]})]}),Q&&!Q.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:["共 ",Q.total," 行 · 成功 ",Q.created," · 失败 ",Q.failed]}),Q.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:Q.rows.filter(x=>!x.success).map(x=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",x.row_no," 行「",x.name,"」:",x.error]},x.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:M.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:ue,onChange:x=>k(x.target.value),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:M.map(x=>e.jsxs("option",{value:String(x.id),children:[x.name,"(ID: ",x.id,")"]},x.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:Z,onChange:x=>se(x.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:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),K&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",K.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:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),oe==="create"?e.jsxs("button",{onClick:ye,disabled:!q||B,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(Dt,{className:"w-4 h-4"}),B?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ee,disabled:!ue||!Z.trim()||B||M.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),B?"处理中...":"追加卡密"]})]})]})}),document.body)]})},dn=t=>t.find(a=>a.status==="running"||a.status==="canceling"),la="ydisks-amap-js-api",xn="c9b68d4ce9a2a97f22a4a439404488ca";let $t=null;const mn=()=>xn,pn=()=>window.AMap?Promise.resolve(window.AMap):$t||($t=new Promise((t,a)=>{const l=document.getElementById(la),i=l||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(N)},_=()=>{window.AMap?(m(),t(window.AMap)):(m(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},N=window.setTimeout(()=>{m(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=_,i.id=la,i.async=!0,i.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(mn())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,i.onerror=()=>{m(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},l||document.head.appendChild(i)}).catch(t=>{throw $t=null,t}),$t),Ht=t=>Number.isFinite(t)&&t!==0,un=t=>{var m,_;const a=Number((m=t.location)==null?void 0:m.lng),l=Number((_=t.location)==null?void 0:_.lat),i={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:a,latitude:l,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!i.division_id||!i.province||!i.city||!i.poi_id||!i.poi_name||!Ht(a)||!Ht(l)||a<-180||a>180||l<-90||l>90?null:i},hn=async(t,a)=>{if(!Ht(t)||!Ht(a)||t<-180||t>180||a<-90||a>90)throw new Error("经纬度无效");const l=await pn();return new Promise((i,m)=>{new l.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,a],1e3,(N,I)=>{var C;if(N!=="complete"){if(N==="no_data"){i([]);return}m(new Error("高德地图附近地址查询失败,请稍后重试"));return}const g=(((C=I==null?void 0:I.poiList)==null?void 0:C.pois)||[]).map(un).filter(j=>j!==null);i(g)})})},gn=t=>{const a=String(t||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},bn=({onConfigureDelivery:t})=>{const[a,l]=r.useState([]),[i,m]=r.useState([]),[_,N]=r.useState([]),[I,g]=r.useState(""),[C,j]=r.useState(""),[F,G]=r.useState(!1),[me,oe]=r.useState(!1),[v,q]=r.useState(!1),[ce,Q]=r.useState(!1),[ee,B]=r.useState(!1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState("upload"),[ve,J]=r.useState(null),[A,E]=r.useState(null),[P,be]=r.useState(""),[Re,ae]=r.useState(!1),[T,p]=r.useState(!1),[b,U]=r.useState([]),[M,ne]=r.useState(null),[he,ye]=r.useState([]),[Ee,ke]=r.useState(null),[x,V]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[X,c]=r.useState(null),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=r.useRef(!1),[de,Se]=r.useState(null),[fe,Oe]=r.useState({}),[re,h]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[f,R]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[z,Ie]=r.useState([]);r.useEffect(()=>{if(!ge||f.images.length===0){Ie([]);return}const n=f.images.map((w,H)=>({key:w.name+H,url:URL.createObjectURL(w)}));return Ie(n),()=>{n.forEach(w=>URL.revokeObjectURL(w.url))}},[ge,f.images]);const Ae=async()=>{const n=await vt();l(n)},we=async()=>{m(await gs())};r.useEffect(()=>{Promise.all([Ft(),vt(),gs(),Hs(20)]).then(([n,w,H,Te])=>{N(n),l(w),m(H);const s=Te.find(o=>["running","canceling"].includes(o.status))||Te.find(o=>o.status!=="preview");Y(s||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!k||!(d!=null&&d.id)||!["running","canceling"].includes(d.status))return;const n=window.setInterval(async()=>{if(!O.current){O.current=!0;try{const w=await bt(d.id);D(w),Y(w),["running","canceling"].includes(w.status)||(K("done"),await Ae(),await we())}catch(w){console.error("刷新批量铺货进度失败:",w)}finally{O.current=!1}}},3e3);return()=>{window.clearInterval(n)}},[k,d==null?void 0:d.id,d==null?void 0:d.status]);const De=async()=>{if(!I)return alert("请先选择账号");G(!0);try{const n=await pr(I);await Ae(),alert((n==null?void 0:n.message)||"商品同步完成")}catch(n){console.error("同步商品失败:",n),alert((n==null?void 0:n.message)||"同步失败,请重试")}finally{G(!1)}},te=n=>{Se(n),Oe({...n}),Q(!0)},je=async()=>{if(de)try{await vr(de.cookie_id,de.item_id,{item_title:fe.item_title||"",item_description:fe.item_description||"",item_category:fe.item_category||"",item_price:fe.item_price||"",item_detail:fe.item_detail||de.item_detail||""}),await Ae(),await we(),Q(!1),Se(null)}catch(n){console.error("更新商品失败:",n),alert("更新失败,请重试")}},u=async n=>{if(confirm(`确认删除商品"${n.item_title}"吗?`))try{await ur(n.cookie_id,n.item_id),l(w=>w.filter(H=>!(H.cookie_id===n.cookie_id&&H.item_id===n.item_id)))}catch(w){console.error("删除商品失败:",w),alert("删除失败,请重试")}},L=async()=>{try{if(!re.cookie_id||!re.item_id){alert("请选择账号并填写商品ID");return}await hr(re.cookie_id,{item_id:re.item_id,item_title:re.item_title,item_price:re.item_price,item_detail:re.item_image?JSON.stringify({item_image:re.item_image}):""}),await Ae(),B(!1),h({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(n){console.error("添加商品失败:",n),alert("添加失败,请重试")}},le=async()=>{if(!f.cookie_id)return alert("请选择发布账号");if(!f.title.trim())return alert("请填写商品标题");if(!f.price.trim())return alert("请填写商品价格");if(!f.quantity||Number(f.quantity)<=0)return alert("库存数量必须大于 0");if(f.images.length===0)return alert("至少上传 1 张商品图片");if(f.postage_mode==="fixed"&&!f.postage.trim())return alert("请填写一口价邮费");oe(!0);try{const n=await gr({...f,location:M||void 0});if(await Ae(),ue(!1),R({cookie_id:I||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),U([]),ne(null),n!=null&&n.item_id){const w={id:n.item_id,cookie_id:f.cookie_id,item_id:n.item_id,item_title:n.item_title||f.title,item_price:n.item_price||f.price,item_image:n.item_image};t(w),alert("商品发布成功,ID: "+n.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(n){console.error("发布商品失败:",n);const w=n==null?void 0:n.payload;if((w==null?void 0:w.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((n==null?void 0:n.message)||"发布失败,请重试")}finally{oe(!1)}},_e=async()=>{K("upload"),c(null),D(null),J(null),E(null),be(""),V({catId:"",catName:"",channelCatId:"",tbCatId:""}),ye([]),ke(null),Z(!0),q(!0);try{const n=await Hs(20),w=dn(n);if(w!=null&&w.id){const H=await bt(w.id);Y(H),D(H),K(["running","canceling"].includes(H.status)?"running":"done")}}catch(n){console.error("恢复最近批量铺货任务失败:",n)}finally{q(!1)}},Ue=async()=>{const n=P.trim();if(!I)return alert("请先选择默认发布账号");if(!n)return alert("请输入类目关键词");ae(!0);try{const H=(await br(I,n)).category;V({catId:H.cat_id,catName:H.cat_name,channelCatId:H.channel_cat_id,tbCatId:H.tb_cat_id||""})}catch(w){console.error("获取推荐类目失败:",w),alert((w==null?void 0:w.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{ae(!1)}},Fe=async()=>{if(S!=null&&S.id){q(!0),Z(!0);try{const n=await bt(S.id);D(n),K(["running","canceling"].includes(n.status)?"running":"done")}catch(n){console.error("加载最近批量铺货结果失败:",n)}finally{q(!1)}}},tt=async()=>{if(!ve)return alert("请先上传商品表格");if(!I)return alert("请先选择默认发布账号");q(!0);try{const n=await fr({file:ve,imagesZip:A,defaultCookieId:I,fallbackCategory:x,location:Ee||void 0});c(n),D(null),K("preview")}catch(n){console.error("批量铺货预检失败:",n),alert((n==null?void 0:n.message)||"预检失败,请检查表格和图片 zip")}finally{q(!1)}},kt=async()=>{if(X!=null&&X.preview_id){if(X.valid<=0)return alert("没有可发布的商品行");q(!0);try{const n=await yr(X.preview_id),w=await bt(n.batch_id||X.preview_id);D(w),Y(w),K(w.status==="running"?"running":"done")}catch(n){console.error("启动批量铺货失败:",n),alert((n==null?void 0:n.message)||"启动发布任务失败")}finally{q(!1)}}},Je=async()=>{if(d!=null&&d.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){q(!0);try{const n=await _r(d.id),w=await bt(d.id);D(w),K((n==null?void 0:n.status)==="canceling"||w.status==="canceling"?"running":"done")}catch(n){alert((n==null?void 0:n.message)||"取消失败")}finally{q(!1)}}},We=async()=>{const n=X==null?void 0:X.preview_id;if(n&&se==="preview")try{await jr(n)}catch(w){console.error("清理批量铺货预检失败:",w)}c(null),K("upload")},Ct=async()=>{await We(),Z(!1)},St=async()=>{if(d!=null&&d.id){q(!0);try{await Nr(d.id),D(await bt(d.id)),K("running")}catch(n){alert((n==null?void 0:n.message)||"重试失败")}finally{q(!1)}}},mt=()=>{const H=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","类目ID","类目名称","频道类目ID","淘宝类目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(y=>y.map($=>`"${String($).replace(/"/g,'""')}"`).join(",")).join(` -`),Te=new Blob(["\uFEFF"+H],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(Te),o=document.createElement("a");o.href=s,o.download="批量铺货模板.csv",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(s)},Lt=()=>{h(n=>({...n,cookie_id:I||n.cookie_id})),B(!0)},nt=()=>{R(n=>({...n,cookie_id:I||n.cookie_id})),ue(!0)},it=async n=>{if(!(n?I:f.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");p(!0),navigator.geolocation.getCurrentPosition(async H=>{try{const Te=await hn(H.coords.longitude,H.coords.latitude);if(!Te.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");n?(ye(Te),ke(Te[0])):(U(Te),ne(Te[0]))}catch(Te){alert((Te==null?void 0:Te.message)||"获取发货地失败")}finally{p(!1)}},H=>{p(!1),alert(H.code===H.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Ot=n=>i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id).length>0?i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id):i.filter(w=>w.cookie_id===n.cookie_id&&!w.item_id),pt=n=>{switch(n){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 n||"-"}},ut=n=>{switch(n){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"}},st=r.useMemo(()=>new Map(_.map(n=>[n.id,n])),[_]),ht=r.useMemo(()=>C?a.filter(n=>n.cookie_id===C):a,[C,a]),Ge=n=>{const w=st.get(n),H=(w==null?void 0:w.remark)||(w==null?void 0:w.nickname);return H?`${H} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ot=n=>{const w=st.get(n);return(w==null?void 0:w.remark)||(w==null?void 0:w.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(al,{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:C,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.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(xt,{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:I,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:De,disabled:F||!I,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(ze,{className:`w-4 h-4 ${F?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Lt,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(et,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:nt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void _e(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Bt,{className:"w-4 h-4"}),S&&["running","canceling"].includes(S.status)?"继续批量任务":"批量铺货"]}),S&&!["running","canceling"].includes(S.status)&&e.jsx("button",{onClick:()=>void Fe(),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:[ht.map(n=>{const w=Ot(n),H=w.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:()=>te(n),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-brand hover:text-white transition-colors",title:"编辑",children:e.jsx(_t,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>u(n),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(Qe,{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:[n.item_image?e.jsx("img",{src:n.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(ga,{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:gn(n.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:n.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:ot(n.cookie_id),children:[e.jsx(xt,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:ot(n.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: ",n.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${H?"text-emerald-600":"text-amber-600"}`,children:[H?e.jsx(ds,{className:"w-3 h-3"}):e.jsx(ll,{className:"w-3 h-3"}),H?`${w.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>t(n),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${H?"bg-gray-900 text-white hover:bg-black":"bg-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(rl,{className:"w-3.5 h-3.5"}),H?"查看发货规则":"关联发货规则"]}),e.jsx(xs,{className:"w-3.5 h-3.5"})]})})]},`${n.cookie_id}-${n.item_id}`)}),ht.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(ba,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),C?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),ce&&de&&qe.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: ",de.item_id]})]}),e.jsx("button",{onClick:()=>Q(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Me,{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:fe.item_title||"",onChange:n=>Oe({...fe,item_title:n.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:fe.item_price||"",onChange:n=>Oe({...fe,item_price:n.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:fe.item_category||"",onChange:n=>Oe({...fe,item_category:n.target.value})}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:fe.item_description||"",onChange:n=>Oe({...fe,item_description:n.target.value})})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:je,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),ee&&qe.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:()=>B(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Me,{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:re.cookie_id,onChange:n=>h({...re,cookie_id:n.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.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:re.item_id,onChange:n=>h({...re,item_id:n.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:re.item_price,onChange:n=>h({...re,item_price:n.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:re.item_title,onChange:n=>h({...re,item_title:n.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:re.item_image,onChange:n=>h({...re,item_image:n.target.value})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:L,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(et,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),ge&&qe.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:()=>ue(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Me,{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:f.cookie_id,onChange:n=>{R({...f,cookie_id:n.target.value}),U([]),ne(null)},children:[e.jsx("option",{value:"",children:"选择账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.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:f.title,onChange:n=>R({...f,title:n.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:f.quantity,onChange:n=>R({...f,quantity:n.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:f.description,onChange:n=>R({...f,description:n.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:f.price,onChange:n=>R({...f,price:n.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:f.original_price,onChange:n=>R({...f,original_price:n.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:f.postage_mode,onChange:n=>R({...f,postage_mode:n.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:"无需邮寄"})]})]})]}),f.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:f.postage,onChange:n=>R({...f,postage:n.target.value})})]}),e.jsxs("div",{className:"rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。"})]}),e.jsxs("button",{type:"button",disabled:T||!f.cookie_id,onClick:()=>void it(!1),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(Ms,{className:"h-4 w-4"}),T?"定位中...":"获取当前位置"]})]}),b.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,b.indexOf(M))),onChange:n=>ne(b[Number(n.target.value)]||null),children:b.map((n,w)=>e.jsx("option",{value:String(w),children:[n.province,n.city,n.area,n.poi_name].filter(Boolean).join(" ")},`${n.division_id}-${n.poi_id}-${w}`))})]}),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(Bt,{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:f.images.length?"已选择 "+f.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:n=>R({...f,images:Array.from(n.target.files||[]).slice(0,9)})})]}),z.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:z.map(n=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:n.url,alt:"",className:"w-full h-full object-cover"})},n.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:me,onClick:le,className:"w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),me?"正在发布...":"发布到闲鱼"]})})]})}),document.body),k&&qe.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 Ct(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Me,{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(([n,w])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${se===n?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:w},n))}),se==="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:mt,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:I,onChange:n=>{g(n.target.value),ye([]),ke(null)},children:[e.jsx("option",{value:"",children:"选择账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-extrabold text-gray-900",children:["默认类目 ",e.jsx("span",{className:"font-medium text-gray-500",children:"(可为空)"})]}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-amber-800",children:"填写后优先使用该类目;留空时由闲鱼根据每件商品自动识别。仍无法识别时,系统最终使用“电子资料”兜底。"})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs("label",{className:"relative flex-1",children:[e.jsx("span",{className:"sr-only",children:"类目关键词"}),e.jsx(Nt,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"w-full ios-input rounded-xl bg-white py-2.5 pl-10 pr-3",placeholder:"输入关键词,例如:课程资料、设计素材",value:P,onChange:n=>be(n.target.value),onKeyDown:n=>{n.key==="Enter"&&(n.preventDefault(),Ue())}})]}),e.jsxs("button",{type:"button",disabled:!I||!P.trim()||Re,onClick:()=>void Ue(),className:"ios-btn-primary flex min-h-[42px] items-center justify-center gap-2 rounded-xl px-4 text-sm font-bold disabled:opacity-50",children:[e.jsx(Nt,{className:"h-4 w-4"}),Re?"匹配中...":"获取类目"]})]}),x.catId?e.jsxs("div",{className:"flex min-h-[46px] items-center justify-between gap-3 border-t border-amber-200 pt-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold text-gray-900",children:[e.jsx(ds,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:x.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",x.catId," · 频道 ",x.channelCatId]})]}),e.jsx("button",{type:"button",title:"清除默认类目",onClick:()=>V({catId:"",catName:"",channelCatId:"",tbCatId:""}),className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",children:e.jsx(Me,{className:"h-4 w-4"})})]}):null]}),e.jsxs("div",{className:"rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"批次发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。"})]}),e.jsxs("button",{type:"button",disabled:T||!I,onClick:()=>void it(!0),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(Ms,{className:"h-4 w-4"}),T?"定位中...":"获取当前位置"]})]}),he.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,he.indexOf(Ee))),onChange:n=>ke(he[Number(n.target.value)]||null),children:he.map((n,w)=>e.jsx("option",{value:String(w),children:[n.province,n.city,n.area,n.poi_name].filter(Boolean).join(" ")},`${n.division_id}-${n.poi_id}-${w}`))})]}),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(Bt,{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:ve?ve.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:n=>{var w;return J(((w=n.target.files)==null?void 0:w[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(Bt,{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:n=>{var w;return E(((w=n.target.files)==null?void 0:w[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","需要指定当前行默认类目时填写","必须和“类目名称、频道类目ID”同时填写;优先于自动识别"],["类目名称","填写了“类目ID”时必填","填写该 ID 对应的准确类目名称"],["频道类目ID","覆盖类目时必填","必须填写闲鱼返回的准确频道类目 ID"],["淘宝类目ID","按闲鱼返回填写","“电子资料”无淘宝类目 ID,保持为空"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([n,w,H])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:n}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${w==="每个商品都要填"?"text-red-600":w==="可以留空"?"text-gray-500":"text-amber-700"}`,children:w}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:H})]},n))})]})})]})]}),se==="preview"&&X&&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:X.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:X.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:X.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("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:X.rows.map(n=>{var w,H,Te,s;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:n.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 ${n.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:n.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:n.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",n.price||"-"," / ",n.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((w=n.category)==null?void 0:w.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((H=n.category)==null?void 0:H.cat_id)||"失败后使用电子资料"})]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((Te=n.images)==null?void 0:Te.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((s=n.errors)==null?void 0:s.join(";"))||"-"})]},n.row_no)})})]})})]}),(se==="running"||se==="done")&&d&&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 ${ut(d.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:pt(d.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:d.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:d.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:d.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:d.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:"类目策略"}),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:d.rows.map(n=>{var w,H;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:n.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 ${ut(n.status)}`,children:pt(n.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:n.title}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((w=n.category)==null?void 0:w.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((H=n.category)==null?void 0:H.cat_id)||"失败后使用电子资料"})]}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:n.item_url?e.jsx("a",{href:n.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:n.item_id}):n.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:n.error_message||"-"})]},n.id)})})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[se==="upload"&&e.jsxs("button",{disabled:v||!ve||!I,onClick:tt,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(ze,{className:`w-4 h-4 ${v?"animate-spin":""}`}),v?"正在预检...":"开始预检"]}),se==="preview"&&X&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:v,onClick:()=>void We(),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:v||X.valid<=0,onClick:kt,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(es,{className:"w-4 h-4"}),v?"启动中...":`确认发布 ${X.valid} 个商品`]})]}),(se==="running"||se==="done")&&d&&e.jsxs("div",{className:"flex gap-3 w-full",children:[d.status==="running"?e.jsx("button",{disabled:v,onClick:Je,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):d.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/${d.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:"下载结果"}),d.retryable>0&&!["running","canceling"].includes(d.status)&&e.jsxs("button",{disabled:v,onClick:St,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(ze,{className:`w-4 h-4 ${v?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(d.status)&&e.jsx("button",{onClick:()=>{Z(!1),Ae(),we()},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)]})},ra="https://dashscope.aliyuncs.com/compatible-mode/v1",fn=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],yn=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"]),jn=()=>{const[t,a]=r.useState(null),[l,i]=r.useState(!1),[m,_]=r.useState(""),[N,I]=r.useState(!1),[g,C]=r.useState([]),[j,F]=r.useState(!1),[G,me]=r.useState(""),[oe,v]=r.useState(!1),q=r.useRef(null),[ce,Q]=r.useState(!1),[ee,B]=r.useState(!1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState(!1),[ve,J]=r.useState(null),[A,E]=r.useState({new_username:"",current_password:"",new_password:"",confirm_password:""});r.useEffect(()=>{be(),Sa().then(b=>{b.username&&E(U=>({...U,new_username:b.username||""}))}).catch(()=>{})},[]),r.useEffect(()=>{const b=U=>{var M;(M=q.current)!=null&&M.contains(U.target)||v(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const P=async(b,U=!1)=>{const M=b||t,ne=(M==null?void 0:M.ai_api_url)||(M==null?void 0:M.ai_base_url)||ra;F(!0),me("");try{const he=await Tr(ne,(M==null?void 0:M.ai_api_key)||"");C(he),v(U&&he.length>0),!(M!=null&&M.ai_model)&&he.length>0&&a(ye=>ye&&{...ye,ai_model:he[0]})}catch(he){C([]),v(!1),me(he.message||"读取模型失败")}finally{F(!1)}},be=()=>{i(!0),_(""),Aa().then(b=>{a(b),P(b)}).catch(b=>{a(null),_(b.message||"加载配置失败")}).finally(()=>i(!1))},Re=async()=>{if(t){I(!0);try{const b=Object.fromEntries(Object.entries(t).filter(([U,M])=>!yn.has(U)&&M!==void 0&&M!==null));await $a(b),alert("系统配置已保存")}catch(b){alert("保存失败:"+b.message)}finally{I(!1)}}},ae=async b=>{b.preventDefault(),J(null);const U=A.new_username.trim();if(U.length<3){J({type:"error",text:"用户名至少需要 3 个字符"});return}if(!A.current_password){J({type:"error",text:"请输入当前密码确认身份"});return}if(A.new_password&&A.new_password.length<8){J({type:"error",text:"新密码至少需要 8 个字符"});return}if(A.new_password!==A.confirm_password){J({type:"error",text:"两次输入的新密码不一致"});return}K(!0);try{const M=await $l({current_password:A.current_password,new_username:U,new_password:A.new_password||void 0});if(!M.success){J({type:"error",text:M.message||"登录凭据更新失败"});return}J({type:"success",text:M.message||"登录凭据已更新"}),window.setTimeout(()=>window.location.reload(),1400)}catch(M){J({type:"error",text:M.message||"登录凭据更新失败"})}finally{K(!1)}};if(!t)return e.jsx("div",{className:"p-8 text-center text-gray-400",children:m||(l?"加载配置中...":"暂无配置")});const T=t.ai_model||"",p=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(js,{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:be,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(ze,{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(nl,{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:t.log_level||"info",onChange:b=>a({...t,log_level:b.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:fn.map(b=>e.jsx("option",{value:b.value,children:b.label},b.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:t.log_format||"text",onChange:b=>a({...t,log_format:b.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:t.renewal_log_retention_days??10,onChange:b=>a({...t,renewal_log_retention_days:parseInt(b.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-brand text-white",children:e.jsx(vs,{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:t.ai_api_url||ra,onChange:b=>a({...t,ai_api_url:b.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:ce?"text":"password",value:t.ai_api_key||"",onChange:b=>a({...t,ai_api_key:b.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:()=>Q(!ce),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:ce?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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:q,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:T,onFocus:()=>g.length>0&&v(!0),onChange:b=>{a({...t,ai_model:b.target.value}),g.length>0&&v(!0)},onKeyDown:b=>{b.key==="Escape"&&v(!1),b.key==="ArrowDown"&&g.length>0&&v(!0)},className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:()=>g.length>0&&v(b=>!b),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(il,{className:`w-4 h-4 transition-transform ${oe?"rotate-180":""}`})}),oe&&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:p.length>0?p.map(b=>e.jsxs("button",{type:"button",onClick:()=>{a({...t,ai_model:b}),v(!1)},className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:b}),b===T&&e.jsx(Ke,{className:"w-4 h-4 shrink-0 text-brand"})]},b)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:()=>P(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(ze,{className:`w-4 h-4 ${j?"animate-spin":""}`}),"读取模型"]})]}),G?e.jsx("p",{className:"text-xs text-red-500",children:G}):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(Mt,{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:t["captcha.remote_service_url"]||"",onChange:b=>a({...t,"captcha.remote_service_url":b.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:ee?"text":"password",value:t["captcha.remote_secret_key"]||"",onChange:b=>a({...t,"captcha.remote_secret_key":b.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:()=>B(!ee),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:ee?"隐藏秘钥":"显示秘钥",children:ee?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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(t["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:b=>a({...t,"captcha.remote_pass_cookies":b.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(qs,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:ae,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(Gt,{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:b=>E({...A,new_username:b.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:ge?"text":"password",value:A.current_password,onChange:b=>E({...A,current_password:b.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:()=>ue(!ge),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:ge?"隐藏密码":"显示密码",children:ge?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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:k?"text":"password",value:A.new_password,onChange:b=>E({...A,new_password:b.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:()=>Z(!k),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:k?"隐藏密码":"显示密码",children:k?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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:k?"text":"password",value:A.confirm_password,onChange:b=>E({...A,confirm_password:b.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),ve&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${ve.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(Mt,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:ve.text})]}),e.jsxs("button",{type:"submit",disabled:se||!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(qs,{className:"w-4 h-4"}),se?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:Re,disabled:N,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(He,{className:"w-6 h-6"}),N?"保存中...":"保存所有配置"]})})]})},ns=(t,a)=>t.allowed_resolutions.includes(a),_n=(t,a)=>({runs:t.runs.filter(l=>!a||l.cookie_id===a),pending_tasks:t.pending_tasks.filter(l=>!a||l.cookie_id===a)}),Nn=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",vn=(t,a,l,i,m,_)=>t!==a||l!==i?!1:(_(m),!0),at={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:qt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:ol},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:va}},Vt=["order_paid","buyer_reviewed","review_missing_timeout"],wn="亲,商品使用满意的话,麻烦给个评价,谢谢~",Pt=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),Ea=t=>{if(!t)return{};try{const a=JSON.parse(t);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return{}}},ct=(t,a={})=>{const l=Ea(t);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),...a})},Rt=(t,a)=>{var i;const l=((i=at[t])==null?void 0:i.label)||"自动化规则";return a?`${l} - ${a}`:l},na=t=>{const a=(t||"").trim();return a?Object.values(at).some(l=>a===l.label||a.startsWith(`${l.label} -`)):!0},Et=(t,a=0)=>{if(t==="review_missing_timeout")return[{action_type:"send_text",message_template:wn,enabled:!0,sort_order:1}];const l={action_type:"send_card",card_id:a,delivery_count:1,enabled:!0,sort_order:1};return t==="order_paid"?[l,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[l]},kn=t=>{var l,i;if(t.trigger_type==="review_missing_timeout")return((i=(l=t.actions)==null?void 0:l.find(m=>m.action_type==="send_text"))==null?void 0:i.message_template)||"发送求评价文案";const a=(t.actions||[]).filter(m=>m.action_type==="send_card");return a.length?a.map(m=>m.card_name||`卡密 ${m.card_id}`).join(" / "):"未配置卡密库存"},ia=(t,a=!1)=>{const l={blue:a?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:a?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:a?"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[t]||l.blue},Cn=t=>t?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Qt=t=>(t==null?void 0:t.nickname)||(t==null?void 0:t.remark)||(t==null?void 0:t.id)||"未知账号",Sn=t=>t===!0||t===1||t==="1",Ln=({initialDeliveryTarget:t,onDeliveryTargetHandled:a})=>{var w,H,Te;const[l,i]=r.useState("automation"),[m,_]=r.useState([]),[N,I]=r.useState({runs:[],pending_tasks:[]}),[g,C]=r.useState([]),[j,F]=r.useState({}),[G,me]=r.useState([]),[oe,v]=r.useState([]),[q,ce]=r.useState([]),[Q,ee]=r.useState(!1),[B,ge]=r.useState(""),[ue,k]=r.useState(""),[Z,se]=r.useState(""),[K,ve]=r.useState(""),[J,A]=r.useState("all"),[E,P]=r.useState(1),[be,Re]=r.useState(10),[ae,T]=r.useState(0),[p,b]=r.useState(0),[U,M]=r.useState({}),ne=r.useRef(0),he=r.useRef(0),ye=r.useRef("");ye.current=B;const[Ee,ke]=r.useState(!1),[x,V]=r.useState(!1),[X,c]=r.useState(!1),[d,D]=r.useState(null),[S,Y]=r.useState(null),[O,de]=r.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""});G.find(s=>s.id===B);const Se=r.useCallback(async()=>{const[s,o,y,$]=await Promise.all([Ft(),Xe(),vt(),Xs()]);me(s),v(o),ce(y),F($),ge(W=>{var pe;return W||((pe=s[0])==null?void 0:pe.id)||""})},[]),fe=r.useCallback(async()=>{const s=++ne.current,o=Sr().catch(W=>(console.warn("加载自动化异常列表失败,不阻断规则展示",W),null)),y=await wr({cookieId:B||void 0,triggerType:K,enabled:J==="all"?void 0:J==="enabled",search:Z,page:E,pageSize:be});if(s!==ne.current)return;_(y.data),T(y.total),b(y.total_pages),M(y.trigger_counts||{}),y.page!==E&&P(y.page);const $=await o;s===ne.current&&$&&I($)},[E,be,J,K,Z,B]),Oe=r.useCallback(async()=>{const s=B;if(s!==ye.current)return;const o=++he.current;if(C([]),!s)return;const y=await $r(s);vn(o,he.current,s,ye.current,y,C)},[B]),re=r.useCallback(async()=>{F(await Xs())},[]),h=r.useCallback(async()=>{ee(!0);try{l==="automation"?await fe():l==="reply"?await Oe():await re()}finally{ee(!1)}},[l,fe,re,Oe]);r.useEffect(()=>{const s=window.setTimeout(()=>{P(1),se(ue.trim())},300);return()=>window.clearTimeout(s)},[ue]),r.useEffect(()=>{Se().catch(s=>console.error("加载规则参考数据失败",s))},[Se]),r.useEffect(()=>{h().catch(s=>console.error("刷新规则页面失败",s))},[h]);const f=r.useMemo(()=>m.filter(s=>!B||s.cookie_id===B),[m,B]),R=r.useMemo(()=>_n(N,B),[N,B]),z=r.useMemo(()=>G.filter(s=>!B||s.id===B),[G,B]),Ie=r.useMemo(()=>{if(p<=1)return[];const s=Math.max(1,Math.min(E-2,p-4)),o=Math.min(p,s+4);return Array.from({length:o-s+1},(y,$)=>s+$)},[E,p]),Ae=!!(ue.trim()||K||J!=="all"),we=()=>{k(""),se(""),ve(""),A("all"),P(1)},De=r.useMemo(()=>{const s=(d==null?void 0:d.cookie_id)||B;return q.filter(o=>o.cookie_id===s)},[d==null?void 0:d.cookie_id,q,B]),te=r.useMemo(()=>{if(!(!(d!=null&&d.cookie_id)||!(d!=null&&d.item_id)))return q.find(s=>s.cookie_id===d.cookie_id&&s.item_id===d.item_id)},[d==null?void 0:d.cookie_id,d==null?void 0:d.item_id,q]),je=Sn(te==null?void 0:te.is_multi_spec),u=(d==null?void 0:d.trigger_type)||"order_paid",L=at[u],le=Ea(d==null?void 0:d.config_json),_e=r.useCallback((s="order_paid",o=B,y="")=>{const $=q.find(pe=>pe.cookie_id===o&&pe.item_id===y),W=($==null?void 0:$.item_title)||y;return{name:Rt(s,W),trigger_type:s,cookie_id:o,item_id:y,item_title:($==null?void 0:$.item_title)||"",item_keyword:W,card_group_id:0,priority:100,enabled:!0,config_json:s==="review_missing_timeout"?ct():"{}",actions:Et(s),variants:s==="review_missing_timeout"?[]:[Pt()]}},[q,B]),Ue=r.useCallback(s=>{var y,$;const o=s.trigger_type||"order_paid";D({...s,trigger_type:o,config_json:o==="review_missing_timeout"?ct(s.config_json):s.config_json||"{}",actions:(y=s.actions)!=null&&y.length?s.actions.map(W=>({...W})):Et(o,s.card_group_id),variants:($=s.variants)!=null&&$.length?s.variants.map(W=>({...W})):o==="review_missing_timeout"?[]:[Pt()]}),ke(!0)},[]);r.useEffect(()=>{if(!t)return;let s=!1;return(async()=>{i("automation"),ge(t.cookieId),ee(!0);try{const[y,$,W]=await Promise.all([gs(),vt(),Xe().catch(xe=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",xe),[]))]);if(s)return;_(y),ce($),v(W);const pe=y.find(xe=>xe.cookie_id===t.cookieId&&xe.item_id===t.itemId&&xe.trigger_type==="order_paid");if(pe)Ue(pe);else{const xe=$.find($e=>$e.cookie_id===t.cookieId&&$e.item_id===t.itemId);D({..._e("order_paid",t.cookieId,t.itemId),item_title:(xe==null?void 0:xe.item_title)||"",item_keyword:(xe==null?void 0:xe.item_title)||t.itemId,name:Rt("order_paid",(xe==null?void 0:xe.item_title)||t.itemId)}),ke(!0)}}catch(y){console.error("打开商品自动化规则失败",y),alert("无法加载该商品的自动化规则")}finally{s||(ee(!1),a==null||a())}})(),()=>{s=!0}},[_e,t,a,Ue]);const Fe=(s="order_paid")=>{if(!B){alert("请先选择账号");return}D(_e(s)),ke(!0)},tt=s=>{var $,W,pe,xe,$e;if(!d)return;const o=((W=($=d.variants)==null?void 0:$.find(ie=>ie.card_id))==null?void 0:W.card_id)||((xe=(pe=d.actions)==null?void 0:pe.find(ie=>ie.action_type==="send_card"))==null?void 0:xe.card_id)||d.card_group_id||0,y=(te==null?void 0:te.item_title)||d.item_title||d.item_id||"";D({...d,trigger_type:s,name:na(d.name)?Rt(s,y):d.name,card_group_id:o,config_json:s==="review_missing_timeout"?ct(d.config_json):"{}",actions:Et(s,o),variants:s==="review_missing_timeout"?[]:($e=d.variants)!=null&&$e.length?d.variants:[{...Pt(),card_id:o}]})},kt=s=>{if(!d)return;const o=q.find($=>$.cookie_id===(d.cookie_id||B)&&$.item_id===s),y=(o==null?void 0:o.item_title)||s;D({...d,item_id:s,item_title:(o==null?void 0:o.item_title)||"",item_keyword:y,name:na(d.name)?Rt(u,y):d.name})},Je=(w=d==null?void 0:d.variants)!=null&&w.length?d.variants:[Pt()],We=(s,o)=>{var $;if(!d)return;const y=Je.map((W,pe)=>pe===s?{...W,...o}:W);D({...d,variants:y,card_group_id:(($=y[0])==null?void 0:$.card_id)||0})},Ct=()=>{if(!d)return;const s=Je[Je.length-1];D({...d,variants:[...Je,{...Pt(),spec_name:je&&(s==null?void 0:s.spec_name)||"",spec_value:je&&(s==null?void 0:s.spec_value)||""}]})},St=async()=>{var $,W,pe,xe,$e;if(!d)return;const s=d.trigger_type||"order_paid";if(!d.cookie_id){alert("请选择账号");return}const o=($=d.variants)!=null&&$.length?d.variants:[];if(s!=="review_missing_timeout"){if(!o.length||o.some(ie=>!ie.card_id)){alert(s==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");return}if(je&&o.some(ie=>!ie.spec_name.trim()||!ie.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}}if(s==="review_missing_timeout"&&!(((pe=(W=d.actions)==null?void 0:W.find(Ye=>Ye.action_type==="send_text"))==null?void 0:pe.message_template)||"").trim()){alert("请填写求评价文案");return}const y=s==="review_missing_timeout"?[]:o.map(ie=>({...ie,spec_name:je?ie.spec_name.trim():"",spec_value:je?ie.spec_value.trim():"",delivery_count:Math.max(1,Number(ie.delivery_count)||1),enabled:ie.enabled!==!1}));try{await Zs({...d,trigger_type:s,name:(d.name||"").trim()||Rt(s,(te==null?void 0:te.item_title)||d.item_id||""),config_json:s==="review_missing_timeout"?ct(d.config_json):d.config_json||"{}",actions:(xe=d.actions)!=null&&xe.length?d.actions:Et(s,(($e=y[0])==null?void 0:$e.card_id)||d.card_group_id||0),variants:y}),ke(!1),await Promise.all([fe(),Se()]),alert("保存成功")}catch(ie){console.error("保存自动化规则失败:",ie),alert("保存失败:"+ie.message)}},mt=async s=>{if(confirm("确定删除该自动化规则吗?"))try{await Cr(s),await fe(),alert("删除成功")}catch(o){alert("删除失败:"+o.message)}},Lt=async s=>{try{await Zs({...s,enabled:!s.enabled}),await fe()}catch(o){alert("操作失败:"+o.message)}},nt=async(s,o)=>{if(confirm(o==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":o==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Lr(s,o),await fe()}catch($){alert("处理失败:"+$.message)}},it=async(s,o)=>{if(confirm(o==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Or(s,o),await fe()}catch(y){alert("处理失败:"+y.message)}},Ot=()=>{if(!B){alert("请先选择账号");return}Y({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),V(!0)},pt=async()=>{var o,y,$;if(!S||!B)return;const s=S.type==="image"?!!((o=S.image_url)!=null&&o.trim()):!!((y=S.reply_content)!=null&&y.trim());if(!(($=S.keyword)!=null&&$.trim())||!s){alert("请填写关键词和回复内容");return}try{await Pr({...S,match_type:"fuzzy",enabled:!0},B),V(!1),await Oe(),alert("保存成功")}catch(W){alert("保存失败:"+W.message)}},ut=async s=>{if(!(!B||!confirm("确定删除该回复规则吗?")))try{await Rr(s,B),await Oe(),alert("删除成功")}catch(o){alert("删除失败:"+o.message)}},st=async(s=B)=>{if(!s){alert("请先选择账号");return}try{const o=await Ur(s);de({cookie_id:s,enabled:o.enabled,reply_content:o.reply_content,reply_once:o.reply_once,reply_image_url:o.reply_image_url||""})}catch{de({cookie_id:s,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}c(!0)},ht=async()=>{if(!O.cookie_id){alert("请先选择账号");return}if(O.enabled&&!O.reply_content.trim()&&!O.reply_image_url.trim()){alert("启用默认回复时,请填写回复内容或图片 URL");return}try{await Wr(O.cookie_id,{enabled:O.enabled,reply_content:O.reply_content,reply_once:O.reply_once,reply_image_url:O.reply_image_url}),c(!1),await re(),alert("保存成功")}catch(s){alert("保存失败:"+s.message)}},Ge=async s=>{if(confirm("确定删除该账号默认回复吗?"))try{await Jr(s),await re(),alert("删除成功")}catch(o){alert("删除失败:"+o.message)}},ot=async s=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Vr(s),alert("清空成功")}catch(o){alert("清空失败:"+o.message)}},n=l==="automation"?"新建自动化":l==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"min-w-0 space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row 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:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap gap-3",children:[e.jsxs("select",{value:B,onChange:s=>{ge(s.target.value),P(1)},className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),G.map(s=>e.jsx("option",{value:s.id,children:Qt(s)},s.id))]}),e.jsxs("button",{onClick:h,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 whitespace-nowrap transition-colors",children:[e.jsx(ze,{className:`w-4 h-4 ${Q?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:l==="automation"?()=>Fe("order_paid"):l==="reply"?Ot:()=>void st(),disabled:!B,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50",children:[e.jsx(et,{className:"w-4 h-4"}),n]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:cs},{id:"reply",label:"关键词回复",icon:Tt},{id:"default",label:"账号默认回复",icon:yt}].map(s=>{const o=s.icon;return e.jsxs("button",{onClick:()=>i(s.id),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${l===s.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(o,{className:"w-4 h-4"}),s.label]},s.id)})}),l==="automation"&&(R.runs.length>0||R.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(rt,{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:[R.runs.map(s=>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:["账号 ",s.cookie_id," · 订单 ",s.order_id||"-"," · 已记录发送 ",s.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Nn(s.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:s.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[ns(s,"continue")&&e.jsx("button",{onClick:()=>void nt(s.id,"continue"),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),ns(s,"retry")&&e.jsx("button",{onClick:()=>void nt(s.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),ns(s,"cancel")&&e.jsx("button",{onClick:()=>void nt(s.id,"cancel"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${s.id}`)),R.pending_tasks.map(s=>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:["账号 ",s.cookie_id," · 延迟任务重试已达 ",s.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:s.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>void it(s.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 it(s.id,"dismiss"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${s.id}`))]})]}),l==="automation"&&e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]",children:[e.jsxs("aside",{className:"min-w-0 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:Vt.map(s=>{const o=at[s],y=o.icon;return e.jsx("button",{type:"button",onClick:()=>Fe(s),className:`w-full text-left rounded-2xl border p-4 transition-colors ${ia(o.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(y,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:o.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:o.description})]})]})},s)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"font-black text-gray-900",children:"筛选结果构成"}),e.jsxs("span",{className:"text-xs font-bold text-gray-400",children:["共 ",ae," 条"]})]}),e.jsx("div",{className:"space-y-3",children:Vt.map(s=>{const o=at[s],y=o.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(y,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:o.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:U[s]||0})]},s)})})]})]}),e.jsxs("section",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-surface-muted p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(Nt,{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:"搜索规则名、商品名或商品 ID...",value:ue,onChange:s=>{k(s.target.value),P(1)},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:"relative xl:w-52",children:[e.jsx(Na,{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:K,onChange:s=>{ve(s.target.value),P(1)},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:"全部自动化类型"}),Vt.map(s=>e.jsx("option",{value:s,children:at[s].shortLabel},s))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:J,onChange:s=>{A(s.target.value),P(1)},className:"ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36",children:[e.jsx("option",{value:"all",children:"全部状态"}),e.jsx("option",{value:"enabled",children:"已启用"}),e.jsx("option",{value:"disabled",children:"已禁用"})]}),Ae&&e.jsx("button",{type:"button",onClick:we,className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900",title:"清除筛选","aria-label":"清除筛选",children:e.jsx(Me,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs font-bold text-gray-400",children:[e.jsxs("span",{children:["找到 ",ae," 条规则"]}),Q&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ze,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),Q&&f.length===0?e.jsxs("div",{className:"flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400",children:[e.jsx(ze,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):f.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(cs,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:Ae?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:Ae?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):f.map(s=>{const o=at[s.trigger_type],y=o.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 ${ia(o.accent,!0)}`,children:e.jsx(y,{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:s.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Cn(s.enabled)}`,children:s.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:o.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:s.item_title||s.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:kn(s)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:()=>Ue(s),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(_t,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:()=>Lt(s),className:`px-4 py-2 rounded-xl text-sm font-bold ${s.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:s.enabled?"禁用":"启用"}),e.jsx("button",{onClick:()=>mt(s.id),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Qe,{className:"w-4 h-4"})})]})]})},s.id)}),ae>0&&e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm font-medium text-gray-500",children:[e.jsxs("span",{children:["第 ",E," / ",Math.max(p,1)," 页"]}),e.jsx("span",{className:"h-4 w-px bg-gray-200"}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"sr-only",children:"每页显示数量"}),e.jsx("select",{value:be,onChange:s=>{Re(Number(s.target.value)),P(1)},className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(s=>e.jsxs("option",{value:s,children:[s," 条/页"]},s))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:E<=1||Q,onClick:()=>P(s=>Math.max(1,s-1)),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"上一页",title:"上一页",children:e.jsx(Ns,{className:"h-4 w-4"})}),Ie.map(s=>e.jsx("button",{type:"button",disabled:Q,onClick:()=>P(s),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${s===E?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${s} 页`,"aria-current":s===E?"page":void 0,children:s},s)),e.jsx("button",{type:"button",disabled:E>=p||Q,onClick:()=>P(s=>Math.min(p,s+1)),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"下一页",title:"下一页",children:e.jsx(_s,{className:"h-4 w-4"})})]})]})]})]}),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(rt,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[g.map(s=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle 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:["“",s.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:s.type==="image"&&s.image_url?s.image_url:s.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:()=>{Y({...s}),V(!0)},className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(_t,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>ut(s.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Qe,{className:"w-5 h-5"})})]})]},s.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(rt,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[z.map(s=>{const o=j[s.id],y=!!(o!=null&&o.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 ${y?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-surface-subtle 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 ${y?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(yt,{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:Qt(s)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${y?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:y?"已启用":"未启用"}),(o==null?void 0:o.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:y?o.reply_content||o.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 st(s.id),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(_t,{className:"w-4 h-4"})}),y&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>void ot(s.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 Ge(s.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Qe,{className:"w-5 h-5"})})]})]})]},s.id)}),z.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),Ee&&d&&qe.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:d.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:L.description})]}),e.jsx("button",{onClick:()=>ke(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(Me,{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:Vt.map(s=>{const o=at[s],y=o.icon,$=u===s;return e.jsx("button",{type:"button",onClick:()=>tt(s),className:`w-full rounded-2xl p-4 text-left border transition-all ${$?"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(y,{className:`w-5 h-5 mt-0.5 ${$?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:o.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${$?"text-gray-500":"text-gray-400"}`,children:o.description})]})]})},s)})}),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:L.flow.map((s,o)=>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:o+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:s})]},s))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-surface-subtle",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(ds,{className:"w-5 h-5 text-brand"}),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:d.name||"",onChange:s=>D({...d,name:s.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:d.cookie_id||"",onChange:s=>D({...d,cookie_id:s.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:"选择账号"}),G.map(s=>e.jsx("option",{value:s.id,children:Qt(s)},s.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:d.item_id||"",onChange:s=>kt(s.target.value),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),De.map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.item_id}`))]})]})]}),te&&u!=="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:te.item_title||te.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${je?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:je?"多规格商品":"普通商品"}),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:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),u!=="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(cl,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:u==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:je?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:Ct,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(et,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:Je.map((s,o)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${je?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[je&&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:s.spec_name,onChange:y=>We(o,{spec_name:y.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:s.spec_value,onChange:y=>We(o,{spec_value:y.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:s.card_id||"",onChange:y=>We(o,{card_id:Number(y.target.value)}),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),oe.filter(y=>y.enabled&&y.type!=="api").map(y=>e.jsx("option",{value:y.id,children:y.name},y.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:s.delivery_count,onChange:y=>We(o,{delivery_count:Math.max(1,Number(y.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:s.delay_override===!0,onChange:y=>We(o,{delay_override:y.target.checked}),className:"accent-brand"}),"覆盖卡密默认延时"]}),s.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:s.delay_seconds||0,onChange:y=>We(o,{delay_seconds:Math.max(0,Number(y.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:s.delay_override?`本动作延时 ${s.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:Je.length===1,onClick:()=>D({...d,variants:Je.filter((y,$)=>$!==o)}),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(Qe,{className:"w-4 h-4"})})]},s.id||o))})]}):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(va,{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(le.after_shipped_hours||72),onChange:s=>D({...d,config_json:ct(d.config_json,{after_shipped_hours:Math.max(1,Number(s.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(le.repeat_interval_hours||24),onChange:s=>D({...d,config_json:ct(d.config_json,{repeat_interval_hours:Math.max(1,Number(s.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(le.max_attempts||1),onChange:s=>D({...d,config_json:ct(d.config_json,{max_attempts:Math.max(1,Number(s.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:((Te=(H=d.actions)==null?void 0:H.find(s=>s.action_type==="send_text"))==null?void 0:Te.message_template)||"",onChange:s=>{var o;return D({...d,actions:((o=d.actions)!=null&&o.length?d.actions:Et("review_missing_timeout")).map(y=>y.action_type==="send_text"?{...y,message_template:s.target.value}:y)})},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:d.priority||100,onChange:s=>D({...d,priority:Number(s.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:d.enabled!==!1,onChange:s=>D({...d,enabled:s.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:()=>ke(!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:St,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),x&&S&&qe.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:S.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:()=>V(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:S.item_id||"",onChange:s=>Y({...S,item_id:s.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),q.filter(s=>!B||s.cookie_id===B).map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.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:S.type||"text",onChange:s=>{const o=s.target.value;Y({...S,type:o,reply_content:o==="text"?S.reply_content:"",image_url:o==="image"?S.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:S.keyword||"",onChange:s=>Y({...S,keyword:s.target.value}),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),S.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:S.image_url||"",onChange:s=>Y({...S,image_url:s.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:S.reply_content||"",onChange:s=>Y({...S,reply_content:s.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:()=>V(!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:pt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),X&&qe.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:()=>c(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(Me,{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:O.cookie_id,onChange:s=>de({...O,cookie_id:s.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),G.map(s=>e.jsx("option",{value:s.id,children:Qt(s)},s.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:()=>de({...O,enabled:!O.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${O.enabled?"bg-brand":"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 ${O.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:O.reply_content,onChange:s=>de({...O,reply_content:s.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:O.reply_image_url,onChange:s=>de({...O,reply_image_url:s.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:O.reply_once,onChange:s=>de({...O,reply_once:s.target.checked}),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",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:ht,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})},On=t=>{const a=String(t.smtp_from||"").trim(),l=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a);return{...t,smtp_from_name:t.smtp_from_name||(l?"":a),smtp_from_address:t.smtp_from_address||(l?a:t.smtp_user||""),smtp_use_tls:oa(t.smtp_use_tls,!0),smtp_use_ssl:oa(t.smtp_use_ssl,!1)}},oa=(t,a)=>{if(typeof t=="boolean")return t;if(typeof t=="string"){if(["true","1","yes","on"].includes(t.toLowerCase()))return!0;if(["false","0","no","off"].includes(t.toLowerCase()))return!1}return a},ks=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],fs=(t,a)=>{if(typeof t=="boolean")return t;if(typeof t=="string"){if(["true","1","yes","on"].includes(t.toLowerCase()))return!0;if(["false","0","no","off"].includes(t.toLowerCase()))return!1}return a},Da=t=>{const a=Object.prototype.hasOwnProperty.call(t,"use_custom_smtp"),l=ks.some(i=>String(t[i]??"").trim()!=="");return{...t,use_custom_smtp:a?fs(t.use_custom_smtp,!1):l}},ca=(t,a)=>{const l={...t,use_custom_smtp:!0};for(const i of ks)String(l[i]??"").trim()===""&&a[i]!==void 0&&(l[i]=a[i]);return l.smtp_port||(l.smtp_port=587),l.smtp_from_address||(l.smtp_from_address=l.smtp_user||""),l.smtp_use_tls=fs(l.smtp_use_tls,!0),l.smtp_use_ssl=fs(l.smtp_use_ssl,!1),l},In=t=>{const a=Da(t),l={to_email:String(a.to_email??"").trim(),use_custom_smtp:a.use_custom_smtp===!0};if(l.use_custom_smtp)for(const i of ks)l[i]=a[i];return l},ft={bark:{label:"Bark",icon:jt,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:"Ydisks闲鱼助手"},{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:Tt,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:Tt,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:Tt,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:dl,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:Zt,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:wa,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},Ta=[{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:"后台任务或系统级异常"}],An=t=>!t||t.length===0?"全部事件":t.map(l=>{var i;return((i=Ta.find(m=>m.value===l))==null?void 0:i.label)||l}).join("、"),$n=({isAdmin:t=!1})=>{const[a,l]=r.useState([]),[i,m]=r.useState(!0),[_,N]=r.useState(!1),[I,g]=r.useState(null),[C,j]=r.useState(!1),[F,G]=r.useState(""),[me,oe]=r.useState(null),[v,q]=r.useState({}),[ce,Q]=r.useState(!1),[ee,B]=r.useState(!1),[ge,ue]=r.useState(!1),[k,Z]=r.useState({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),se=async()=>{m(!0);try{const p=await Ra();l(p.data||[])}catch(p){console.error("加载通知渠道失败",p)}finally{m(!1)}},K=async()=>{try{const p=await Aa();q(On(p||{}))}catch(p){console.error("加载 SMTP 配置失败",p)}},ve=async()=>{Q(!0);try{await $a({smtp_server:v.smtp_server||"",smtp_port:v.smtp_port||587,smtp_user:v.smtp_user||"",smtp_password:v.smtp_password||"",smtp_from_name:v.smtp_from_name||"",smtp_from_address:v.smtp_from_address||v.smtp_user||"",smtp_use_tls:v.smtp_use_tls!==!1,smtp_use_ssl:v.smtp_use_ssl===!0}),J("success","SMTP 配置已保存")}catch(p){J("error",(p==null?void 0:p.message)||"保存失败")}finally{Q(!1)}};r.useEffect(()=>{se(),t?K():q({})},[t]);const J=(p,b)=>{oe({type:p,text:b}),window.setTimeout(()=>oe(null),3e3)},A=()=>{g(null),Z({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),ue(!1),N(!0)},E=p=>{g(p);const b=p.type==="email"?Da({...p.config||{}}):null,U=b?b.use_custom_smtp===!0?ca(b,v):b:{...p.config||{}};Z({name:p.name,type:p.type,enabled:p.enabled,config:U,event_types:p.event_types||[]}),ue(!1),N(!0)},P=async()=>{const p=ft[k.type];for(const U of p.fields)if(U.required&&!String(k.config[U.key]||"").trim()){J("error",`请填写 ${U.label}`);return}if(!k.name.trim()){J("error","请填写渠道名称");return}let b=k.config;if(k.type==="email"&&(b=In(k.config),b.use_custom_smtp)){const M=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([ne])=>!String(b[ne]||"").trim());if(M){J("error",`请填写 ${M[1]}`);return}}j(!0);try{const U={name:k.name.trim(),type:k.type,config:b,event_types:k.event_types,enabled:k.enabled};I?await Ys(I.id,U):await qr(U),N(!1),await se(),J("success",I?"已更新":"已创建")}catch(U){console.error("保存失败",U),J("error",(U==null?void 0:U.message)||"保存失败")}finally{j(!1)}},be=async p=>{if(confirm(`确认删除渠道「${p.name}」吗?已绑定该渠道的账号会自动解绑。`))try{await Fr(p.id),await se(),J("success","已删除")}catch(b){J("error",(b==null?void 0:b.message)||"删除失败")}},Re=async p=>{try{await Ys(p.id,{enabled:!p.enabled}),l(b=>b.map(U=>U.id===p.id?{...U,enabled:!U.enabled}:U))}catch(b){J("error",(b==null?void 0:b.message)||"切换失败")}},ae=async p=>{G(p.id);try{await zr(p.id),J("success","测试通知已发送,请检查对应渠道")}catch(b){J("error",(b==null?void 0:b.message)||"发送失败")}finally{G("")}},T=ft[k.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:se,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(ze,{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(et,{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(jt,{className:"w-5 h-5 text-brand 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:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),i?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Pe,{className:"w-8 h-8 text-brand animate-spin"})}):a.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(jt,{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:a.map(p=>{const b=ft[p.type]||ft.webhook,U=b.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(U,{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:p.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:b.label}),!p.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:b.fields.map(M=>{var ne;return(ne=p.config)==null?void 0:ne[M.key]}).filter(Boolean).map((M,ne)=>e.jsx("span",{className:"mr-3",children:String(M).length>40?String(M).slice(0,40)+"…":String(M)},ne))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",An(p.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:()=>Re(p),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${p.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:p.enabled?"启用中":"已停用"}),e.jsxs("button",{onClick:()=>ae(p),disabled:F===p.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[F===p.id?e.jsx(Pe,{className:"w-3 h-3 animate-spin"}):e.jsx(Zt,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{onClick:()=>E(p),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(_a,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>be(p),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(Qe,{className:"w-4 h-4"})})]})]},p.id)})}),t&&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(wa,{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:v.smtp_server||"",onChange:p=>q({...v,smtp_server:p.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:v.smtp_port||587,onChange:p=>q({...v,smtp_port:parseInt(p.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:v.smtp_user||"",onChange:p=>q({...v,smtp_user:p.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:ee?"text":"password",value:v.smtp_password||"",onChange:p=>q({...v,smtp_password:p.target.value}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>B(!ee),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:ee?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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:v.smtp_from_name||"",onChange:p=>q({...v,smtp_from_name:p.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:v.smtp_from_address||v.smtp_user||"",onChange:p=>q({...v,smtp_from_address:p.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:v.smtp_use_tls!==!1,onChange:p=>q({...v,smtp_use_tls:p.target.checked,smtp_use_ssl:p.target.checked?!1:v.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:v.smtp_use_ssl===!0,onChange:p=>q({...v,smtp_use_ssl:p.target.checked,smtp_use_tls:p.target.checked?!1:v.smtp_use_tls})}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:ve,disabled:ce,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[ce?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),ce?"保存中...":"保存 SMTP 配置"]})]}),_&&qe.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:I?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:()=>N(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Me,{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:k.name,onChange:p=>Z({...k,name:p.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(ft).map(p=>{const b=ft[p],U=b.icon,M=k.type===p;return e.jsxs("button",{type:"button",onClick:()=>Z({...k,type:p,config:{}}),className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${M?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(U,{className:`w-5 h-5 ${M?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${M?"text-brand":"text-gray-600"}`,children:b.label})]},p)})})]}),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(jt,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",T.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:T.guide.steps.map((p,b)=>e.jsx("li",{children:p},b))}),T.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:T.guide.urlFormat})]}),T.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",T.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:T.fields.map(p=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[p.label,p.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{type:p.type==="password"?"password":p.type==="number"?"number":"text",value:String(k.config[p.key]||""),onChange:b=>Z({...k,config:{...k.config,[p.key]:b.target.value}}),placeholder:p.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),p.help&&e.jsx("p",{className:"text-xs text-gray-500",children:p.help})]},p.key))}),k.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:k.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:()=>{const p=k.config.use_custom_smtp===!0;Z({...k,config:p?{...k.config,use_custom_smtp:!1}:ca(k.config,v)})},className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${k.config.use_custom_smtp===!0?"bg-brand":"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 ${k.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),k.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(k.config.smtp_server||""),onChange:p=>Z({...k,config:{...k.config,smtp_server:p.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(k.config.smtp_port||587),onChange:p=>Z({...k,config:{...k.config,smtp_port:p.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(k.config.smtp_user||""),onChange:p=>Z({...k,config:{...k.config,smtp_user:p.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:ge?"text":"password",value:String(k.config.smtp_password||""),onChange:p=>Z({...k,config:{...k.config,smtp_password:p.target.value}}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>ue(p=>!p),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:ge?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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(k.config.smtp_from_name||""),onChange:p=>Z({...k,config:{...k.config,smtp_from_name:p.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(k.config.smtp_from_address||""),onChange:p=>Z({...k,config:{...k.config,smtp_from_address:p.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:k.config.smtp_use_tls!==!1,onChange:p=>Z({...k,config:{...k.config,smtp_use_tls:p.target.checked,smtp_use_ssl:p.target.checked?!1:k.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:k.config.smtp_use_ssl===!0,onChange:p=>Z({...k,config:{...k.config,smtp_use_ssl:p.target.checked,smtp_use_tls:p.target.checked?!1:k.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:Ta.map(p=>{const b=k.event_types.includes(p.value);return e.jsxs("button",{type:"button",onClick:()=>{const U=b?k.event_types.filter(M=>M!==p.value):[...k.event_types,p.value];Z({...k,event_types:U})},className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${b?"border-brand 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 ${b?"bg-brand border-brand":"border-gray-300"}`,children:b&&e.jsx(Ke,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${b?"text-brand":"text-gray-800"}`,children:p.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:p.description})]},p.value)})})]}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:()=>Z({...k,enabled:!k.enabled}),className:`relative w-11 h-6 rounded-full transition-colors ${k.enabled?"bg-brand":"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 ${k.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:()=>N(!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:P,disabled:C,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[C?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),C?"保存中...":"保存"]})]})]})}),document.body),me&&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 text-white ${me.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[me.type==="success"?e.jsx(Ke,{className:"w-4 h-4"}):e.jsx(Me,{className:"w-4 h-4"}),me.text]})]})},Ma=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"],["流汗","https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"],["憨笑","https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"],["耶","https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"],["奋斗","https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"],["咒骂","https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"],["疑问","https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"],["嘘","https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"],["晕","https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"],["开心到模糊","https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"],["衰","https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"],["委屈","https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"],["再见","https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"],["鼓掌","https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"],["吐","https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"],["坏笑","https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"],["抠鼻","https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"],["叹气","https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"],["无聊","https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"],["思考","https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"],["呆","https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["哇哦","https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"],["飞吻","https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"],["好喜欢","https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"],["拜托","https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"],["真棒","https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"],["流鼻血","https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"],["费解","https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"],["秃头","https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"],["嘿哈","https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"],["吃土","https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"],["机智","https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"],["举杯","https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"],["握手","https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"],["挥手","https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"],["yeah","https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"],["666","https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"],["棒","https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"],["爱你","https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"],["比心","https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"],["感谢","https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"],["拍手","https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"],["拉钩","https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"],["没钱","https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"],["小刀","https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"],["不刀","https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"],["同出","https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"],["递钱","https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"],["数钱","https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"],["打call","https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"],["号外","https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"],["包邮","https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"],["求赞","https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"],["非主流","https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"],["吃瓜","https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"],["种草","https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"],["佛系","https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"],["超便宜","https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"],["拥抱","https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"],["摊手","https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"],["举手","https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"],["蹲","https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"],["跪了","https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"],["拜","https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"],["排","https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"],["旺财","https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"],["招财猫","https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"],["酸了","https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"],["鸭鸭","https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"],["方了","https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"],["白菜","https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"],["桃子","https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"],["打包","https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"],["沙发","https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["南","https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"],["盯","https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"],["hot","https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"],["new","https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"],["cool","https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"],["1","https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"],["可","https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"],["搬砖","https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"],["菜狗","https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"],["开心面具","https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"],["快递","https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["裂开","https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"],["啤酒","https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"],["瑞思拜","https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"],["小丑","https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"],["爱心","https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"]],Pn=t=>t,Rn=new Map(Ma.map(([t,a])=>[t,a])),da=t=>t.split(/(\[[^\]]+\])/g).map((a,l)=>{const i=a.startsWith("[")?Rn.get(a.slice(1,-1)):void 0;return i?e.jsx("img",{src:i,alt:a,title:a,className:"mx-0.5 inline-block h-7 w-7 align-middle"},l):e.jsx(ys.Fragment,{children:a},l)}),xa="ydisks.chat.account.v1",En=t=>{if(!t)return"";const a=new Date(t<1e10?t*1e3:t),l=new Date;return a.toDateString()===l.toDateString()?a.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):a.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},ma=t=>new Date(t<1e10?t*1e3:t).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),Dn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState(""),[m,_]=r.useState({}),[N,I]=r.useState(""),[g,C]=r.useState([]),[j,F]=r.useState(""),[G,me]=r.useState(!1),[oe,v]=r.useState(""),[q,ce]=r.useState(!0),[Q,ee]=r.useState(!1),[B,ge]=r.useState(!1),[ue,k]=r.useState(!1),[Z,se]=r.useState(),[K,ve]=r.useState({}),[J,A]=r.useState({}),[E,P]=r.useState(!1),[be,Re]=r.useState(!1),[ae,T]=r.useState(!1),[p,b]=r.useState(""),[U,M]=r.useState("connecting"),ne=r.useRef(""),he=r.useRef(""),ye=r.useRef(null),Ee=r.useRef({accountID:"",chatID:""}),ke=r.useRef(!0),x=r.useRef(!1),V=r.useRef(null),X=r.useRef(new Set);r.useEffect(()=>{ne.current=l},[l]),r.useEffect(()=>{he.current=N},[N]);const c=async h=>{const f=await as(h,void 0,void 0,!0);return _(R=>({...R,[h]:f.sessions})),ve(R=>({...R,[h]:f.next_cursor})),A(R=>({...R,[h]:f.has_more})),f.sessions};r.useEffect(()=>{let h=!1;return(async()=>{var R;ce(!0);try{const[z,Ie]=await Promise.all([Ft(),hs()]),we=z.map(u=>{var L,le;return{...u,runtime_state:((L=Ie[u.id])==null?void 0:L.state)||(u.enabled?"connecting":"disabled"),runtime_connected:((le=Ie[u.id])==null?void 0:le.connected)===!0}}).filter(u=>u.enabled),De=await Promise.all(we.map(async u=>[u.id,await as(u.id)]));if(h)return;a(we),_(Object.fromEntries(De.map(([u,L])=>[u,L.sessions]))),ve(Object.fromEntries(De.map(([u,L])=>[u,L.next_cursor]))),A(Object.fromEntries(De.map(([u,L])=>[u,L.has_more])));const te=window.localStorage.getItem(xa)||"",je=we.some(u=>u.id===te)?te:((R=we[0])==null?void 0:R.id)||"";i(je)}catch(z){h||b(z instanceof Error?z.message:"加载聊天数据失败")}finally{h||ce(!1)}})(),()=>{h=!0}},[]),r.useEffect(()=>{let h=!1,f=0,R=null;const z=async()=>{R=new AbortController;try{const Ie=await hs({signal:R.signal,timeoutMs:1e4});h||a(Ae=>Ae.map(we=>{var De,te;return{...we,runtime_state:((De=Ie[we.id])==null?void 0:De.state)||we.runtime_state,runtime_connected:((te=Ie[we.id])==null?void 0:te.connected)??we.runtime_connected}}))}catch{}finally{h||(f=window.setTimeout(z,3e3))}};return f=window.setTimeout(z,3e3),()=>{h=!0,window.clearTimeout(f),R==null||R.abort()}},[]),r.useEffect(()=>{if(!l)return;window.localStorage.setItem(xa,l);const h=m[l]||[];I(f=>{var R;return h.some(z=>z.chat_id===f)?f:((R=h[0])==null?void 0:R.chat_id)||""})},[l,m]),r.useEffect(()=>{!l||X.current.has(l)||(X.current.add(l),c(l).catch(h=>{b(h instanceof Error?h.message:"同步会话失败")}))},[l]),r.useEffect(()=>{if(!l||!N){C([]);return}const h=new AbortController;return ee(!0),Promise.all([us(l,N,void 0,void 0,{signal:h.signal}),Qs(l,N)]).then(([f])=>{C(f.messages),k(f.has_more),se(f.next_cursor),f.session&&_(R=>({...R,[l]:(R[l]||[]).map(z=>{var Ie;return z.chat_id===((Ie=f.session)==null?void 0:Ie.chat_id)?f.session:z})})),_(R=>({...R,[l]:(R[l]||[]).map(z=>z.chat_id===N?{...z,unread_count:0}:z)}))}).catch(f=>{h.signal.aborted||b(f instanceof Error?f.message:"加载消息失败")}).finally(()=>{h.signal.aborted||ee(!1)}),()=>h.abort()},[l,N]);const d=async()=>{var R;if(!l||!N||B||!ue)return;const h=ye.current,f=(h==null?void 0:h.scrollHeight)||0;x.current=!0,ge(!0),b("");try{const z=(R=g[0])==null?void 0:R.id,Ie=await us(l,N,Z,z);C(Ae=>{const we=new Set(Ae.map(De=>De.message_key));return[...Ie.messages.filter(De=>!we.has(De.message_key)),...Ae]}),k(Ie.has_more),se(Ie.next_cursor),requestAnimationFrame(()=>{h&&(h.scrollTop+=h.scrollHeight-f)})}catch(z){x.current=!1,b(z instanceof Error?z.message:"加载历史消息失败")}finally{ge(!1)}};r.useEffect(()=>{let h=!1,f=0,R=0,z=null;const Ie=()=>{if(h)return;M("connecting");const Ae=window.location.protocol==="https:"?"wss:":"ws:";z=new WebSocket(`${Ae}//${window.location.host}/api/chat/ws`),z.onopen=()=>{R=0,M("online")},z.onmessage=we=>{try{const te=JSON.parse(we.data).message;if(!te)return;const je=te.account_id;_(u=>{const L=u[je]||[];return L.some(_e=>_e.chat_id===te.chat_id)?{...u,[je]:L.map(_e=>_e.chat_id===te.chat_id?{..._e,last_message:te.content,last_message_at:te.sent_at,unread_count:te.direction==="incoming"&&(ne.current!==je||he.current!==te.chat_id)?_e.unread_count+1:_e.unread_count}:_e).sort((_e,Ue)=>Ue.last_message_at-_e.last_message_at)}:(c(je),u)}),ne.current===je&&he.current===te.chat_id&&(C(u=>{const L=u.findIndex(le=>le.message_key===te.message_key);return L>=0?u.map((le,_e)=>_e===L?te:le):[...u,te]}),te.direction==="incoming"&&Qs(je,te.chat_id))}catch{}},z.onclose=()=>{if(h)return;M("offline");const we=Math.min(15e3,1e3*2**Math.min(R++,4));f=window.setTimeout(Ie,we)},z.onerror=()=>z==null?void 0:z.close()};return Ie(),()=>{h=!0,window.clearTimeout(f),z==null||z.close()}},[]);const D=()=>{const h=ye.current;if(!h)return;const f=h.scrollHeight-h.scrollTop-h.clientHeight;ke.current=f<=48};r.useLayoutEffect(()=>{const h=Ee.current.accountID!==l||Ee.current.chatID!==N;Ee.current={accountID:l,chatID:N},h&&(ke.current=!0);const f=ye.current;if(f){if(x.current){x.current=!1;return}(Q||ke.current)&&(f.scrollTop=f.scrollHeight)}},[l,N,g,Q]);const S=t.find(h=>h.id===l),Y=m[l]||[],O=Y.find(h=>h.chat_id===N),de=r.useMemo(()=>{const h=j.trim().toLowerCase();return Y.filter(f=>G&&f.unread_count<=0?!1:h?[f.buyer_name,f.buyer_id,f.item_title,f.last_message].some(R=>(R||"").toLowerCase().includes(h)):!0)},[Y,j,G]),Se=h=>(m[h]||[]).reduce((f,R)=>f+R.unread_count,0),fe=async()=>{if(!(!l||E||!J[l])){P(!0),b("");try{const h=await as(l,K[l],void 0,!0);_(f=>({...f,[l]:h.sessions})),ve(f=>({...f,[l]:h.next_cursor})),A(f=>({...f,[l]:h.has_more}))}catch(h){b(h instanceof Error?h.message:"加载历史联系人失败")}finally{P(!1)}}},Oe=async()=>{const h=oe.trim();if(!(!h||!O||!l||ae)){T(!0),b("");try{const f=await Tl({account_id:l,chat_id:O.chat_id,buyer_id:O.buyer_id,buyer_name:O.buyer_name,item_id:O.item_id,item_title:O.item_title,text:h});v(""),C(R=>R.some(z=>z.message_key===f.message.message_key)?R.map(z=>z.message_key===f.message.message_key?f.message:z):[...R,f.message])}catch(f){b(f instanceof Error?f.message:"消息发送失败"),Dl(l,O.chat_id).then(C)}finally{T(!1)}}},re=async h=>{if(!(!h||!O||!l||ae)){T(!0),b("");try{const f=await Ml({account_id:l,chat_id:O.chat_id,buyer_id:O.buyer_id,buyer_name:O.buyer_name,buyer_avatar_url:O.buyer_avatar_url,item_id:O.item_id,item_title:O.item_title,image:h});C(R=>R.some(z=>z.message_key===f.message.message_key)?R.map(z=>z.message_key===f.message.message_key?f.message:z):[...R,f.message])}catch(f){b(f instanceof Error?f.message:"图片发送失败")}finally{T(!1),V.current&&(V.current.value="")}}};return q?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(Pe,{className:"h-8 w-8 animate-spin text-sky-500"})}):e.jsxs("section",{className:"flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat",children:[e.jsxs("header",{className:"border-b border-slate-200 bg-slate-50/70 px-5 pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-black tracking-tight text-slate-950",children:"在线聊天"}),e.jsx("p",{className:"mt-0.5 text-xs font-medium text-slate-500",children:"复用账号实时连接,消息按账号完全隔离"})]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${U==="online"?"bg-emerald-50 text-emerald-700":U==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[U==="online"?e.jsx(xl,{className:"h-3.5 w-3.5"}):e.jsx(ml,{className:"h-3.5 w-3.5"}),U==="online"?"实时同步中":U==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:t.map(h=>{const f=h.id===l,R=Se(h.id),z=h.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":f,onClick:()=>i(h.id),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${f?"border-sky-500 text-sky-700":"border-transparent text-slate-500 hover:text-slate-900"}`,children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${z?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:h.nickname||h.remark||h.id}),R>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:R>99?"99+":R})]},h.id)})})]}),t.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(is,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-800",children:"暂无启用账号"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"先在账号管理中启用账号,聊天会话会自动出现。"})]}):e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40",children:[e.jsxs("div",{className:"space-y-3 border-b border-slate-200 p-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Nt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:j,onChange:h=>F(h.target.value),placeholder:"搜索用户、商品或消息",className:"h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:()=>me(h=>!h),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${G?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:G?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:()=>void c(l),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(ze,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[de.map(h=>e.jsxs("button",{type:"button",onClick:()=>I(h.chat_id),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${h.chat_id===N?"bg-white shadow-chat-active":"hover:bg-white/80"}`,children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500",children:h.buyer_avatar_url?e.jsx("img",{src:h.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(Gt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-extrabold text-slate-900",children:h.buyer_name||`用户 ${h.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:En(h.last_message_at)})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs text-slate-500",children:h.last_message||"暂无消息"}),h.unread_count>0&&e.jsx("span",{className:"ml-auto min-w-5 shrink-0 rounded-full bg-red-500 px-1.5 py-0.5 text-center text-[10px] font-bold text-white",children:h.unread_count})]}),h.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",h.item_title]})]})]},h.chat_id)),de.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),J[l]&&!j&&!G&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:()=>void fe(),disabled:E,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[E&&e.jsx(Pe,{className:"h-3.5 w-3.5 animate-spin"}),E?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:O?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-black text-slate-950",children:O.buyer_name||O.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",O.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(S==null?void 0:S.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(S==null?void 0:S.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:ye,onScroll:D,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:Q?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Pe,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[ue&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:()=>void d(),disabled:B,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[B&&e.jsx(Pe,{className:"h-3.5 w-3.5 animate-spin"}),B?"正在加载":"加载更早消息"]})}),g.map(h=>{const f=h.direction==="outgoing";return h.message_type==="system"?e.jsx("div",{className:"flex justify-center py-1",children:e.jsxs("div",{className:"max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500",children:[da(h.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:ma(h.sent_at)})]})},h.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${f?"justify-end":"justify-start"}`,children:[!f&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:O.buyer_avatar_url?e.jsx("img",{src:O.buyer_avatar_url,alt:O.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(Gt,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${f?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:f?(S==null?void 0:S.nickname)||(S==null?void 0:S.remark)||"我":O.buyer_name||h.sender_name||O.buyer_id}),h.message_type==="image"?e.jsx("a",{href:h.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${f?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:h.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):h.message_type==="video"?e.jsx("video",{src:h.content,controls:!0,preload:"metadata",className:"max-h-80 max-w-full rounded-2xl bg-black"}):e.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${f?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:da(h.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[ma(h.sent_at),f&&(h.status==="failed"?e.jsx(rt,{className:"h-3 w-3 text-red-500"}):h.status==="sent"?e.jsx(pl,{className:"h-3 w-3 text-sky-500"}):e.jsx(Ke,{className:"h-3 w-3"}))]})]}),f&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:S!=null&&S.avatar_url?e.jsx("img",{src:S.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(Gt,{className:"m-2 h-5 w-5 text-sky-600"})})]},h.message_key)})]})}),p&&e.jsx("div",{className:"border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:p}),e.jsxs("div",{className:"relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>Re(h=>!h),disabled:ae||(S==null?void 0:S.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"闲鱼表情",children:e.jsx(ul,{className:"h-5 w-5"})}),be&&e.jsxs("div",{className:"absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl",children:[e.jsx("div",{className:"mb-2 text-xs font-bold text-slate-500",children:"全部表情"}),e.jsx("div",{className:"grid max-h-72 grid-cols-8 gap-1 overflow-y-auto",children:Ma.map(([h,f])=>e.jsx("button",{type:"button",title:`[${h}]`,onClick:()=>{v(R=>R+`[${h}]`),Re(!1)},className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:Pn(f),alt:`[${h}]`,className:"h-8 w-8 object-contain"})},h))})]})]}),e.jsx("input",{ref:V,type:"file",accept:"image/*",className:"hidden",onChange:h=>{var f;return void re((f=h.target.files)==null?void 0:f[0])}}),e.jsx("button",{type:"button",onClick:()=>{var h;return(h=V.current)==null?void 0:h.click()},disabled:ae||(S==null?void 0:S.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"发送图片(最大 10MB)",children:e.jsx(hl,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100",children:[e.jsx("textarea",{value:oe,onChange:h=>v(h.target.value),rows:2,maxLength:2e3,onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),Oe())},disabled:(S==null?void 0:S.runtime_state)!=="online",placeholder:(S==null?void 0:S.runtime_state)==="online"?"输入消息,Enter 发送,Shift + Enter 换行":"账号离线,暂时无法发送",className:"max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed"}),e.jsx("button",{type:"button",onClick:()=>void Oe(),disabled:!oe.trim()||ae||(S==null?void 0:S.runtime_state)!=="online",className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none","aria-label":"发送消息",children:ae?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(Zt,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(is,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-700",children:"选择一个用户开始聊天"}),e.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})},qa="ydisks.sidebar.v1",Tn=()=>{try{return window.localStorage.getItem(qa)==="collapsed"}catch{return!1}},Mn=t=>{try{window.localStorage.setItem(qa,t?"collapsed":"expanded")}catch{}},Fa={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/chat":"chat","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},pa=Object.fromEntries(Object.entries(Fa).map(([t,a])=>[a,t])),ua=()=>Fa[window.location.pathname]||"dashboard",qn=()=>{const[t,a]=r.useState(!1),[l,i]=r.useState(!1),[m,_]=r.useState(ua),[N,I]=r.useState(!0),[g,C]=r.useState(!1),[j,F]=r.useState(""),[G,me]=r.useState(""),[oe,v]=r.useState(!1),[q,ce]=r.useState(""),[Q,ee]=r.useState(""),[B,ge]=r.useState(""),[ue,k]=r.useState(!1),[Z,se]=r.useState(""),[K,ve]=r.useState(),[J,A]=r.useState(Tn),E=T=>{const p=T==="settings"&&!l?"dashboard":T,b=pa[p];b&&b!==window.location.pathname&&window.history.pushState({},"",b),_(p)};r.useEffect(()=>{const T=()=>_(ua());return window.addEventListener("popstate",T),()=>window.removeEventListener("popstate",T)},[]),r.useEffect(()=>{Sa().then(p=>{if((p==null?void 0:p.initialized)===!1){C(!0),a(!1),i(!1);return}C(!1),p!=null&&p.authenticated?(a(!0),i(p.is_admin===!0)):i(!1)}).catch(()=>{a(!1),i(!1)}).finally(()=>I(!1));const T=()=>{a(!1),i(!1)};return window.addEventListener("auth:logout",T),()=>window.removeEventListener("auth:logout",T)},[]),r.useEffect(()=>{!N&&t&&!l&&m==="settings"&&(window.history.replaceState({},"",pa.dashboard),_("dashboard"))},[N,t,l,m]);const P=async T=>{T.preventDefault(),v(!0),ce("");try{const p=await Ol({username:j,password:G});p.success?(a(!0),i(p.is_admin===!0)):ce(p.message||"登录失败")}catch(p){const b=p instanceof Error?p.message:String(p);ce(b||"登录失败")}finally{v(!1)}},be=async T=>{if(T.preventDefault(),se(""),Q.length<8){se("密码至少需要 8 个字符");return}if(Q!==B){se("两次输入的密码不一致");return}k(!0);try{const p=await Il(Q);if(!p.success){se(p.message||"初始化失败,请重试");return}C(!1),a(!0),i(p.is_admin===!0),ee(""),ge("")}catch(p){const b=p instanceof Error?p.message:String(p);se(b||"初始化失败,请重试")}finally{k(!1)}},Re=async()=>{try{await Al()}catch(T){console.error("退出登录失败",T)}finally{a(!1),i(!1)}};if(N)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface",children:e.jsx(Pe,{className:"w-8 h-8 text-brand animate-spin"})});if(g)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas 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-panel 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(ms,{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:"设置完成后会自动进入系统,管理员账号为 admin。"})]}),e.jsxs("form",{onSubmit:be,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(Fs,{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:"设置管理员密码(至少 8 个字符)",value:Q,onChange:T=>ee(T.target.value),autoFocus:!0,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(Mt,{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:B,onChange:T=>ge(T.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),Z&&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(Mt,{className:"w-4 h-4"})," ",Z]}),e.jsx("button",{type:"submit",disabled:ue,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:ue?e.jsx(Pe,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["设置密码并进入系统 ",e.jsx(xs,{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(!t)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas 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-panel 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(ms,{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:P,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(xt,{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:T=>F(T.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(Fs,{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:G,onChange:T=>me(T.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),q&&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(Mt,{className:"w-4 h-4"})," ",q]}),e.jsx("button",{type:"submit",disabled:oe,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:oe?e.jsx(Pe,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["立即登录 ",e.jsx(xs,{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 ae=()=>{switch(m){case"dashboard":return e.jsx(rs,{});case"accounts":return e.jsx(an,{});case"chat":return e.jsx(Dn,{});case"orders":return e.jsx(nn,{});case"cards":return e.jsx(cn,{});case"items":return e.jsx(bn,{onConfigureDelivery:T=>{ve({cookieId:T.cookie_id,itemId:T.item_id,requestId:Date.now()}),E("rules")}});case"rules":return e.jsx(Ln,{initialDeliveryTarget:K,onDeliveryTargetHandled:()=>ve(void 0)});case"notifications":return e.jsx($n,{isAdmin:l});case"settings":return l?e.jsx(jn,{}):e.jsx(rs,{});default:return e.jsx(rs,{})}};return e.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[e.jsx(vl,{activeTab:m,isAdmin:l,collapsed:J,onToggleCollapsed:()=>A(T=>{const p=!T;return Mn(p),p}),onNavigate:E,onLogout:Re}),e.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${J?"ml-16":"ml-64"} ${m==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,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:`${m==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:ae()})]})]})},Ba=document.getElementById("root");if(!Ba)throw new Error("Could not find root element to mount to");const Fn=Ua.createRoot(Ba);Fn.render(e.jsx(ys.StrictMode,{children:e.jsx(qn,{})})); diff --git a/internal/webui/static/assets/index-DxxeH3eR.js b/internal/webui/static/assets/index-DxxeH3eR.js new file mode 100644 index 0000000..9b09678 --- /dev/null +++ b/internal/webui/static/assets/index-DxxeH3eR.js @@ -0,0 +1,19 @@ +import{j as e,r,c as ys,b as qe,d as Ja}from"./react-vendor-C_od1ZSF.js";import{L as Va,U as ba,M as is,C as os,B as fa,S as ya,Z as cs,a as jt,b as js,G as As,c as _s,d as Ns,e as Qa,f as rt,A as $s,D as Ga,g as Rs,P as ja,h as qt,E as _a,T as Ka,i as Ha,j as Re,X as Me,k as Za,l as Ya,m as vs,n as Na,o as He,Q as Xt,p as xt,q as Qe,r as yt,s as Tt,t as Ps,R as ze,u as va,v as Xa,w as Ge,K as el,x as dt,y as lt,z as et,F as Es,H as Nt,I as _t,J as Dt,N as wa,O as tl,V as Ds,W as Ts,Y as sl,_ as al,$ as ll,a0 as rl,a1 as es,a2 as Bt,a3 as ds,a4 as nl,a5 as il,a6 as xs,a7 as Ms,a8 as ol,a9 as cl,aa as Mt,ab as qs,ac as Gt,ad as ka,ae as dl,af as xl,ag as Zt,ah as Ca,ai as ml,aj as pl,ak as ul,al as hl,am as gl,an as bl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as fl,X as Bs,Y as zs,T as Ut,a as yl,C as ts,A as jl,b as _l,c as Nl,P as Us,d as Ws,L as vl}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const N of m)if(N.type==="childList")for(const _ of N.addedNodes)_.tagName==="LINK"&&_.rel==="modulepreload"&&i(_)}).observe(document,{childList:!0,subtree:!0});function l(m){const N={};return m.integrity&&(N.integrity=m.integrity),m.referrerPolicy&&(N.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?N.credentials="include":m.crossOrigin==="anonymous"?N.credentials="omit":N.credentials="same-origin",N}function i(m){if(m.ep)return;m.ep=!0;const N=l(m);fetch(m.href,N)}})();const wl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,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"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="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 ${t} 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:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),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(wl,{className:a})})]})]}),kl=({activeTab:t,isAdmin:a=!1,collapsed:l,onToggleCollapsed:i,onNavigate:m,onLogout:N})=>{const[_,I]=r.useState({version:"dev",commit:"unknown"});r.useEffect(()=>{const j=new AbortController;return fetch("/health",{signal:j.signal}).then(B=>B.ok?B.json():Promise.reject(new Error("health request failed"))).then(B=>I({version:String(B.version||"dev"),commit:String(B.commit||"unknown")})).catch(B=>{B instanceof DOMException&&B.name}),()=>j.abort()},[]);const g=[{id:"dashboard",icon:Va,label:"仪表盘"},{id:"accounts",icon:ba,label:"账号管理"},{id:"chat",icon:is,label:"在线聊天"},{id:"cards",icon:os,label:"卡密库存"},{id:"items",icon:fa,label:"商品列表"},{id:"orders",icon:ya,label:"订单管理"},{id:"rules",icon:cs,label:"自动化规则"},{id:"notifications",icon:jt,label:"通知设置"},...a?[{id:"settings",icon:js,label:"系统与AI"}]:[]],C=/^\d+\.\d+\.\d+$/.test(_.version)?`v${_.version}`:_.version;return e.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${l?"w-16":"w-64"}`,children:[e.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${l?"justify-center px-2":"gap-3 px-5"}`,children:[e.jsx(ms,{sizeClass:"h-10 w-10"}),!l&&e.jsxs("div",{className:"min-w-0 leading-tight",children:[e.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),e.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),e.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${l?"px-2":"px-3"}`,"aria-label":"主导航",children:g.map(j=>{const B=j.icon,K=t===j.id;return e.jsx(ys.Fragment,{children:e.jsxs("button",{type:"button",title:l?j.label:void 0,"aria-label":j.label,"aria-current":K?"page":void 0,onClick:()=>m(j.id),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${l?"justify-center":"gap-3 px-3.5"} ${K?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(B,{className:`h-[19px] w-[19px] shrink-0 ${K?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!l&&e.jsx("span",{className:"truncate text-sm font-bold",children:j.label}),K&&!l&&e.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},j.id)})}),e.jsxs("div",{children:[e.jsx("div",{title:l?`版本 ${_.version} · ${_.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${l?"flex justify-center px-1":"px-6"}`,children:l?e.jsx(As,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${_.version}`}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[e.jsx(As,{className:"h-3.5 w-3.5"}),"运行版本"]}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[e.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:C}),e.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:_.commit})]})]})}),e.jsxs("div",{className:`space-y-2 p-2 ${l?"":"p-3"}`,children:[e.jsxs("button",{type:"button",onClick:i,title:l?"展开侧边栏":"收起侧边栏","aria-label":l?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${l?"justify-center":"gap-3 px-3"}`,children:[l?e.jsx(_s,{className:"h-5 w-5"}):e.jsx(Ns,{className:"h-5 w-5"}),!l&&e.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),e.jsxs("button",{type:"button",onClick:N,title:l?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${l?"justify-center":"gap-3 px-3"}`,children:[e.jsx(Qa,{className:"h-5 w-5"}),!l&&e.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},Cl=3e4,Sl=10*6e4;let ss=!1;const Sa=()=>{ss||typeof window>"u"||(ss=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{ss=!1}))},Ll=t=>{if(!t)return"";const a=new URLSearchParams;for(const[i,m]of Object.entries(t))m!=null&&a.set(i,String(m));const l=a.toString();return l?`?${l}`:""},Yt=async(t,a,l={})=>{var C;const i=Ll(l.params),m=`${a}${i}`,N=La(l.signal,l.timeoutMs??Cl);let _;try{_=await fetch(m,{method:t,credentials:"include",signal:N.signal,headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)})}catch(j){throw N.signal.aborted?new Error((C=l.signal)!=null&&C.aborted?"请求已取消":"请求超时,请稍后重试"):j}finally{N.cleanup()}const g=(_.headers.get("content-type")||"").includes("application/json");if(!_.ok){_.status===401&&!l.skipAuthLogout&&Sa();const j=g?await _.json().catch(()=>{}):await _.text().catch(()=>{}),B=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(B||`请求失败: ${_.status}`)}return g?await _.json():await _.text()},Ie=async(t,a,l)=>Yt("GET",t,{params:a,...l}),Le=async(t,a,l)=>Yt("POST",t,{body:a,...l}),Be=async(t,a,l)=>Yt("PUT",t,{body:a,...l}),Ze=async(t,a,l)=>Yt("DELETE",t,{params:a,...l}),wt=async(t,a,l={})=>{var g;const i=La(l.signal,l.timeoutMs??Sl);let m;try{m=await fetch(t,{method:"POST",credentials:"include",signal:i.signal,body:a})}catch(C){throw i.signal.aborted?new Error((g=l.signal)!=null&&g.aborted?"请求已取消":"上传超时,请稍后重试"):C}finally{i.cleanup()}const I=(m.headers.get("content-type")||"").includes("application/json")?await m.json().catch(()=>{}):await m.text().catch(()=>{});if(!m.ok){m.status===401&&Sa();const C=typeof I=="string"?I:(I==null?void 0:I.detail)||(I==null?void 0:I.message)||(I==null?void 0:I.msg),j=new Error(C||"请求失败: "+m.status);throw j.payload=I,j}return I},La=(t,a)=>{const l=new AbortController,i=()=>l.abort(t==null?void 0:t.reason);t!=null&&t.aborted?i():t==null||t.addEventListener("abort",i,{once:!0});const m=globalThis.setTimeout(()=>l.abort(new DOMException("timeout","TimeoutError")),Math.max(1,a));return{signal:l.signal,cleanup:()=>{globalThis.clearTimeout(m),t==null||t.removeEventListener("abort",i)}}},Kt=t=>{const a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${a}-${l}-${i}`},ws=(t,a)=>{const l=new Date(t);return l.setHours(12,0,0,0),l.setDate(l.getDate()+a),l},ps=(t,a)=>({startDate:Kt(ws(t,-(a-1))),endDate:Kt(t)}),Js=(t,a=new Date,l="",i="")=>{if(t==="custom"&&l&&i){if(l>i)throw new Error("开始日期不能晚于结束日期");return{startDate:l,endDate:i}}return t==="yesterday"?ps(ws(a,-1),1):ps(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Ol=t=>{const a=new Date(`${t.startDate}T12:00:00`),l=new Date(`${t.endDate}T12:00:00`),i=Math.round((l.getTime()-a.getTime())/864e5)+1,m=ws(a,-1);return ps(m,i)},Il=t=>{const a={...t};if("renewal_log_retention_days"in a){const l=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(l)?l:10}return a},Al=async t=>Le("/login",t,{skipAuthLogout:!0}),$l=async t=>Le("/initialize",{password:t},{skipAuthLogout:!0}),Oa=async()=>Ie("/verify"),Rl=async()=>Le("/logout",{}),Pl=async t=>Be("/account/credentials",t),El=(t,a)=>{const l=t.avatar_url||"";if(!l)return"";try{const i=new URL(l,window.location.origin);return i.hostname.endsWith("alicdn.com")&&i.searchParams.set("_v",a),i.toString()}catch{return l}},Ft=async t=>{const a=await Ie("/cookies/details",void 0,t),l=Date.now().toString();return a.map(i=>({id:i.id,value:"",cookie:"",enabled:i.enabled,auto_confirm:i.auto_confirm,remark:i.remark,note:i.remark,pause_duration:i.pause_duration,paused_until:Number(i.paused_until||0),paused:i.paused===!0,username:i.username||"",login_password:"",show_browser:i.show_browser===!0||i.show_browser===1||i.show_browser==="1"||i.show_browser==="true",nickname:i.nickname||i.remark||`账号 ${i.id.substring(0,6)}`,avatar_url:El(i,l),profile_error:i.profile_error||"",ai_enabled:!1,auto_rate_enabled:i.auto_rate_enabled===!0||i.auto_rate_enabled===1,rate_content:i.rate_content||"不错的买家,交易愉快",auto_polish_enabled:i.auto_polish_enabled===!0||i.auto_polish_enabled===1,polish_time:i.polish_time||"03:00",last_rate_scan_at:Number(i.last_rate_scan_at||0),last_polish_date:i.last_polish_date||"",last_polish_at:Number(i.last_polish_at||0)}))},Dl=async t=>Ie(`/api/account-tasks/${t}`),Vs=async(t,a)=>Be(`/api/account-tasks/${t}`,a),Tl=async(t,a)=>Le(`/api/account-tasks/${t}/run`,{task_type:a},{timeoutMs:12e4}),as=async(t,a,l,i=!1)=>{const m=await Ie("/api/chat/sessions",{account_id:t,cursor:a,refresh:i?1:void 0},i?{timeoutMs:6e4,...l}:l);return{sessions:m.sessions||[],has_more:m.has_more===!0,next_cursor:m.next_cursor}},us=async(t,a,l,i,m)=>{const N=await Ie("/api/chat/messages",{account_id:t,chat_id:a,cursor:l,before_id:i},m);return{messages:N.messages||[],has_more:N.has_more===!0,next_cursor:N.next_cursor,session:N.session}},Ml=async(t,a,l,i)=>(await us(t,a,void 0,l,i)).messages,ql=async t=>Le("/api/chat/messages",t),Fl=async t=>{const a=new FormData;return Object.entries(t).forEach(([l,i])=>a.append(l,i)),wt("/api/chat/images",a,{timeoutMs:12e4})},Qs=async(t,a,l=[])=>Le("/api/chat/read",{account_id:t,chat_id:a,message_ids:l}),hs=async t=>Ie("/cookies/runtime-status",void 0,t),Bl=async t=>Le("/qr-login/generate",void 0,{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),zl=async(t,a)=>Ie(`/qr-login/check/${t}`,void 0,{signal:a,timeoutMs:1e4}),Ul=async(t,a)=>Le(`/qr-login/complete-verification/${t}`,{target_account_id:a||""}),Wl=async(t,a)=>Be(`/cookies/${t}/status`,{enabled:a}),Jl=async t=>Ze(`/cookies/${t}`),Vl=async(t,a)=>Be(`/cookies/${t}/pause-duration`,{pause_duration:a}),Ql=async(t,a)=>Be(`/cookies/${t}/settings`,a),Gl=async t=>Ie(`/cookies/${t}/long-login`),Kl=async(t,a)=>Be(`/cookies/${t}/long-login`,{enabled:a}),Hl=async t=>Le("/password-login",t),Zl=async(t,a)=>Ie(`/password-login/check/${t}`,void 0,{signal:a,timeoutMs:1e4}),Yl=async t=>Ze(`/password-login/cancel/${t}`),Xl=async t=>Le(`/cookies/${t}/refresh-profile`,{}),er=async t=>Ie("/ai-reply-settings",void 0,t),Ia=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},tr=async(t,a,l=1,i=20,m)=>{const N={page:l,page_size:i};t&&(N.cookie_id=t),a&&a!=="all"&&(N.status=a),m!=null&&m.trim()&&(N.search=m.trim());const _=await Ie("/api/orders",N),g=(_.orders||_.data||[]).map(C=>({...C,id:C.id||C.order_id,status:Ia(C.status||C.order_status),quantity:Number(C.quantity||1)}));return{success:!0,data:g,total:_.total||g.length,page:_.page||l,page_size:_.page_size||i,total_pages:_.total_pages||1}},sr=async(t,a)=>Be(`/api/orders/${t}`,a),ar=async t=>Ze(`/api/orders/${t}`),lr=async(t,a)=>{const l=new FormData;return t&&l.append("cookie_id",t),a&&l.append("status",a),wt("/api/orders/refresh",l)},rr=async t=>Le(`/api/orders/${t}/refresh`),nr=async(t,a)=>Le("/api/orders/manual-ship",{order_ids:t,ship_mode:a}),ir=async t=>t instanceof FormData?wt("/api/orders/import",t):Le("/api/orders/import",t),or=async()=>Ie("/dashboard/stats"),Gs=async(t=7)=>{let a;if(typeof t=="number"){const l=new Date,i=new Date;i.setDate(i.getDate()-t),a={start_date:Kt(i),end_date:Kt(l)}}else a=t;return Ie("/analytics/orders",{...a,timezone_offset_minutes:-new Date().getTimezoneOffset()})},cr=async t=>{const a=await Ie("/analytics/orders/valid",{start_date:t.start_date,end_date:t.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()}),i=(Array.isArray(a)?a:a.orders||[]).map(m=>({...m,id:m.id||m.order_id,status:Ia(m.status||m.order_status),quantity:Number(m.quantity||1)}));return{orders:i,total:Array.isArray(a)?i.length:Number(a.total??i.length),truncated:Array.isArray(a)?!1:a.truncated===!0}},dr=t=>{let a=t.api_config;if(typeof a=="string"&&a.trim())try{a=JSON.parse(a)}catch{a=void 0}return{...t,api_config:a||void 0}},Aa=t=>({...t,api_config:t.api_config?JSON.stringify(t.api_config):""}),Xe=async()=>{const t=await Ie("/cards");return(Array.isArray(t)?t:(t==null?void 0:t.cards)||[]).map(dr)},xr=async t=>Le("/cards",Aa(t)),Ks=async(t,a)=>Be(`/cards/${t}`,Aa(a)),mr=async t=>Ze(`/cards/${t}`),pr=async t=>{const a=new FormData;return a.append("file",t),wt("/cards/batch",a)},ur=async(t,a)=>Le(`/cards/${t}/append-data`,{content:a}),ls=t=>t===!0||t===1||t==="1",vt=async t=>{const a=await Ie("/items",void 0);return(Array.isArray(a)?a:a.items||[]).map(i=>({...i,id:i.id||`${i.cookie_id}-${i.item_id}`,is_multi_spec:ls(i.is_multi_spec),is_multi_qty_ship:ls(i.is_multi_qty_ship??i.multi_quantity_delivery),multi_quantity_delivery:ls(i.multi_quantity_delivery??i.is_multi_qty_ship)}))},hr=async t=>Le("/items/get-all-from-account",{cookie_id:t}),gr=async(t,a)=>Ze(`/items/${t}/${a}`),br=async(t,a)=>Le(`/items/${t}`,a),fr=async t=>{const a=new FormData;a.set("cookie_id",t.cookie_id),a.set("title",t.title),a.set("description",t.description),a.set("price",t.price),a.set("original_price",t.original_price||""),a.set("quantity",String(t.quantity)),a.set("postage_mode",t.postage_mode),a.set("postage",t.postage||""),t.location&&a.set("location",JSON.stringify(t.location));for(const l of t.images)a.append("images",l);return wt("/items/publish",a)},yr=async(t,a)=>Le("/items/publish-categories/recommend",{cookie_id:t,keyword:a}),jr=async t=>{const a=new FormData;return a.set("file",t.file),t.imagesZip&&a.set("images_zip",t.imagesZip),t.defaultCookieId&&a.set("default_cookie_id",t.defaultCookieId),a.set("fallback_category_id",t.fallbackCategory.catId),a.set("fallback_category_name",t.fallbackCategory.catName),a.set("fallback_channel_category_id",t.fallbackCategory.channelCatId||""),a.set("fallback_tb_category_id",t.fallbackCategory.tbCatId||""),t.location&&a.set("location",JSON.stringify(t.location)),wt("/items/publish-batches/preview",a)},_r=async t=>Le("/items/publish-batches",{preview_id:t}),bt=async t=>Ie(`/items/publish-batches/${t}`),Hs=async(t=20)=>{const a=await Ie("/items/publish-batches",{limit:t});return Array.isArray(a)?a:a.batches||[]},Nr=async t=>Ze(`/items/publish-batches/${t}`),vr=async t=>Le(`/items/publish-batches/${t}/cancel`,{}),wr=async t=>Le(`/items/publish-batches/${t}/retry-failed`,{}),kr=async(t,a,l)=>Be(`/items/${t}/${a}`,l),$a=t=>t.map(a=>{var l,i;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((l=(a.actions||[]).find(m=>m.action_type==="send_card"))==null?void 0:l.card_id)||0),card_group_name:((i=(a.actions||[]).find(m=>m.action_type==="send_card"))==null?void 0:i.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(m=>({id:m.id?String(m.id):void 0,action_type:m.action_type,card_id:Number(m.card_id||0),card_name:m.card_name||"",delivery_count:Number(m.delivery_count||1),message_template:m.message_template||"",delay_seconds:Number(m.delay_seconds||0),config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:Number(m.sort_order||0)})),variants:(a.actions||[]).filter(m=>m.action_type==="send_card").map(m=>{let N={};try{N=JSON.parse(m.config_json||"{}")}catch{}return{id:m.id?String(m.id):void 0,spec_name:N.spec_name||"",spec_value:N.spec_value||"",card_id:Number(m.card_id||0),card_name:m.card_name||"",delivery_count:Number(m.delivery_count||1),enabled:m.enabled!==!1,delay_override:N.delay_override===!0,delay_seconds:Number(m.delay_seconds||0),config_json:m.config_json||"{}"}})}}),gs=async()=>{const t=await Ie("/automation-rules"),a=Array.isArray(t)?t:t.data||t.rules||[];return $a(a)},Cr=async({cookieId:t,triggerType:a,enabled:l,search:i,page:m=1,pageSize:N=10}={})=>{const _=await Ie("/automation-rules",{page:m,page_size:N,cookie_id:t||void 0,trigger_type:a||void 0,enabled:l,search:(i==null?void 0:i.trim())||void 0}),I=$a(Array.isArray(_)?_:_.data||_.rules||[]);return{success:!0,data:I,total:Number(_.total??I.length),page:Number(_.page??m),page_size:Number(_.page_size??N),total_pages:Number(_.total_pages??(I.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(_.trigger_counts||{}).map(([g,C])=>[g,Number(C)]))}},Sr=(t,a)=>{if(t!=="order_paid")return a.map((m,N)=>({...m,sort_order:m.sort_order||N+1}));const l=a.filter(m=>m.action_type==="send_card").map((m,N)=>({...m,sort_order:N+1})),i=a.filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment");return[...l,...i.map((m,N)=>({...m,sort_order:l.length+N+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:l.length+i.length+1}]},Zs=async t=>{const a=t.trigger_type||"order_paid",i=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[a]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),m=(t.actions||[]).filter(g=>g.action_type!=="send_card"&&g.action_type!=="confirm_shipment"),N=t.variants&&t.variants.length>0?[...t.variants.map((g,C)=>({action_type:"send_card",card_id:g.card_id,delivery_count:g.delivery_count||1,enabled:g.enabled!==!1,sort_order:C+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})})),...m]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],_=Sr(a,N),I={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||i||"自动化规则",trigger_type:a,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:_.map((g,C)=>({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||C+1}))};return t.id?Be(`/automation-rules/${t.id}`,I):Le("/automation-rules",I)},Lr=async t=>Ze(`/automation-rules/${t}`),Or=async()=>{const t=await Ie("/automation-issues");return{runs:Array.isArray(t==null?void 0:t.runs)?t.runs:[],pending_tasks:Array.isArray(t==null?void 0:t.pending_tasks)?t.pending_tasks:[]}},Ir=async(t,a)=>Le(`/automation-runs/${t}/resolve`,{resolution:a}),Ar=async(t,a)=>Le(`/automation-pending-tasks/${t}/resolve`,{resolution:a}),$r=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Rr=async t=>{const a=await Ie(`/keywords-with-type/${t}`);return Array.isArray(a)?a.map($r):[]},Pr=async t=>t?(await Rr(t)).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||""})):[],Er=async(t,a)=>{const l=t.type||"text",i={keyword:t.keyword||"",reply:l==="text"&&t.reply_content||"",item_id:t.item_id||"",type:l,image_url:l==="image"&&t.image_url||""};return t.id?Be(`/keywords-with-type/${a}/${t.id}`,i):Le(`/keywords-with-item-id/${a}`,i)},Dr=async(t,a)=>Ze(`/keywords-with-type/${a}/${t}`),Ra=async()=>{const t=await Ie("/system-settings");return Il(t.data||t)},Pa=async t=>{const a=Object.fromEntries(Object.entries(t).filter(([,l])=>l!=null));return Be("/system-settings",a)},Tr=async(t,a)=>Ie(`/ai-reply-settings/${t}`,void 0,a),Mr=async(t,a)=>{const l={ai_enabled:a.ai_enabled??!1,max_discount_percent:a.max_discount_percent??10,max_discount_amount:a.max_discount_amount??100,max_bargain_rounds:a.max_bargain_rounds??3,custom_prompts:a.custom_prompts??""};return Be(`/ai-reply-settings/${t}`,l)},qr=async(t,a="")=>(await Le("/ai-models",{base_url:t,api_key:a})).models||[],Fr=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const a=JSON.parse(t);if(Array.isArray(a))return a.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(a=>a.trim()).filter(Boolean)},Ea=t=>{const a=Array.from(new Set((t||[]).filter(Boolean)));return a.length>0?JSON.stringify(a):""},Da=async t=>({success:!0,data:(await Ie("/notification-channels",void 0,t)||[]).map(i=>{let m;try{m=typeof i.config=="string"?JSON.parse(i.config):i.config}catch{m={}}return{id:String(i.id),name:i.name,type:i.type==="ding_talk"?"dingtalk":i.type==="lark"?"feishu":i.type,config:m,event_types:Fr(i.event_types),enabled:i.enabled,created_at:i.created_at,updated_at:i.updated_at}})}),Br=async t=>Le("/notification-channels",{...t,config:JSON.stringify(t.config),event_types:Ea(t.event_types)}),Ys=async(t,a)=>{const l={...a};return"config"in a&&(l.config=JSON.stringify(a.config)),"event_types"in a&&(l.event_types=Ea(a.event_types)),Be(`/notification-channels/${t}`,l)},zr=async t=>Ze(`/notification-channels/${t}`),Ur=async(t,a)=>{const l=await Ie(`/message-notifications/${t}`,void 0,a);return(l==null?void 0:l.channel_ids)||[]},Wr=async t=>Le(`/notification-channels/${t}/test`,{}),Xs=async()=>Ie("/api/default-replies"),Jr=async t=>{const a=await Ie(`/api/default-reply/${t}`);return{cookie_id:t,enabled:a.enabled||!1,reply_content:a.reply_content||"",reply_once:a.reply_once||!1,reply_image_url:a.reply_image_url||""}},Vr=async(t,a)=>Be(`/api/default-reply/${t}`,{enabled:a.enabled??!1,reply_content:a.reply_content||"",reply_once:a.reply_once??!1,reply_image_url:a.reply_image_url||""}),Qr=async t=>Ze(`/api/default-reply/${t}`),Gr=async t=>Le(`/api/default-reply/${t}/clear-records`,{}),At=t=>String(t).padStart(2,"0"),bs=t=>{if(t==null||t==="")return"-";const a=t instanceof Date?t:new Date(t);return Number.isNaN(a.getTime())?"-":[a.getFullYear(),At(a.getMonth()+1),At(a.getDate())].join("-")+" "+[At(a.getHours()),At(a.getMinutes()),At(a.getSeconds())].join(":")},Ne=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Kr=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand 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:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},Wt=({title:t,value:a,icon:l,colorClass:i,trend:m})=>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 ${i} 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 ${i} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(l,{className:`w-6 h-6 ${i.replace("bg-","text-")}`})}),m&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(Ka,{className:"w-3 h-3"})," ",m]})]}),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:a}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),rs=()=>{var V,ee;const[t,a]=r.useState(null),[l,i]=r.useState(null),[m,N]=r.useState(""),[_,I]=r.useState("7days"),[g,C]=r.useState(""),[j,B]=r.useState(""),[K,me]=r.useState(null),[oe,v]=r.useState(""),[F,ce]=r.useState([]),[Q,te]=r.useState(0),[z,ge]=r.useState(!1),[he,k]=r.useState(!1),[Y,se]=r.useState([]),[H,ve]=r.useState({}),J=r.useRef(0),A=[Ne("brand"),Ne("brand-highlight"),Ne("success-500"),Ne("warning-500"),Ne("accent-500")],E=c=>`¥${Number(c||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`,P=async c=>{let d;try{d=Js(c,new Date,g,j)}catch(Oe){N(Oe instanceof Error?Oe.message:"日期范围无效");return}const{startDate:T,endDate:S}=d,X={start_date:T,end_date:S},O=Ol(d),de=++J.current;k(!0),N("");try{const[Oe,fe,Ae]=await Promise.all([Gs(X),Gs({start_date:O.startDate,end_date:O.endDate}),cr(X)]);if(de!==J.current)return;i(Oe),me(fe),ce(Ae.orders),te(Ae.total),ge(Ae.truncated)}catch(Oe){de===J.current&&N(Oe instanceof Error?Oe.message:"经营数据加载失败")}finally{de===J.current&&k(!1)}},be=()=>{if(!l||!K)return null;const c=l.revenue_stats.total_amount,d=K.revenue_stats.total_amount;if(d===0)return c>0?"+100%":"0%";const T=(c-d)/d*100;return`${T>=0?"+":""}${T.toFixed(1)}%`};if(r.useEffect(()=>{let c=!1;return Promise.all([or(),vt()]).then(([d,T])=>{if(c)return;a(d),se(T);const S={};T.forEach(X=>{S[X.item_id]=X.item_title||X.item_id}),ve(S)}).catch(d=>{c||N(d instanceof Error?d.message:"概览加载失败")}),()=>{c=!0}},[]),r.useEffect(()=>{_!=="custom"&&P(_)},[_]),m&&(!t||!l))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(rt,{className:"w-8 h-8"}),e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:()=>window.location.reload(),children:"重新加载"})]});if(!t||!l)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx($s,{className:"w-8 h-8 animate-spin text-brand"})});const Pe=((V=l.daily_stats)==null?void 0:V.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})))||[],ae=l.item_stats||[],M=l.revenue_stats.total_orders||0,p=l.revenue_stats.total_amount||0,b=ae.length>0?ae.map(c=>({name:(H[c.item_id]||c.item_id).length>12?(H[c.item_id]||c.item_id).substring(0,12)+"...":H[c.item_id]||c.item_id,sales:c.order_count})).sort((c,d)=>d.sales-c.sales).slice(0,10):[],U=Math.max(...b.map(c=>c.sales),1),q=ae.length>0?ae.map(c=>({name:(H[c.item_id]||c.item_id).length>10?(H[c.item_id]||c.item_id).substring(0,10)+"...":H[c.item_id]||c.item_id,value:c.order_count,percent:M>0?c.order_count/M*100:0})).sort((c,d)=>d.value-c.value).slice(0,6).map((c,d)=>({...c,color:A[d%A.length]})):[],re=ae.length>0?ae.map(c=>({name:(H[c.item_id]||c.item_id).length>12?(H[c.item_id]||c.item_id).substring(0,12)+"...":H[c.item_id]||c.item_id,value:c.total_amount,orderCount:c.order_count,percentage:p>0?c.total_amount/p*100:0})).sort((c,d)=>d.value-c.value).slice(0,5).map((c,d)=>({...c,color:A[d%A.length],percentage:c.percentage.toFixed(1)})):[],pe=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}],je=((ee=pe.find(c=>c.key===_))==null?void 0:ee.label)||"所选范围";let Ee;try{Ee=Js(_,new Date,g,j)}catch{Ee={startDate:g,endDate:j}}const Se=oe.trim().toLowerCase(),x=F.filter(c=>{var d,T,S,X;return((d=c.order_id)==null?void 0:d.toLowerCase().includes(Se))||((T=c.item_id)==null?void 0:T.toLowerCase().includes(Se))||((S=c.item_title)==null?void 0:S.toLowerCase().includes(Se))||((X=c.buyer_id)==null?void 0:X.toLowerCase().includes(Se))});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:[pe.map(c=>e.jsx("button",{onClick:()=>I(c.key),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${_===c.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:c.label},c.key)),_==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:g,onChange:c=>C(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:j,onChange:c=>B(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:()=>{try{N(""),P("custom")}catch(c){N(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(Wt,{title:"累计营收 (CNY)",value:`¥${l.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:Ga,colorClass:"bg-blue-400",trend:be()||void 0}),e.jsx(Wt,{title:"活跃账号 / 总数",value:`${t.active_cookies} / ${t.total_cookies}`,icon:ba,colorClass:"bg-blue-500"}),e.jsx(Wt,{title:"订单数",value:l.revenue_stats.total_orders.toLocaleString(),icon:Rs,colorClass:"bg-blue-500"}),e.jsx(Wt,{title:"库存卡密余量",value:t.available_card_stock,icon:ja,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:[je,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:Pe.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(Rs,{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:"所选时间范围内暂无订单记录"})]}):Pe.length<=2?e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(fl,{data:Pe,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Bs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:Ne("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(zs,{axisLine:!1,tickLine:!1,tick:{fill:Ne("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:c=>`¥${c}`}),e.jsx(Ut,{contentStyle:{backgroundColor:Ne("white"),borderRadius:"8px",border:`1px solid ${Ne("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:Ne("neutral-500"),fontWeight:500},itemStyle:{color:Ne("brand"),fontWeight:600},cursor:{fill:Ne("brand",.08)},formatter:c=>[`¥${Number(c).toFixed(2)}`,"营收"]}),e.jsx(yl,{dataKey:"amount",fill:Ne("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:Pe.map((c,d)=>e.jsx(ts,{fill:Ne("brand"),stroke:"none",strokeWidth:0},`cell-${d}`))})]})}):e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(jl,{data:Pe,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:Ne("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:Ne("brand"),stopOpacity:0})]})}),e.jsx(Bs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:Ne("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(zs,{axisLine:!1,tickLine:!1,tick:{fill:Ne("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(_l,{vertical:!1,stroke:Ne("neutral-100"),strokeDasharray:"3 3"}),e.jsx(Ut,{contentStyle:{backgroundColor:Ne("white"),borderRadius:"8px",border:`1px solid ${Ne("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:Ne("neutral-500"),fontWeight:500},itemStyle:{color:Ne("brand"),fontWeight:600},cursor:{stroke:Ne("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Nl,{type:"monotone",dataKey:"amount",stroke:Ne("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:Ne("white"),stroke:Ne("brand"),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:b.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:b.map((c,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 ${d<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:d+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-brand",style:{width:`${Math.max(8,c.sales/U*100)}%`}})})]},`${c.name}-${d}`))})})]}),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:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${M} 单`,children:q.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(Us,{accessibilityLayer:!1,children:[e.jsx(Ws,{data:q,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:q.map((c,d)=>e.jsx(ts,{fill:c.color},`cell-${d}`))}),e.jsx(Ut,{formatter:c=>`${Number(c||0)} 单`,wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:Ne("white"),border:`1px solid ${Ne("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(vl,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:c=>e.jsx("span",{style:{color:Ne("neutral-500"),fontWeight:500},children:c})})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:M}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),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-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),z&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",F.length," / ",Q," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:oe,onChange:c=>v(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:he?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx($s,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):x.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(qt,{className:"w-7 h-7 text-gray-300"})}),Se?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:["当前共有 ",F.length," 单参与统计,但没有订单号、商品、买家匹配“",oe,"”。"]})]}):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:["日期范围:",Ee.startDate," 至 ",Ee.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",l.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] 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 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:x.map(c=>e.jsxs("tr",{className:"hover:bg-warning-50/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(qt,{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:bs(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 whitespace-nowrap",children:e.jsx(Kr,{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(_a,{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)"}),re.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${E(p)}`,children:[e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(Us,{accessibilityLayer:!1,children:[e.jsx(Ws,{data:re,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:re.map((c,d)=>e.jsx(ts,{fill:c.color||A[d%A.length]},`cell-${d}`))}),e.jsx(Ut,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:Ne("white"),border:`1px solid ${Ne("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:c=>`¥${Number(c||0).toLocaleString()}`})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:E(p)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:re.map(c=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:c.color||A[re.indexOf(c)%A.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:c.name,children:c.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",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))})]})]})]})]})},Hr=(t,a)=>{const l=a.pause_duration||0;return t!==l},Zr=(t,a)=>{const l=a.username!==(t.username||""),i=a.show_browser!==(t.show_browser||!1),m=a.login_password!=="",N=a.clear_password===!0;if(!l&&!i&&!m&&!N)return null;const _={username:a.username,show_browser:a.show_browser};return N?_.clear_password=!0:m&&(_.login_password=a.login_password),_},Yr=(t,a)=>t&&a,Xr=(t,a)=>{if(!t||!a)return!1;const l=Date.parse(t),i=Date.parse(a);return Number.isFinite(l)&&Number.isFinite(i)&&it.map(l=>{const i=a[l.id];return!i||Xr(l.runtime_updated_at,i.updated_at)?l:{...l,runtime_state:i.state,runtime_message:i.message||"",runtime_connected:i.connected,runtime_updated_at:i.updated_at}}),tn=new Set(["expired","cancelled","error","not_found"]),Jt=()=>{let t=0;return{next:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:a=>a===t}},sn=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let a=null,l=null,i=-1,m=0;const N=()=>{m+=1,l==null||l.abort(),l=null,a!==null&&(t.clearInterval(a),a=null)};return{start:(I,g,C,j=2e3)=>{N();const B=m;l=new AbortController;const K=l.signal;a=t.setInterval(()=>{i===B||B!==m||(i=B,(async()=>{var me,oe;try{const v=await g(I,K);if(v.status==="success"){N(),await C.onSuccess(v);return}if(v.status==="scanned"){(me=C.onScanned)==null||me.call(C,v);return}if(v.status==="verification_required"){(oe=C.onVerificationRequired)==null||oe.call(C,v);return}v.status&&tn.has(v.status)&&(N(),C.onTerminalError(v))}catch(v){if(K.aborted||B!==m)return;N(),C.onPollError(v)}finally{i===B&&(i=-1)}})())},j)},stop:N,isActive:()=>a!==null}},an=({faceQrUrl:t,verificationScreenshot:a})=>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(Ha,{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:t?e.jsx("img",{src:t,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):a?e.jsx("img",{src:a,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(Re,{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:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),ea=({src:t,alt:a,className:l=""})=>e.jsx("img",{src:t,alt:a,className:`block aspect-square h-auto w-full object-contain ${l}`.trim()}),ta=({checked:t,onChange:a,label:l})=>e.jsx("button",{type:"button","aria-label":l,"aria-pressed":t,onClick:a,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-6":""}`})}),ln=({account:t,onClose:a,onSaved:l})=>{const[i,m]=r.useState({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),[N,_]=r.useState(!1),[I,g]=r.useState(""),[C,j]=r.useState(""),[B,K]=r.useState(null),me=async()=>{_(!0),j("");try{const v=await Vs(t.id,i);m(v),l(v)}catch(v){j(v instanceof Error?v.message:"保存失败")}finally{_(!1)}},oe=async v=>{g(v),j(""),K(null);try{await Vs(t.id,i);const F=await Tl(t.id,v),ce=await Dl(t.id);K(F.summary),m(ce),l(ce)}catch(F){j(F instanceof Error?F.message:"任务执行失败")}finally{g("")}};return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:a,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(Me,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(Za,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(ta,{checked:i.auto_rate_enabled,onChange:()=>m(v=>({...v,auto_rate_enabled:!v.auto_rate_enabled})),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:i.rate_content,maxLength:500,onChange:v=>m(F=>({...F,rate_content:v.target.value})),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",i.last_rate_scan_at?new Date(i.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:I!==""||!t.enabled,onClick:()=>void oe("auto_rate"),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[I==="auto_rate"?e.jsx(Re,{className:"h-4 w-4 animate-spin"}):e.jsx(Ya,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(vs,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(ta,{checked:i.auto_polish_enabled,onChange:()=>m(v=>({...v,auto_polish_enabled:!v.auto_polish_enabled})),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:i.polish_time,onChange:v=>m(F=>({...F,polish_time:v.target.value})),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:I!==""||!t.enabled,onClick:()=>void oe("auto_polish"),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[I==="auto_polish"?e.jsx(Re,{className:"h-4 w-4 animate-spin"}):e.jsx(Na,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",i.last_polish_at?new Date(i.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),B&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",B.found," 项,成功 ",B.success,",失败 ",B.failed,",跳过 ",B.skipped,"。",B.message||""]}),C&&e.jsx("div",{className:"rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:C})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:a,disabled:N||I!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:()=>void me(),disabled:N||I!==""||i.auto_rate_enabled&&!i.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[N?e.jsx(Re,{className:"h-4 w-4 animate-spin"}):e.jsx(He,{className:"h-4 w-4"}),"保存"]})]})})]})})},rn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState(!0),[m,N]=r.useState(""),[_,I]=r.useState(""),[g,C]=r.useState(""),[j,B]=r.useState(null),[K,me]=r.useState(""),[oe,v]=r.useState(!1),[F,ce]=r.useState(""),[Q,te]=r.useState("pending"),[z,ge]=r.useState(""),[he,k]=r.useState(""),[Y,se]=r.useState(""),[H,ve]=r.useState(null),[J,A]=r.useState(null),[E,P]=r.useState(null),[be,Pe]=r.useState(null),[ae,M]=r.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[p,b]=r.useState([]),[U,q]=r.useState([]),[re,pe]=r.useState(!1),[je,Ee]=r.useState(!1),[Se,x]=r.useState(!1),[V,ee]=r.useState(""),[c,d]=r.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),[T,S]=r.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[X,O]=r.useState(!1),[de,Oe]=r.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),fe=r.useRef(null),Ae=r.useRef(null),ne=r.useRef(null),h=r.useRef(null),f=r.useRef(null),D=r.useRef(null),R=r.useRef(null),we=r.useRef(null),Ce=r.useRef(null),ke=r.useRef(null),De=r.useRef(null),G=r.useRef(null),ye=r.useRef(0);fe.current===null&&(fe.current=sn()),Ae.current===null&&(Ae.current=Jt()),ne.current===null&&(ne.current=Jt()),h.current===null&&(h.current=Jt()),f.current===null&&(f.current=Jt());const u=()=>{De.current!==null&&(window.clearTimeout(De.current),De.current=null)},L=()=>{G.current!==null&&(window.clearTimeout(G.current),G.current=null)},le=()=>{var s;(s=fe.current)==null||s.stop()},_e=()=>{var s,o;(s=Ce.current)==null||s.abort(),(o=Ae.current)==null||o.cancel(),le(),u(),v(!1)},Ue=()=>{u(),De.current=window.setTimeout(()=>{De.current=null,v(!1),Fe()},1e3)},Fe=async()=>{var y,$,W,ue,xe;const s=ne.current.next();(y=D.current)==null||y.abort();const o=new AbortController;D.current=o,i(!0);try{const $e={signal:o.signal},[ie,Ye]=await Promise.allSettled([Ft($e),er($e)]);if(!(($=ne.current)!=null&&$.isCurrent(s)))return;if(ie.status==="rejected")throw ie.reason;const Ve=ie.value,It=Ye.status==="fulfilled"?Ye.value:{};Ye.status==="rejected"&&console.error("Failed to load AI settings:",Ye.reason);const Wa=Ve.map(gt=>{var Cs,Ss,Ls,Os,Is;return{...gt,ai_enabled:((Cs=It[gt.id])==null?void 0:Cs.ai_enabled)??!1,max_discount_percent:((Ss=It[gt.id])==null?void 0:Ss.max_discount_percent)??10,max_discount_amount:((Ls=It[gt.id])==null?void 0:Ls.max_discount_amount)??100,max_bargain_rounds:((Os=It[gt.id])==null?void 0:Os.max_bargain_rounds)??3,custom_prompts:((Is=It[gt.id])==null?void 0:Is.custom_prompts)??""}});(W=ne.current)!=null&&W.isCurrent(s)&&a(Wa)}catch($e){(ue=ne.current)!=null&&ue.isCurrent(s)&&!o.signal.aborted&&console.error("Failed to load accounts:",$e)}finally{(xe=ne.current)!=null&&xe.isCurrent(s)&&i(!1)}};r.useEffect(()=>{let s=!1,o=null;const y=new AbortController,$=async()=>{try{const W=await hs({signal:y.signal,timeoutMs:1e4});s||a(ue=>en(ue,W))}catch(W){s||console.error("Failed to load account runtime statuses:",W)}finally{s||(o=window.setTimeout(()=>void $(),2e3))}};return Fe().finally(()=>{s||$()}),()=>{s=!0,y.abort(),o!==null&&window.clearTimeout(o)}},[]),r.useEffect(()=>()=>{var s,o,y,$,W,ue,xe,$e,ie;le(),(s=Ae.current)==null||s.cancel(),(o=ne.current)==null||o.cancel(),(y=h.current)==null||y.cancel(),($=f.current)==null||$.cancel(),(W=D.current)==null||W.abort(),(ue=R.current)==null||ue.abort(),(xe=we.current)==null||xe.abort(),($e=Ce.current)==null||$e.abort(),(ie=ke.current)==null||ie.abort(),u(),ye.current+=1,L()},[]);const tt=s=>{if(!s.enabled||s.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(s.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"}}},kt=async(s,o)=>{await Wl(s,!o),Fe()},Je=s=>{g||(me(""),B(s))},We=()=>{g||(me(""),B(null))},Ct=async()=>{const s=j;if(!(!s||g)){C(s.id),me("");try{await Jl(s.id),a(o=>o.filter(y=>y.id!==s.id)),B(null)}catch(o){console.error("删除账号失败:",o),me((o==null?void 0:o.message)||"删除账号失败,请稍后重试")}finally{C("")}}},St=async s=>{I(s.id);try{const o=await Xl(s.id);o!=null&&o.profile_error&&alert("资料刷新失败:"+o.profile_error),await Fe()}catch(o){console.error("刷新账号资料失败:",o),alert((o==null?void 0:o.message)||"刷新账号资料失败,请先重新授权该账号")}finally{I("")}},mt=async s=>{var ue,xe;const o=h.current.next();(ue=R.current)==null||ue.abort();const y=new AbortController;R.current=y,Ee(!0),pe(!1),x(!1),ee("");const[$,W]=await Promise.allSettled([Da({signal:y.signal}),Ur(s,{signal:y.signal})]);(xe=h.current)!=null&&xe.isCurrent(o)&&($.status==="fulfilled"?b($.value.data||[]):(b([]),ee("通知渠道列表加载失败,请重试")),W.status==="fulfilled"?(q(W.value||[]),pe(!0)):(q([]),ee("通知绑定加载失败;本次保存不会修改现有绑定")),Ee(!1))},Lt=async s=>{var y;ye.current+=1,(y=ke.current)==null||y.abort(),L(),Oe({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),P(s),d({remark:s.remark||s.note||"",cookie:s.cookie||s.value||"",auto_confirm:s.auto_confirm||!1,pause_duration:s.pause_duration||0,username:s.username||"",login_password:s.login_password||"",show_browser:s.show_browser||!1,showLoginPassword:!1,clear_password:!1}),A("edit"),M({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,o]=await Promise.allSettled([mt(s.id),Gl(s.id)]);o.status==="fulfilled"?M({loading:!1,saving:!1,canOpen:o.value.can_open_long_login,enabled:o.value.enabled,error:""}):M({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"})},nt=async()=>{if(!E||ae.loading||ae.saving||!ae.canOpen)return;const s=!ae.enabled;M(o=>({...o,saving:!0,error:""}));try{const o=await Kl(E.id,s);M({loading:!1,saving:!1,canOpen:o.can_open_long_login,enabled:o.enabled,error:""})}catch(o){M(y=>({...y,saving:!1,error:o instanceof Error?o.message:"保存登录信息设置失败"}))}},it=async s=>{var $,W,ue,xe;const o=f.current.next();($=we.current)==null||$.abort();const y=new AbortController;we.current=y,P(s),A("ai-settings"),O(!0);try{const $e=await Tr(s.id,{signal:y.signal});if(!((W=f.current)!=null&&W.isCurrent(o)))return;S({ai_enabled:$e.ai_enabled??!1,max_discount_percent:$e.max_discount_percent??10,max_discount_amount:$e.max_discount_amount??100,max_bargain_rounds:$e.max_bargain_rounds??3,custom_prompts:$e.custom_prompts??""})}catch($e){(ue=f.current)!=null&&ue.isCurrent(o)&&console.error("Failed to load AI settings:",$e)}finally{(xe=f.current)!=null&&xe.isCurrent(o)&&O(!1)}},Ot=async()=>{if(E){O(!0);try{const s={};c.remark!==(E.remark||E.note||"")&&(s.remark=c.remark),c.cookie&&c.cookie!==(E.cookie||E.value||"")&&(s.cookie=c.cookie),c.auto_confirm!==E.auto_confirm&&(s.auto_confirm=c.auto_confirm),Hr(c.pause_duration,E)&&(s.pause_duration=c.pause_duration);const o=Zr(E,c);o&&Object.assign(s,o),Yr(re,Se)&&(s.channel_ids=U),Object.keys(s).length>0&&await Ql(E.id,s),A(null),Fe()}catch(s){console.error("更新账号失败:",s),alert("更新失败,请重试")}finally{O(!1)}}},pt=async()=>{if(!(!E||c.pause_duration<=0)){O(!0);try{const s=await Vl(E.id,c.pause_duration);P({...E,pause_duration:c.pause_duration,paused:(s==null?void 0:s.paused)===!0,paused_until:Number((s==null?void 0:s.paused_until)||0)}),await Fe()}catch(s){alert(s instanceof Error?s.message:"重新暂停失败")}finally{O(!1)}}},ut=async()=>{if(E){O(!0);try{await Mr(E.id,T),A(null),Fe()}catch(s){console.error("更新AI设置失败:",s),alert("更新失败,请重试")}finally{O(!1)}}},st=async(s,o)=>{var $;($=ke.current)==null||$.abort();const y=new AbortController;ke.current=y;try{const W=await Zl(s,y.signal);if(o!==ye.current)return;if(W.status==="success"){L(),Oe({sessionId:s,status:"success",message:W.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}),d(ue=>({...ue,login_password:"",showLoginPassword:!1})),await Fe();return}if(W.status==="processing"||W.status==="verification_required"){Oe({sessionId:s,status:W.status,message:W.message||(W.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:W.qr_code_url||""}),L(),G.current=window.setTimeout(()=>void st(s,o),1500);return}L(),Oe({sessionId:s,status:"failed",message:W.error||W.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""})}catch(W){if(o!==ye.current)return;L(),Oe({sessionId:s,status:"failed",message:W instanceof Error?W.message:"查询密码登录状态失败",qrCodeUrl:""})}},ht=async()=>{var y;if(!E)return;const s=c.username.trim();if(!s||!c.login_password){alert("请先填写登录账号和本次登录密码");return}L(),(y=ke.current)==null||y.abort();const o=++ye.current;Oe({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const $=await Hl({account_id:E.id,account:s,password:c.login_password,show_browser:c.show_browser});if(o!==ye.current)return;if(!$.success||!$.session_id)throw new Error($.message||"无法启动密码登录");Oe({sessionId:$.session_id,status:"processing",message:$.message||"登录处理中",qrCodeUrl:""}),await st($.session_id,o)}catch($){if(o!==ye.current)return;Oe({sessionId:"",status:"failed",message:$ instanceof Error?$.message:"启动密码登录失败",qrCodeUrl:""})}},Ke=async()=>{var o;const s=de.sessionId;if(ye.current+=1,(o=ke.current)==null||o.abort(),L(),s)try{await Yl(s)}catch(y){console.error("取消密码登录失败",y)}Oe({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},ot=async()=>{var s,o;(s=h.current)==null||s.cancel(),(o=R.current)==null||o.abort(),(de.status==="processing"||de.status==="verification_required")&&await Ke(),A(null)},n=()=>{var s,o;(s=f.current)==null||s.cancel(),(o=we.current)==null||o.abort(),A(null)},w=async(s,o)=>{const y=await Ul(s,o==null?void 0:o.id);if(!y.success||!y.account_id)throw new Error(y.message||"保存扫码授权失败");return y.account_id},Z=async s=>{var W,ue,xe,$e;le(),(W=Ce.current)==null||W.abort();const o=new AbortController;Ce.current=o;const y=Ae.current.next();u();const $=s||null;ve($),v(!0),te("loading"),ge(""),ce(""),k(""),se("");try{const ie=await Bl({signal:o.signal});if(!((ue=Ae.current)!=null&&ue.isCurrent(y)))return;if(!ie.success||!ie.qr_code_url||!ie.session_id)throw new Error(ie.message||"闲鱼未返回可用的登录二维码");if(ie.success&&ie.qr_code_url&&ie.session_id){const Ye=ie.session_id;ce(ie.qr_code_url),te("waiting"),(xe=fe.current)==null||xe.start(Ye,zl,{onSuccess:async()=>{try{if(!await w(Ye,$)){te("error");return}}catch(Ve){console.error("保存扫码授权失败",Ve),te("error");return}te("success"),Ue()},onScanned:()=>{te("waiting")},onTerminalError:()=>{te("error")},onPollError:Ve=>{console.error("轮询扫码状态失败",Ve),te("error")},onVerificationRequired:Ve=>{te("verification"),Ve.face_qr_url&&se(Ve.face_qr_url),Ve.verification_screenshot&&k(Ve.verification_screenshot)}})}}catch(ie){if(!(($e=Ae.current)!=null&&$e.isCurrent(y)))return;ge(ie instanceof Error?ie.message:"二维码获取失败,请稍后重试"),te("error")}finally{Ce.current===o&&(Ce.current=null)}};if(l)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(Re,{className:"w-8 h-8 text-brand animate-spin"})});const Te=t.filter(s=>{const o=m.trim().toLowerCase();return o?[s.id,s.nickname,s.remark,s.note,s.username,s.runtime_message].some(y=>(y||"").toLowerCase().includes(o)):!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:m,onChange:s=>N(s.target.value),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:()=>Z(),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(Xt,{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:["当前显示 ",Te.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[Te.map(s=>{const o=tt(s),y=s.runtime_state==="auth_expired"||s.runtime_state==="verification_required";return e.jsx("div",{className:"ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-5 sm:gap-8",children:[e.jsxs("div",{className:"relative",children:[s.avatar_url?e.jsx("img",{src:s.avatar_url,alt:s.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(xt,{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 ${o.dot}`,children:s.runtime_state==="online"&&e.jsx(Qe,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:s.nickname||s.remark||`账号 ${s.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${o.badge}`,children:o.label}),s.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(yt,{className:"w-3 h-3"})," AI"]}),s.auto_rate_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700",children:[e.jsx(Tt,{className:"h-3 w-3"})," 自动评价"]}),s.auto_polish_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700",children:[e.jsx(vs,{className:"h-3 w-3"})," 每日擦亮"]}),s.auto_confirm&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700",children:[e.jsx(Qe,{className:"h-3 w-3"})," 自动确认发货"]}),s.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:s.profile_error,children:[e.jsx(rt,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"text-sm font-medium text-gray-500",children:[e.jsx("p",{children:s.remark||s.note||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",s.id]})]}),s.runtime_message&&s.runtime_state!=="online"&&s.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${y?"text-red-700":"text-amber-700"}`,children:[e.jsx(rt,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:s.runtime_message}),y&&e.jsxs("button",{type:"button",onClick:()=>Z(s),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(Xt,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),s.paused&&e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700",children:[e.jsx(Ps,{className:"h-3 w-3"})," 暂停处理中"]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>St(s),disabled:_===s.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(ze,{className:`w-5 h-5 ${_===s.id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>Z(s),className:`p-3 rounded-xl transition-colors ${y?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(Xt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Lt(s),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(va,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>it(s),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(yt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Pe(s),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(Na,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>kt(s.id,s.enabled),className:`p-3 rounded-xl transition-colors ${s.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:s.enabled?"停用账号":"启用账号",children:e.jsx(Xa,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Je(s),disabled:g!=="",className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:g===s.id?"删除中…":`删除账号 ${s.nickname||s.remark||s.id}`,children:g===s.id?e.jsx(Re,{className:"w-5 h-5 animate-spin"}):e.jsx(Ge,{className:"w-5 h-5"})})]})]})]})]})},s.id)}),t.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(xt,{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:"请点击右上角扫码添加您的闲鱼账号"})]}),t.length>0&&Te.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。"})]})]}),be&&qe.createPortal(e.jsx(ln,{account:be,onClose:()=>Pe(null),onSaved:s=>{a(o=>o.map(y=>y.id===be.id?{...y,auto_rate_enabled:s.auto_rate_enabled,rate_content:s.rate_content,auto_polish_enabled:s.auto_polish_enabled,polish_time:s.polish_time,last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}:y))}}),document.body),j&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",role:"presentation",children:e.jsxs("div",{className:"h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal",role:"dialog","aria-modal":"true","aria-labelledby":"delete-account-title","aria-describedby":"delete-account-description",children:[e.jsxs("div",{className:"relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5",children:[e.jsx("div",{className:"absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl"}),e.jsxs("div",{className:"relative flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200",children:e.jsx(Ge,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{id:"delete-account-title",className:"text-lg font-extrabold tracking-tight text-gray-950",children:"删除这个账号?"}),e.jsx("p",{id:"delete-account-description",className:"mt-1 text-xs leading-5 text-gray-600",children:"删除后,该账号的关联配置也会一并清理,此操作无法撤销。"})]}),e.jsx("button",{type:"button",onClick:We,disabled:g!=="",className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"关闭删除确认",children:e.jsx(Me,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:j.nickname||j.remark||"未命名账号"}),j.remark&&j.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",j.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",j.id]})]}),g===j.id&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(Re,{className:"h-5 w-5 flex-shrink-0 animate-spin text-brand"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-blue-950",children:"正在删除账号"}),e.jsx("div",{className:"mt-0.5 text-xs text-blue-700",children:"正在清理关联数据,请保持页面打开…"})]})]}),K&&e.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3",role:"alert",children:[e.jsx(rt,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-red-800",children:"删除失败"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-red-700",children:K})]})]})]}),e.jsxs("div",{className:"flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4",children:[e.jsx("button",{type:"button",onClick:We,disabled:g!=="",className:"flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50",children:"取消"}),e.jsx("button",{type:"button",onClick:()=>void Ct(),disabled:g!=="",className:"flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400",children:g===j.id?e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),oe&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:_e,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(Me,{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:H?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:H?`请用闲鱼APP扫码,为「${H.nickname||H.remark||H.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${Q==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[Q==="loading"&&e.jsx(Re,{className:"w-10 h-10 text-brand animate-spin"}),Q==="waiting"&&e.jsx(ea,{src:F,alt:"闲鱼登录二维码",className:"p-2"}),Q==="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(Qe,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),Q==="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:z||"请关闭窗口后重新发起扫码登录。"})]}),Q==="verification"&&e.jsx(an,{faceQrUrl:Y,verificationScreenshot:he})]}),Q!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),J==="edit"&&E&&qe.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:E.nickname||E.remark||E.id})]}),e.jsx("button",{onClick:()=>void ot(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Me,{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:E.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:c.remark,onChange:s=>d({...c,remark:s.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:c.cookie,onChange:s=>d({...c,cookie:s.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长度: ",c.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(Qe,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:()=>d({...c,auto_confirm:!c.auto_confirm}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${c.auto_confirm?"bg-brand":"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 ${c.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(Ps,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:c.pause_duration,onChange:s=>d({...c,pause_duration:parseInt(s.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:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),c.pause_duration>0&&!E.paused&&c.pause_duration===(E.pause_duration||0)&&e.jsx("button",{type:"button",disabled:X,onClick:()=>void pt(),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(el,{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:"状态直接读取并修改闲鱼官方长登录设置"}),ae.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:ae.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:ae.loading||ae.saving||!ae.canOpen,onClick:()=>void nt(),className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${ae.enabled?"bg-brand":"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 ${ae.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:c.username,onChange:s=>d({...c,username:s.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:c.showLoginPassword?"text":"password",value:c.login_password,onChange:s=>d({...c,login_password:s.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:()=>d({...c,showLoginPassword:!c.showLoginPassword}),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:c.showLoginPassword?e.jsx(dt,{className:"w-5 h-5"}):e.jsx(lt,{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:c.clear_password,onChange:s=>d({...c,clear_password:s.target.checked,login_password:s.target.checked?"":c.login_password}),className:"w-4 h-4 accent-brand"}),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:()=>d({...c,show_browser:!c.show_browser}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${c.show_browser?"bg-brand":"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 ${c.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 和保存的登录信息。"})]}),de.status==="processing"||de.status==="verification_required"?e.jsx("button",{type:"button",onClick:Ke,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:ht,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),de.message&&e.jsx("div",{className:`text-sm font-medium ${de.status==="failed"?"text-red-700":de.status==="success"?"text-green-700":"text-blue-800"}`,children:de.message}),de.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 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),de.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(ea,{src:de.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(p.length>0||je||V)&&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(jt,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),je&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Re,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),V&&!je&&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:V}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:()=>mt(E.id),children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:p.map(s=>{const o=U.includes(Number(s.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:()=>{re&&(q(y=>o?y.filter($=>$!==Number(s.id)):[...y,Number(s.id)]),x(!0))},disabled:!re,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${o?"bg-brand border-brand":"bg-white border-gray-300"}`,children:o&&e.jsx(Qe,{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:s.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[s.type,s.enabled?"":" · 已停用"]})]})]},s.id)})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>void ot(),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:X,children:"取消"}),e.jsxs("button",{onClick:Ot,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:X,children:[X?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),X?"保存中...":"保存"]})]})})]})}),document.body),J==="ai-settings"&&E&&qe.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(yt,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:E.nickname||E.remark||E.id})]}),e.jsx("button",{onClick:n,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Me,{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(yt,{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:()=>S({...T,ai_enabled:!T.ai_enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${T.ai_enabled?"bg-brand":"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 ${T.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:T.max_discount_percent,onChange:s=>S({...T,max_discount_percent:parseInt(s.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:T.max_discount_amount,onChange:s=>S({...T,max_discount_amount:parseInt(s.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:T.max_bargain_rounds,onChange:s=>S({...T,max_bargain_rounds:parseInt(s.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:T.custom_prompts,onChange:s=>S({...T,custom_prompts:s.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(js,{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:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:X,children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:X,children:[X?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),X?"保存中...":"保存"]})]})})]})}),document.body)]})},nn=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(a=>({order_id:String((a==null?void 0:a.order_id)||"unknown"),success:(a==null?void 0:a.success)===!0,message:String((a==null?void 0:a.message)||"")})):[]}),on=t=>(t==null?void 0:t.results.filter(a=>!a.success))||[],sa=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand 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 ${a[t]||a.cancelled}`,children:l[t]||t})},cn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState([]),[m,N]=r.useState([]),[_,I]=r.useState({}),[g,C]=r.useState("all"),[j,B]=r.useState(""),[K,me]=r.useState(""),[oe,v]=r.useState(""),F=r.useRef(0),[ce,Q]=r.useState(1),[te,z]=r.useState(1),[ge,he]=r.useState(!1),[k,Y]=r.useState(!1),[se,H]=r.useState(!1),[ve,J]=r.useState(!1),[A,E]=r.useState(null),[P,be]=r.useState(null),[Pe,ae]=r.useState({}),[M,p]=r.useState(!1),[b,U]=r.useState(""),[q,re]=r.useState(!1),[pe,je]=r.useState(null),[Ee,Se]=r.useState(null),[x,V]=r.useState(null),[ee,c]=r.useState(!1),[d,T]=r.useState(null),[S,X]=r.useState(null),O=async()=>{const u=++F.current;he(!0);try{const L=await tr(j||void 0,g,ce,20,oe);if(u!==F.current)return;a(L.data),z(L.total_pages)}catch(L){console.error("加载订单失败:",L)}finally{u===F.current&&he(!1)}},de=(u,L,le)=>{if(le&&le.trim())return le;if(_[`${u}:${L}`])return _[`${u}:${L}`];const _e=l.find(Ue=>{if(le&&Ue.item_title){const Fe=le.toLowerCase(),tt=Ue.item_title.toLowerCase();return tt.includes(Fe)||Fe.includes(tt)}return!1});return _e!=null&&_e.item_title?_e.item_title:"未知商品"},Oe=u=>{const L={};u.forEach(le=>{le.item_id&&(L[`${le.cookie_id}:${le.item_id}`]=le.item_title||le.item_id)}),I(L)};r.useEffect(()=>{const u=window.setTimeout(()=>{Q(1),v(K.trim())},300);return()=>window.clearTimeout(u)},[K]),r.useEffect(()=>{O()},[j,g,ce,oe]),r.useEffect(()=>{Promise.all([Ft(),vt()]).then(([u,L])=>{N(u),i(L),Oe(L)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const fe=r.useMemo(()=>new Map(m.map(u=>[u.id,u])),[m]),Ae=u=>{const L=fe.get(u),le=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return le?`${le} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},ne=u=>{const L=fe.get(u);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"},h=async()=>{he(!0);try{const u=await lr(j||void 0,g);await O(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{he(!1)}},f=u=>{U(u),je(null),p(!0)},D=async u=>{var L;re(!0),je(null);try{const le=await nr([b],u),_e=(L=le==null?void 0:le.results)==null?void 0:L[0];_e!=null&&_e.success?(je({success:!0,message:_e.message}),O()):je({success:!1,message:(_e==null?void 0:_e.message)||"发货失败"})}catch(le){je({success:!1,message:(le==null?void 0:le.message)||"请求失败"})}finally{re(!1)}},R=u=>{E(u),Y(!0)},we=u=>{be({...u}),H(!0)},Ce=async()=>{if(!(!P||!P.order_id))try{const u={};P.status!==void 0&&(u.order_status=P.status),P.buyer_id!==void 0&&(u.buyer_id=P.buyer_id),P.amount!==void 0&&(u.amount=P.amount),P.receiver_name!==void 0&&(u.receiver_name=P.receiver_name),P.receiver_phone!==void 0&&(u.receiver_phone=P.receiver_phone),P.receiver_address!==void 0&&(u.receiver_address=P.receiver_address),P.item_id!==void 0&&(u.item_id=P.item_id),P.quantity!==void 0&&(u.quantity=P.quantity),P.item_title!==void 0&&(u.item_title=P.item_title),await sr(P.order_id,u),H(!1),be(null),O()}catch(u){console.error("更新订单失败:",u),alert("更新失败,请重试")}},ke=async()=>{if(Ee){c(!0);try{const u=new FormData;u.append("file",Ee);const L=nn(await ir(u));V(L),Se(null),await O(),L.failed_count===0&&(J(!1),V(null),alert(`订单导入成功,共 ${L.success_count} 条`))}catch(u){alert((u==null?void 0:u.message)||"导入失败,请检查文件格式")}finally{c(!1)}}},De=()=>{ee||(J(!1),Se(null),V(null))},G=async u=>{T(u);try{const L=await rr(u);L.success?await O():alert(L.message||"同步失败")}catch(L){console.error("同步订单失败:",L),alert((L==null?void 0:L.message)||"同步失败,请重试")}finally{T(null)}},ye=async u=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){X(u);try{await ar(u),t.length===1&&ce>1?Q(L=>L-1):await O()}catch(L){console.error("删除订单失败:",L),alert((L==null?void 0:L.message)||"删除失败,请重试"),await O()}finally{X(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:O,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(ze,{className:`w-5 h-5 ${ge?"animate-spin":""}`})}),e.jsxs("button",{onClick:()=>{V(null),J(!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(et,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:h,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(Es,{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-surface-muted",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(u=>e.jsx("button",{onClick:()=>{C(u.k),Q(1),me("")},className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${g===u.k?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:u.v},u.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(xt,{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:u=>{B(u.target.value),Q(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:"全部账号"}),m.map(u=>e.jsx("option",{value:u.id,children:Ae(u.id)},u.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(Nt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:K,onChange:u=>{me(u.target.value),Q(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:t.map(u=>e.jsxs("tr",{className:"hover:bg-warning-50/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:u.item_image?e.jsx("img",{src:u.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(qt,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:de(u.cookie_id,u.item_id,u.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:ne(u.cookie_id),children:[e.jsx(xt,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:ne(u.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",u.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",u.quantity," • ",bs(u.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:u.buyer_id}),u.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:u.receiver_name})]}),u.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:u.receiver_phone})]}),u.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:u.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:u.amount?`¥${u.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(sa,{status:u.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[u.status==="pending_ship"&&e.jsx("button",{onClick:()=>f(u.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=${u.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(_a,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>R(u),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(lt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>we(u),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(_t,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>G(u.order_id),disabled:d===u.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(ze,{className:`w-4 h-4 ${d===u.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>ye(u.order_id),disabled:S===u.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(Ge,{className:"w-4 h-4"})})]})]},u.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:["第 ",ce," 页 / 共 ",te," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:ce<=1,onClick:()=>Q(u=>u-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(Ns,{className:"w-5 h-5"})}),e.jsx("button",{disabled:ce>=te,onClick:()=>Q(u=>u+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(_s,{className:"w-5 h-5"})})]})]})]}),k&&A&&qe.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:()=>Y(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:ne(A.cookie_id),children:ne(A.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(sa,{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:bs(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:de(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:()=>Y(!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:()=>{Y(!1),f(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),ve&&qe.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:De,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:u=>{var L;return Se(((L=u.target.files)==null?void 0:L[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 格式"})]}),Ee&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:Ee.name})]})}),x&&x.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:["导入完成:成功 ",x.success_count," 条,失败 ",x.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:on(x).map((u,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:u.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:u.message||"导入失败"})]},`${u.order_id}-${L}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:De,disabled:ee,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:ke,disabled:!Ee||ee,className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:ee?"正在导入…":"导入订单"})]})})]})}),document.body),M&&qe.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:()=>{p(!1),je(null)},className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:()=>D("status_only"),disabled:q,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(Es,{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:()=>D("full_delivery"),disabled:q,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand 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(qt,{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:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),q&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(ze,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),pe&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${pe.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[pe.success?"✓ ":"✗ ",pe.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:()=>{p(!1),je(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:pe!=null&&pe.success?"完成":"取消"})})]})}),document.body),se&&P&&qe.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:()=>H(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:P.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:P.status,onChange:u=>be({...P,status:u.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:P.buyer_id,onChange:u=>be({...P,buyer_id:u.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:P.amount,onChange:u=>be({...P,amount:u.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:P.receiver_name||"",onChange:u=>be({...P,receiver_name:u.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:P.receiver_phone||"",onChange:u=>be({...P,receiver_phone:u.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:P.receiver_address||"",onChange:u=>be({...P,receiver_address:u.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:P.item_title||"",onChange:u=>be({...P,item_title:u.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:()=>H(!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(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},dn=(t,a,l)=>{const i=l.trim().toLocaleLowerCase();return t.filter(m=>(!a||m.type===a)&&(!i||m.name.toLocaleLowerCase().includes(i)))},aa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),xn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState(!1),[m,N]=r.useState(!1),[_,I]=r.useState(null),[g,C]=r.useState({}),[j,B]=r.useState(aa),[K,me]=r.useState(!1),[oe,v]=r.useState("create"),[F,ce]=r.useState(null),[Q,te]=r.useState(null),[z,ge]=r.useState(!1),[he,k]=r.useState(""),[Y,se]=r.useState(""),[H,ve]=r.useState(null),[J,A]=r.useState(""),[E,P]=r.useState("");r.useEffect(()=>{Xe().then(a)},[]);const be=({type:x})=>{switch(x){case"text":return e.jsx(Ds,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Ts,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(ll,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(os,{className:"w-5 h-5 text-gray-500"})}},Pe=x=>{var V,ee,c,d,T;I(x),C({id:x.id,name:x.name||"",type:x.type||"text",api_url:((V=x.api_config)==null?void 0:V.url)||"",api_method:((ee=x.api_config)==null?void 0:ee.method)||"GET",api_timeout:((c=x.api_config)==null?void 0:c.timeout)||10,api_headers:((d=x.api_config)==null?void 0:d.headers)||"",api_params:((T=x.api_config)==null?void 0:T.params)||"",text_content:x.text_content||"",data_content:x.data_content||"",image_url:x.image_url||"",delay_seconds:x.delay_seconds||0,description:x.description||"",enabled:x.enabled}),i(!0)},ae=async()=>{var x,V,ee,c,d,T,S,X;if(_){if(!((x=g.name)!=null&&x.trim())){alert("请输入卡密名称");return}if(!g.type){alert("请选择卡密类型");return}try{const O={name:g.name.trim(),type:g.type,description:(V=g.description)==null?void 0:V.trim(),delay_seconds:g.delay_seconds||0,enabled:g.enabled??!0};g.type==="api"?O.api_config={url:((ee=g.api_url)==null?void 0:ee.trim())||"",method:g.api_method,timeout:g.api_timeout||10,headers:((c=g.api_headers)==null?void 0:c.trim())||void 0,params:((d=g.api_params)==null?void 0:d.trim())||void 0}:g.type==="text"?O.text_content=((T=g.text_content)==null?void 0:T.trim())||"":g.type==="data"?O.data_content=((S=g.data_content)==null?void 0:S.trim())||"":g.type==="image"&&(O.image_url=((X=g.image_url)==null?void 0:X.trim())||""),await Ks(_.id,O),i(!1),Xe().then(a)}catch(O){console.error("更新卡密失败:",O),alert("更新失败,请重试")}}},M=async x=>{if(confirm("确认删除该卡密吗?"))try{await mr(x),Xe().then(a)}catch(V){console.error("删除卡密失败:",V),alert("删除失败,请重试")}},p=async()=>{if(!j.name.trim()){alert("请输入卡密名称");return}if(!j.content.trim()){alert(j.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const x={name:j.name.trim(),type:j.type,description:j.description.trim(),enabled:j.enabled,delay_seconds:j.delay_seconds};j.type==="text"&&(x.text_content=j.content.trim()),j.type==="data"&&(x.data_content=j.content.trim()),j.type==="image"&&(x.image_url=j.content.trim()),j.type==="api"&&(x.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 xr(x),N(!1),B(aa()),Xe().then(a)}catch(x){console.error("添加卡密失败:",x),alert("添加失败,请重试")}},b=async x=>{try{await Ks(x.id,{...x,enabled:!x.enabled}),Xe().then(a)}catch(V){console.error("切换状态失败:",V)}},U=async x=>{try{await navigator.clipboard.writeText(String(x)),alert(`已复制卡密组ID:${x}`)}catch{prompt("复制卡密组ID",String(x))}},q=t.filter(x=>x.type==="data"),re=r.useMemo(()=>dn(t,J,E),[t,E,J]),pe=()=>{const ee=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 +VIP-MONTH-002 +VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(S=>S.map(X=>`"${String(X).replace(/"/g,'""')}"`).join(",")).join(` +`),c=new Blob(["\uFEFF"+ee],{type:"text/csv;charset=utf-8"}),d=URL.createObjectURL(c),T=document.createElement("a");T.href=d,T.download="卡密组批量导入模板.csv",document.body.appendChild(T),T.click(),T.remove(),URL.revokeObjectURL(d)},je=async()=>{if(F){ge(!0),te(null);try{const x=await pr(F);if(te(x),x.created>0){const V=await Xe();a(V)}}catch(x){te({error:(x==null?void 0:x.message)||"上传失败"})}finally{ge(!1)}}},Ee=async()=>{if(!(!he||!Y.trim())){ge(!0),ve(null);try{const x=await ur(he,Y);ve({added:x.added}),se("");const V=await Xe();a(V)}catch(x){alert("追加失败:"+((x==null?void 0:x.message)||"未知错误"))}finally{ge(!1)}}},Se=()=>{var x;v("create"),ce(null),te(null),k((x=q[0])!=null&&x.id?String(q[0].id):""),se(""),ve(null),me(!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:Se,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(Dt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>N(!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(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:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted 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(wa,{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:J,onChange:x=>A(x.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(Nt,{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:E,onChange:x=>P(x.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:["显示 ",re.length," / ",t.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:re.map(x=>{let V="";return x.type==="data"&&x.data_content?V=`库存: ${x.data_content.split(` +`).filter(c=>c.trim()).length} 条`:x.type==="text"&&x.text_content?V=x.text_content:x.type==="api"&&x.api_config?V=x.api_config.url:x.type==="image"&&x.image_url&&(V="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/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(be,{type:x.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:x.name,children:x.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>U(x.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:x.id}),e.jsx(tl,{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 ${x.type==="text"?"bg-blue-50 text-blue-600":x.type==="data"?"bg-purple-50 text-purple-600":x.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:x.type==="text"?"文本":x.type==="data"?"批量":x.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:V,children:V})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:x.description||"-",children:x.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>b(x),className:`w-12 h-8 rounded-full relative transition-colors ${x.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 ${x.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:()=>Pe(x),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(_t,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>M(x.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ge,{className:"h-4 w-4"})})]})})]},x.id)})})]})}),re.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ja,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&_&&qe.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:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Me,{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:x=>C({...g,name:x.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:x=>C({...g,type:x.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:"批量数据"}),(_==null?void 0:_.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:x=>C({...g,api_url:x.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:x=>C({...g,api_method:x.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:x=>C({...g,api_timeout:parseInt(x.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:x=>C({...g,api_headers:x.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:x=>C({...g,api_params:x.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:x=>C({...g,text_content:x.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:x=>C({...g,data_content:x.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(x=>x.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:x=>C({...g,image_url:x.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:x=>{x.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:x=>C({...g,delay_seconds:parseInt(x.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:x=>C({...g,description:x.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:()=>C({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-brand":"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:()=>i(!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(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),m&&qe.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:()=>N(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Me,{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:x=>B({...j,name:x.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:()=>B({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>B({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ds,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>B({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ts,{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:x=>B({...j,content:x.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:x=>B({...j,content:x.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:x=>B({...j,content:x.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-brand",children:j.content.split(` +`).filter(x=>x.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:x=>B({...j,api_method:x.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:x=>B({...j,api_timeout:parseInt(x.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:x=>B({...j,api_headers:x.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:x=>B({...j,api_params:x.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:x=>B({...j,description:x.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:x=>B({...j,delay_seconds:parseInt(x.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:()=>N(!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:p,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),K&&qe.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:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Me,{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:()=>v("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 ${oe==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(sl,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>v("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 ${oe==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Dt,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),oe==="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:pe,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(al,{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(Dt,{className:"w-4 h-4"}),F?F.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:x=>{var V;return ce(((V=x.target.files)==null?void 0:V[0])||null)}})]})]}),Q&&!Q.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:["共 ",Q.total," 行 · 成功 ",Q.created," · 失败 ",Q.failed]}),Q.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:Q.rows.filter(x=>!x.success).map(x=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",x.row_no," 行「",x.name,"」:",x.error]},x.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:q.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:he,onChange:x=>k(x.target.value),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:q.map(x=>e.jsxs("option",{value:String(x.id),children:[x.name,"(ID: ",x.id,")"]},x.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:Y,onChange:x=>se(x.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:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),H&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",H.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:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),oe==="create"?e.jsxs("button",{onClick:je,disabled:!F||z,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[z?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(Dt,{className:"w-4 h-4"}),z?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ee,disabled:!he||!Y.trim()||z||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:[z?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),z?"处理中...":"追加卡密"]})]})]})}),document.body)]})},mn=t=>t.find(a=>a.status==="running"||a.status==="canceling"),la="ydisks-amap-js-api",pn="c9b68d4ce9a2a97f22a4a439404488ca";let $t=null;const un=()=>pn,hn=()=>window.AMap?Promise.resolve(window.AMap):$t||($t=new Promise((t,a)=>{const l=document.getElementById(la),i=l||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(_)},N=()=>{window.AMap?(m(),t(window.AMap)):(m(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},_=window.setTimeout(()=>{m(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=N,i.id=la,i.async=!0,i.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(un())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,i.onerror=()=>{m(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},l||document.head.appendChild(i)}).catch(t=>{throw $t=null,t}),$t),Ht=t=>Number.isFinite(t)&&t!==0,gn=t=>{var m,N;const a=Number((m=t.location)==null?void 0:m.lng),l=Number((N=t.location)==null?void 0:N.lat),i={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:a,latitude:l,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!i.division_id||!i.province||!i.city||!i.poi_id||!i.poi_name||!Ht(a)||!Ht(l)||a<-180||a>180||l<-90||l>90?null:i},bn=async(t,a)=>{if(!Ht(t)||!Ht(a)||t<-180||t>180||a<-90||a>90)throw new Error("经纬度无效");const l=await hn();return new Promise((i,m)=>{new l.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,a],1e3,(_,I)=>{var C;if(_!=="complete"){if(_==="no_data"){i([]);return}m(new Error("高德地图附近地址查询失败,请稍后重试"));return}const g=(((C=I==null?void 0:I.poiList)==null?void 0:C.pois)||[]).map(gn).filter(j=>j!==null);i(g)})})},fn=t=>{const a=String(t||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},yn=({onConfigureDelivery:t})=>{const[a,l]=r.useState([]),[i,m]=r.useState([]),[N,_]=r.useState([]),[I,g]=r.useState(""),[C,j]=r.useState(""),[B,K]=r.useState(!1),[me,oe]=r.useState(!1),[v,F]=r.useState(!1),[ce,Q]=r.useState(!1),[te,z]=r.useState(!1),[ge,he]=r.useState(!1),[k,Y]=r.useState(!1),[se,H]=r.useState("upload"),[ve,J]=r.useState(null),[A,E]=r.useState(null),[P,be]=r.useState(""),[Pe,ae]=r.useState(!1),[M,p]=r.useState(!1),[b,U]=r.useState([]),[q,re]=r.useState(null),[pe,je]=r.useState([]),[Ee,Se]=r.useState(null),[x,V]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[ee,c]=r.useState(null),[d,T]=r.useState(null),[S,X]=r.useState(null),O=r.useRef(!1),[de,Oe]=r.useState(null),[fe,Ae]=r.useState({}),[ne,h]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[f,D]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[R,we]=r.useState([]);r.useEffect(()=>{if(!ge||f.images.length===0){we([]);return}const n=f.images.map((w,Z)=>({key:w.name+Z,url:URL.createObjectURL(w)}));return we(n),()=>{n.forEach(w=>URL.revokeObjectURL(w.url))}},[ge,f.images]);const Ce=async()=>{const n=await vt();l(n)},ke=async()=>{m(await gs())};r.useEffect(()=>{Promise.all([Ft(),vt(),gs(),Hs(20)]).then(([n,w,Z,Te])=>{_(n),l(w),m(Z);const s=Te.find(o=>["running","canceling"].includes(o.status))||Te.find(o=>o.status!=="preview");X(s||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!k||!(d!=null&&d.id)||!["running","canceling"].includes(d.status))return;const n=window.setInterval(async()=>{if(!O.current){O.current=!0;try{const w=await bt(d.id);T(w),X(w),["running","canceling"].includes(w.status)||(H("done"),await Ce(),await ke())}catch(w){console.error("刷新批量铺货进度失败:",w)}finally{O.current=!1}}},3e3);return()=>{window.clearInterval(n)}},[k,d==null?void 0:d.id,d==null?void 0:d.status]);const De=async()=>{if(!I)return alert("请先选择账号");K(!0);try{const n=await hr(I);await Ce(),alert((n==null?void 0:n.message)||"商品同步完成")}catch(n){console.error("同步商品失败:",n),alert((n==null?void 0:n.message)||"同步失败,请重试")}finally{K(!1)}},G=n=>{Oe(n),Ae({...n}),Q(!0)},ye=async()=>{if(de)try{await kr(de.cookie_id,de.item_id,{item_title:fe.item_title||"",item_description:fe.item_description||"",item_category:fe.item_category||"",item_price:fe.item_price||"",item_detail:fe.item_detail||de.item_detail||""}),await Ce(),await ke(),Q(!1),Oe(null)}catch(n){console.error("更新商品失败:",n),alert("更新失败,请重试")}},u=async n=>{if(confirm(`确认删除商品"${n.item_title}"吗?`))try{await gr(n.cookie_id,n.item_id),l(w=>w.filter(Z=>!(Z.cookie_id===n.cookie_id&&Z.item_id===n.item_id)))}catch(w){console.error("删除商品失败:",w),alert("删除失败,请重试")}},L=async()=>{try{if(!ne.cookie_id||!ne.item_id){alert("请选择账号并填写商品ID");return}await br(ne.cookie_id,{item_id:ne.item_id,item_title:ne.item_title,item_price:ne.item_price,item_detail:ne.item_image?JSON.stringify({item_image:ne.item_image}):""}),await Ce(),z(!1),h({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(n){console.error("添加商品失败:",n),alert("添加失败,请重试")}},le=async()=>{if(!f.cookie_id)return alert("请选择发布账号");if(!f.title.trim())return alert("请填写商品标题");if(!f.price.trim())return alert("请填写商品价格");if(!f.quantity||Number(f.quantity)<=0)return alert("库存数量必须大于 0");if(f.images.length===0)return alert("至少上传 1 张商品图片");if(f.postage_mode==="fixed"&&!f.postage.trim())return alert("请填写一口价邮费");oe(!0);try{const n=await fr({...f,location:q||void 0});if(await Ce(),he(!1),D({cookie_id:I||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),U([]),re(null),n!=null&&n.item_id){const w={id:n.item_id,cookie_id:f.cookie_id,item_id:n.item_id,item_title:n.item_title||f.title,item_price:n.item_price||f.price,item_image:n.item_image};t(w),alert("商品发布成功,ID: "+n.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(n){console.error("发布商品失败:",n);const w=n==null?void 0:n.payload;if((w==null?void 0:w.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((n==null?void 0:n.message)||"发布失败,请重试")}finally{oe(!1)}},_e=async()=>{H("upload"),c(null),T(null),J(null),E(null),be(""),V({catId:"",catName:"",channelCatId:"",tbCatId:""}),je([]),Se(null),Y(!0),F(!0);try{const n=await Hs(20),w=mn(n);if(w!=null&&w.id){const Z=await bt(w.id);X(Z),T(Z),H(["running","canceling"].includes(Z.status)?"running":"done")}}catch(n){console.error("恢复最近批量铺货任务失败:",n)}finally{F(!1)}},Ue=async()=>{const n=P.trim();if(!I)return alert("请先选择默认发布账号");if(!n)return alert("请输入类目关键词");ae(!0);try{const Z=(await yr(I,n)).category;V({catId:Z.cat_id,catName:Z.cat_name,channelCatId:Z.channel_cat_id,tbCatId:Z.tb_cat_id||""})}catch(w){console.error("获取推荐类目失败:",w),alert((w==null?void 0:w.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{ae(!1)}},Fe=async()=>{if(S!=null&&S.id){F(!0),Y(!0);try{const n=await bt(S.id);T(n),H(["running","canceling"].includes(n.status)?"running":"done")}catch(n){console.error("加载最近批量铺货结果失败:",n)}finally{F(!1)}}},tt=async()=>{if(!ve)return alert("请先上传商品表格");if(!I)return alert("请先选择默认发布账号");F(!0);try{const n=await jr({file:ve,imagesZip:A,defaultCookieId:I,fallbackCategory:x,location:Ee||void 0});c(n),T(null),H("preview")}catch(n){console.error("批量铺货预检失败:",n),alert((n==null?void 0:n.message)||"预检失败,请检查表格和图片 zip")}finally{F(!1)}},kt=async()=>{if(ee!=null&&ee.preview_id){if(ee.valid<=0)return alert("没有可发布的商品行");F(!0);try{const n=await _r(ee.preview_id),w=await bt(n.batch_id||ee.preview_id);T(w),X(w),H(w.status==="running"?"running":"done")}catch(n){console.error("启动批量铺货失败:",n),alert((n==null?void 0:n.message)||"启动发布任务失败")}finally{F(!1)}}},Je=async()=>{if(d!=null&&d.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){F(!0);try{const n=await vr(d.id),w=await bt(d.id);T(w),H((n==null?void 0:n.status)==="canceling"||w.status==="canceling"?"running":"done")}catch(n){alert((n==null?void 0:n.message)||"取消失败")}finally{F(!1)}}},We=async()=>{const n=ee==null?void 0:ee.preview_id;if(n&&se==="preview")try{await Nr(n)}catch(w){console.error("清理批量铺货预检失败:",w)}c(null),H("upload")},Ct=async()=>{await We(),Y(!1)},St=async()=>{if(d!=null&&d.id){F(!0);try{await wr(d.id),T(await bt(d.id)),H("running")}catch(n){alert((n==null?void 0:n.message)||"重试失败")}finally{F(!1)}}},mt=()=>{const Z=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","类目ID","类目名称","频道类目ID","淘宝类目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(y=>y.map($=>`"${String($).replace(/"/g,'""')}"`).join(",")).join(` +`),Te=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(Te),o=document.createElement("a");o.href=s,o.download="批量铺货模板.csv",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(s)},Lt=()=>{h(n=>({...n,cookie_id:I||n.cookie_id})),z(!0)},nt=()=>{D(n=>({...n,cookie_id:I||n.cookie_id})),he(!0)},it=async n=>{if(!(n?I:f.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");p(!0),navigator.geolocation.getCurrentPosition(async Z=>{try{const Te=await bn(Z.coords.longitude,Z.coords.latitude);if(!Te.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");n?(je(Te),Se(Te[0])):(U(Te),re(Te[0]))}catch(Te){alert((Te==null?void 0:Te.message)||"获取发货地失败")}finally{p(!1)}},Z=>{p(!1),alert(Z.code===Z.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Ot=n=>i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id).length>0?i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id):i.filter(w=>w.cookie_id===n.cookie_id&&!w.item_id),pt=n=>{switch(n){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 n||"-"}},ut=n=>{switch(n){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"}},st=r.useMemo(()=>new Map(N.map(n=>[n.id,n])),[N]),ht=r.useMemo(()=>C?a.filter(n=>n.cookie_id===C):a,[C,a]),Ke=n=>{const w=st.get(n),Z=(w==null?void 0:w.remark)||(w==null?void 0:w.nickname);return Z?`${Z} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ot=n=>{const w=st.get(n);return(w==null?void 0:w.remark)||(w==null?void 0:w.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(rl,{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:C,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),N.map(n=>e.jsx("option",{value:n.id,children:Ke(n.id)},n.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(xt,{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:I,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),N.map(n=>e.jsx("option",{value:n.id,children:Ke(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:De,disabled:B||!I,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(ze,{className:`w-4 h-4 ${B?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Lt,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(et,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:nt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void _e(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Bt,{className:"w-4 h-4"}),S&&["running","canceling"].includes(S.status)?"继续批量任务":"批量铺货"]}),S&&!["running","canceling"].includes(S.status)&&e.jsx("button",{onClick:()=>void Fe(),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:[ht.map(n=>{const w=Ot(n),Z=w.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:()=>G(n),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-brand hover:text-white transition-colors",title:"编辑",children:e.jsx(_t,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>u(n),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(Ge,{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:[n.item_image?e.jsx("img",{src:n.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(fa,{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:fn(n.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:n.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:ot(n.cookie_id),children:[e.jsx(xt,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:ot(n.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: ",n.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${Z?"text-emerald-600":"text-amber-600"}`,children:[Z?e.jsx(ds,{className:"w-3 h-3"}):e.jsx(nl,{className:"w-3 h-3"}),Z?`${w.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>t(n),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${Z?"bg-gray-900 text-white hover:bg-black":"bg-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(il,{className:"w-3.5 h-3.5"}),Z?"查看发货规则":"关联发货规则"]}),e.jsx(xs,{className:"w-3.5 h-3.5"})]})})]},`${n.cookie_id}-${n.item_id}`)}),ht.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(ya,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),C?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),ce&&de&&qe.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: ",de.item_id]})]}),e.jsx("button",{onClick:()=>Q(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Me,{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:fe.item_title||"",onChange:n=>Ae({...fe,item_title:n.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:fe.item_price||"",onChange:n=>Ae({...fe,item_price:n.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:fe.item_category||"",onChange:n=>Ae({...fe,item_category:n.target.value})}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:fe.item_description||"",onChange:n=>Ae({...fe,item_description:n.target.value})})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:ye,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),te&&qe.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:()=>z(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Me,{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:ne.cookie_id,onChange:n=>h({...ne,cookie_id:n.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),N.map(n=>e.jsx("option",{value:n.id,children:Ke(n.id)},n.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:ne.item_id,onChange:n=>h({...ne,item_id:n.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:ne.item_price,onChange:n=>h({...ne,item_price:n.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:ne.item_title,onChange:n=>h({...ne,item_title:n.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:ne.item_image,onChange:n=>h({...ne,item_image:n.target.value})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:L,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(et,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),ge&&qe.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:()=>he(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Me,{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:f.cookie_id,onChange:n=>{D({...f,cookie_id:n.target.value}),U([]),re(null)},children:[e.jsx("option",{value:"",children:"选择账号"}),N.map(n=>e.jsx("option",{value:n.id,children:Ke(n.id)},n.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:f.title,onChange:n=>D({...f,title:n.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:f.quantity,onChange:n=>D({...f,quantity:n.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:f.description,onChange:n=>D({...f,description:n.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:f.price,onChange:n=>D({...f,price:n.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:f.original_price,onChange:n=>D({...f,original_price:n.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:f.postage_mode,onChange:n=>D({...f,postage_mode:n.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:"无需邮寄"})]})]})]}),f.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:f.postage,onChange:n=>D({...f,postage:n.target.value})})]}),e.jsxs("div",{className:"rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。"})]}),e.jsxs("button",{type:"button",disabled:M||!f.cookie_id,onClick:()=>void it(!1),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(Ms,{className:"h-4 w-4"}),M?"定位中...":"获取当前位置"]})]}),b.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,b.indexOf(q))),onChange:n=>re(b[Number(n.target.value)]||null),children:b.map((n,w)=>e.jsx("option",{value:String(w),children:[n.province,n.city,n.area,n.poi_name].filter(Boolean).join(" ")},`${n.division_id}-${n.poi_id}-${w}`))})]}),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(Bt,{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:f.images.length?"已选择 "+f.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:n=>D({...f,images:Array.from(n.target.files||[]).slice(0,9)})})]}),R.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:R.map(n=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:n.url,alt:"",className:"w-full h-full object-cover"})},n.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:me,onClick:le,className:"w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),me?"正在发布...":"发布到闲鱼"]})})]})}),document.body),k&&qe.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 Ct(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Me,{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(([n,w])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${se===n?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:w},n))}),se==="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:mt,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:I,onChange:n=>{g(n.target.value),je([]),Se(null)},children:[e.jsx("option",{value:"",children:"选择账号"}),N.map(n=>e.jsx("option",{value:n.id,children:Ke(n.id)},n.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-extrabold text-gray-900",children:["默认类目 ",e.jsx("span",{className:"font-medium text-gray-500",children:"(可为空)"})]}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-amber-800",children:"填写后优先使用该类目;留空时由闲鱼根据每件商品自动识别。仍无法识别时,系统最终使用“电子资料”兜底。"})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs("label",{className:"relative flex-1",children:[e.jsx("span",{className:"sr-only",children:"类目关键词"}),e.jsx(Nt,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"w-full ios-input rounded-xl bg-white py-2.5 pl-10 pr-3",placeholder:"输入关键词,例如:课程资料、设计素材",value:P,onChange:n=>be(n.target.value),onKeyDown:n=>{n.key==="Enter"&&(n.preventDefault(),Ue())}})]}),e.jsxs("button",{type:"button",disabled:!I||!P.trim()||Pe,onClick:()=>void Ue(),className:"ios-btn-primary flex min-h-[42px] items-center justify-center gap-2 rounded-xl px-4 text-sm font-bold disabled:opacity-50",children:[e.jsx(Nt,{className:"h-4 w-4"}),Pe?"匹配中...":"获取类目"]})]}),x.catId?e.jsxs("div",{className:"flex min-h-[46px] items-center justify-between gap-3 border-t border-amber-200 pt-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold text-gray-900",children:[e.jsx(ds,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:x.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",x.catId," · 频道 ",x.channelCatId]})]}),e.jsx("button",{type:"button",title:"清除默认类目",onClick:()=>V({catId:"",catName:"",channelCatId:"",tbCatId:""}),className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",children:e.jsx(Me,{className:"h-4 w-4"})})]}):null]}),e.jsxs("div",{className:"rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"批次发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。"})]}),e.jsxs("button",{type:"button",disabled:M||!I,onClick:()=>void it(!0),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(Ms,{className:"h-4 w-4"}),M?"定位中...":"获取当前位置"]})]}),pe.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,pe.indexOf(Ee))),onChange:n=>Se(pe[Number(n.target.value)]||null),children:pe.map((n,w)=>e.jsx("option",{value:String(w),children:[n.province,n.city,n.area,n.poi_name].filter(Boolean).join(" ")},`${n.division_id}-${n.poi_id}-${w}`))})]}),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(Bt,{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:ve?ve.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:n=>{var w;return J(((w=n.target.files)==null?void 0:w[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(Bt,{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:n=>{var w;return E(((w=n.target.files)==null?void 0:w[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","需要指定当前行默认类目时填写","必须和“类目名称、频道类目ID”同时填写;优先于自动识别"],["类目名称","填写了“类目ID”时必填","填写该 ID 对应的准确类目名称"],["频道类目ID","覆盖类目时必填","必须填写闲鱼返回的准确频道类目 ID"],["淘宝类目ID","按闲鱼返回填写","“电子资料”无淘宝类目 ID,保持为空"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([n,w,Z])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:n}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${w==="每个商品都要填"?"text-red-600":w==="可以留空"?"text-gray-500":"text-amber-700"}`,children:w}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:Z})]},n))})]})})]})]}),se==="preview"&&ee&&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:ee.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:ee.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:ee.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("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:ee.rows.map(n=>{var w,Z,Te,s;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:n.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 ${n.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:n.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:n.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",n.price||"-"," / ",n.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((w=n.category)==null?void 0:w.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((Z=n.category)==null?void 0:Z.cat_id)||"失败后使用电子资料"})]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((Te=n.images)==null?void 0:Te.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((s=n.errors)==null?void 0:s.join(";"))||"-"})]},n.row_no)})})]})})]}),(se==="running"||se==="done")&&d&&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 ${ut(d.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:pt(d.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:d.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:d.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:d.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:d.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:"类目策略"}),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:d.rows.map(n=>{var w,Z;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:n.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 ${ut(n.status)}`,children:pt(n.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:n.title}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((w=n.category)==null?void 0:w.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((Z=n.category)==null?void 0:Z.cat_id)||"失败后使用电子资料"})]}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:n.item_url?e.jsx("a",{href:n.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:n.item_id}):n.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:n.error_message||"-"})]},n.id)})})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[se==="upload"&&e.jsxs("button",{disabled:v||!ve||!I,onClick:tt,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(ze,{className:`w-4 h-4 ${v?"animate-spin":""}`}),v?"正在预检...":"开始预检"]}),se==="preview"&&ee&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:v,onClick:()=>void We(),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:v||ee.valid<=0,onClick:kt,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(es,{className:"w-4 h-4"}),v?"启动中...":`确认发布 ${ee.valid} 个商品`]})]}),(se==="running"||se==="done")&&d&&e.jsxs("div",{className:"flex gap-3 w-full",children:[d.status==="running"?e.jsx("button",{disabled:v,onClick:Je,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):d.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/${d.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:"下载结果"}),d.retryable>0&&!["running","canceling"].includes(d.status)&&e.jsxs("button",{disabled:v,onClick:St,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(ze,{className:`w-4 h-4 ${v?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(d.status)&&e.jsx("button",{onClick:()=>{Y(!1),Ce(),ke()},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)]})},ra="https://dashscope.aliyuncs.com/compatible-mode/v1",jn=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],_n=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"]),Nn=()=>{const[t,a]=r.useState(null),[l,i]=r.useState(!1),[m,N]=r.useState(""),[_,I]=r.useState(!1),[g,C]=r.useState([]),[j,B]=r.useState(!1),[K,me]=r.useState(""),[oe,v]=r.useState(!1),F=r.useRef(null),[ce,Q]=r.useState(!1),[te,z]=r.useState(!1),[ge,he]=r.useState(!1),[k,Y]=r.useState(!1),[se,H]=r.useState(!1),[ve,J]=r.useState(null),[A,E]=r.useState({new_username:"",current_password:"",new_password:"",confirm_password:""});r.useEffect(()=>{be(),Oa().then(b=>{b.username&&E(U=>({...U,new_username:b.username||""}))}).catch(()=>{})},[]),r.useEffect(()=>{const b=U=>{var q;(q=F.current)!=null&&q.contains(U.target)||v(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const P=async(b,U=!1)=>{const q=b||t,re=(q==null?void 0:q.ai_api_url)||(q==null?void 0:q.ai_base_url)||ra;B(!0),me("");try{const pe=await qr(re,(q==null?void 0:q.ai_api_key)||"");C(pe),v(U&&pe.length>0),!(q!=null&&q.ai_model)&&pe.length>0&&a(je=>je&&{...je,ai_model:pe[0]})}catch(pe){C([]),v(!1),me(pe.message||"读取模型失败")}finally{B(!1)}},be=()=>{i(!0),N(""),Ra().then(b=>{a(b),P(b)}).catch(b=>{a(null),N(b.message||"加载配置失败")}).finally(()=>i(!1))},Pe=async()=>{if(t){I(!0);try{const b=Object.fromEntries(Object.entries(t).filter(([U,q])=>!_n.has(U)&&q!==void 0&&q!==null));await Pa(b),alert("系统配置已保存")}catch(b){alert("保存失败:"+b.message)}finally{I(!1)}}},ae=async b=>{b.preventDefault(),J(null);const U=A.new_username.trim();if(U.length<3){J({type:"error",text:"用户名至少需要 3 个字符"});return}if(!A.current_password){J({type:"error",text:"请输入当前密码确认身份"});return}if(A.new_password&&A.new_password.length<8){J({type:"error",text:"新密码至少需要 8 个字符"});return}if(A.new_password!==A.confirm_password){J({type:"error",text:"两次输入的新密码不一致"});return}H(!0);try{const q=await Pl({current_password:A.current_password,new_username:U,new_password:A.new_password||void 0});if(!q.success){J({type:"error",text:q.message||"登录凭据更新失败"});return}J({type:"success",text:q.message||"登录凭据已更新"}),window.setTimeout(()=>window.location.reload(),1400)}catch(q){J({type:"error",text:q.message||"登录凭据更新失败"})}finally{H(!1)}};if(!t)return e.jsx("div",{className:"p-8 text-center text-gray-400",children:m||(l?"加载配置中...":"暂无配置")});const M=t.ai_model||"",p=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(js,{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:be,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(ze,{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(ol,{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:t.log_level||"info",onChange:b=>a({...t,log_level:b.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:jn.map(b=>e.jsx("option",{value:b.value,children:b.label},b.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:t.log_format||"text",onChange:b=>a({...t,log_format:b.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:t.renewal_log_retention_days??10,onChange:b=>a({...t,renewal_log_retention_days:parseInt(b.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-brand text-white",children:e.jsx(vs,{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:t.ai_api_url||ra,onChange:b=>a({...t,ai_api_url:b.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:ce?"text":"password",value:t.ai_api_key||"",onChange:b=>a({...t,ai_api_key:b.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:()=>Q(!ce),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:ce?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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:F,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:M,onFocus:()=>g.length>0&&v(!0),onChange:b=>{a({...t,ai_model:b.target.value}),g.length>0&&v(!0)},onKeyDown:b=>{b.key==="Escape"&&v(!1),b.key==="ArrowDown"&&g.length>0&&v(!0)},className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:()=>g.length>0&&v(b=>!b),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(cl,{className:`w-4 h-4 transition-transform ${oe?"rotate-180":""}`})}),oe&&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:p.length>0?p.map(b=>e.jsxs("button",{type:"button",onClick:()=>{a({...t,ai_model:b}),v(!1)},className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:b}),b===M&&e.jsx(Qe,{className:"w-4 h-4 shrink-0 text-brand"})]},b)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:()=>P(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(ze,{className:`w-4 h-4 ${j?"animate-spin":""}`}),"读取模型"]})]}),K?e.jsx("p",{className:"text-xs text-red-500",children:K}):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(Mt,{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:t["captcha.remote_service_url"]||"",onChange:b=>a({...t,"captcha.remote_service_url":b.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:te?"text":"password",value:t["captcha.remote_secret_key"]||"",onChange:b=>a({...t,"captcha.remote_secret_key":b.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:()=>z(!te),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:te?"隐藏秘钥":"显示秘钥",children:te?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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(t["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:b=>a({...t,"captcha.remote_pass_cookies":b.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(qs,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:ae,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(Gt,{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:b=>E({...A,new_username:b.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:ge?"text":"password",value:A.current_password,onChange:b=>E({...A,current_password:b.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:()=>he(!ge),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:ge?"隐藏密码":"显示密码",children:ge?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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:k?"text":"password",value:A.new_password,onChange:b=>E({...A,new_password:b.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:()=>Y(!k),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:k?"隐藏密码":"显示密码",children:k?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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:k?"text":"password",value:A.confirm_password,onChange:b=>E({...A,confirm_password:b.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),ve&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${ve.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(Mt,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:ve.text})]}),e.jsxs("button",{type:"submit",disabled:se||!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(qs,{className:"w-4 h-4"}),se?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:Pe,disabled:_,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(He,{className:"w-6 h-6"}),_?"保存中...":"保存所有配置"]})})]})},ns=(t,a)=>t.allowed_resolutions.includes(a),vn=(t,a)=>({runs:t.runs.filter(l=>!a||l.cookie_id===a),pending_tasks:t.pending_tasks.filter(l=>!a||l.cookie_id===a)}),wn=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",kn=(t,a,l,i,m,N)=>t!==a||l!==i?!1:(N(m),!0),at={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:qt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:dl},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:ka}},Vt=["order_paid","buyer_reviewed","review_missing_timeout"],Cn="亲,商品使用满意的话,麻烦给个评价,谢谢~",Rt=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),Ta=t=>{if(!t)return{};try{const a=JSON.parse(t);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return{}}},ct=(t,a={})=>{const l=Ta(t);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),...a})},Pt=(t,a)=>{var i;const l=((i=at[t])==null?void 0:i.label)||"自动化规则";return a?`${l} - ${a}`:l},na=t=>{const a=(t||"").trim();return a?Object.values(at).some(l=>a===l.label||a.startsWith(`${l.label} -`)):!0},Et=(t,a=0)=>{if(t==="review_missing_timeout")return[{action_type:"send_text",message_template:Cn,enabled:!0,sort_order:1}];const l={action_type:"send_card",card_id:a,delivery_count:1,enabled:!0,sort_order:1};return t==="order_paid"?[l,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[l]},Sn=t=>{var l,i;if(t.trigger_type==="review_missing_timeout")return((i=(l=t.actions)==null?void 0:l.find(m=>m.action_type==="send_text"))==null?void 0:i.message_template)||"发送求评价文案";const a=(t.actions||[]).filter(m=>m.action_type==="send_card");return a.length?a.map(m=>m.card_name||`卡密 ${m.card_id}`).join(" / "):"未配置卡密库存"},ia=(t,a=!1)=>{const l={blue:a?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:a?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:a?"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[t]||l.blue},Ln=t=>t?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Qt=t=>(t==null?void 0:t.nickname)||(t==null?void 0:t.remark)||(t==null?void 0:t.id)||"未知账号",On=t=>t===!0||t===1||t==="1",In=({initialDeliveryTarget:t,onDeliveryTargetHandled:a})=>{var w,Z,Te;const[l,i]=r.useState("automation"),[m,N]=r.useState([]),[_,I]=r.useState({runs:[],pending_tasks:[]}),[g,C]=r.useState([]),[j,B]=r.useState({}),[K,me]=r.useState([]),[oe,v]=r.useState([]),[F,ce]=r.useState([]),[Q,te]=r.useState(!1),[z,ge]=r.useState(""),[he,k]=r.useState(""),[Y,se]=r.useState(""),[H,ve]=r.useState(""),[J,A]=r.useState("all"),[E,P]=r.useState(1),[be,Pe]=r.useState(10),[ae,M]=r.useState(0),[p,b]=r.useState(0),[U,q]=r.useState({}),re=r.useRef(0),pe=r.useRef(0),je=r.useRef("");je.current=z;const[Ee,Se]=r.useState(!1),[x,V]=r.useState(!1),[ee,c]=r.useState(!1),[d,T]=r.useState(null),[S,X]=r.useState(null),[O,de]=r.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""});K.find(s=>s.id===z);const Oe=r.useCallback(async()=>{const[s,o,y,$]=await Promise.all([Ft(),Xe(),vt(),Xs()]);me(s),v(o),ce(y),B($),ge(W=>{var ue;return W||((ue=s[0])==null?void 0:ue.id)||""})},[]),fe=r.useCallback(async()=>{const s=++re.current,o=Or().catch(W=>(console.warn("加载自动化异常列表失败,不阻断规则展示",W),null)),y=await Cr({cookieId:z||void 0,triggerType:H,enabled:J==="all"?void 0:J==="enabled",search:Y,page:E,pageSize:be});if(s!==re.current)return;N(y.data),M(y.total),b(y.total_pages),q(y.trigger_counts||{}),y.page!==E&&P(y.page);const $=await o;s===re.current&&$&&I($)},[E,be,J,H,Y,z]),Ae=r.useCallback(async()=>{const s=z;if(s!==je.current)return;const o=++pe.current;if(C([]),!s)return;const y=await Pr(s);kn(o,pe.current,s,je.current,y,C)},[z]),ne=r.useCallback(async()=>{B(await Xs())},[]),h=r.useCallback(async()=>{te(!0);try{l==="automation"?await fe():l==="reply"?await Ae():await ne()}finally{te(!1)}},[l,fe,ne,Ae]);r.useEffect(()=>{const s=window.setTimeout(()=>{P(1),se(he.trim())},300);return()=>window.clearTimeout(s)},[he]),r.useEffect(()=>{Oe().catch(s=>console.error("加载规则参考数据失败",s))},[Oe]),r.useEffect(()=>{h().catch(s=>console.error("刷新规则页面失败",s))},[h]);const f=r.useMemo(()=>m.filter(s=>!z||s.cookie_id===z),[m,z]),D=r.useMemo(()=>vn(_,z),[_,z]),R=r.useMemo(()=>K.filter(s=>!z||s.id===z),[K,z]),we=r.useMemo(()=>{if(p<=1)return[];const s=Math.max(1,Math.min(E-2,p-4)),o=Math.min(p,s+4);return Array.from({length:o-s+1},(y,$)=>s+$)},[E,p]),Ce=!!(he.trim()||H||J!=="all"),ke=()=>{k(""),se(""),ve(""),A("all"),P(1)},De=r.useMemo(()=>{const s=(d==null?void 0:d.cookie_id)||z;return F.filter(o=>o.cookie_id===s)},[d==null?void 0:d.cookie_id,F,z]),G=r.useMemo(()=>{if(!(!(d!=null&&d.cookie_id)||!(d!=null&&d.item_id)))return F.find(s=>s.cookie_id===d.cookie_id&&s.item_id===d.item_id)},[d==null?void 0:d.cookie_id,d==null?void 0:d.item_id,F]),ye=On(G==null?void 0:G.is_multi_spec),u=(d==null?void 0:d.trigger_type)||"order_paid",L=at[u],le=Ta(d==null?void 0:d.config_json),_e=r.useCallback((s="order_paid",o=z,y="")=>{const $=F.find(ue=>ue.cookie_id===o&&ue.item_id===y),W=($==null?void 0:$.item_title)||y;return{name:Pt(s,W),trigger_type:s,cookie_id:o,item_id:y,item_title:($==null?void 0:$.item_title)||"",item_keyword:W,card_group_id:0,priority:100,enabled:!0,config_json:s==="review_missing_timeout"?ct():"{}",actions:Et(s),variants:s==="review_missing_timeout"?[]:[Rt()]}},[F,z]),Ue=r.useCallback(s=>{var y,$;const o=s.trigger_type||"order_paid";T({...s,trigger_type:o,config_json:o==="review_missing_timeout"?ct(s.config_json):s.config_json||"{}",actions:(y=s.actions)!=null&&y.length?s.actions.map(W=>({...W})):Et(o,s.card_group_id),variants:($=s.variants)!=null&&$.length?s.variants.map(W=>({...W})):o==="review_missing_timeout"?[]:[Rt()]}),Se(!0)},[]);r.useEffect(()=>{if(!t)return;let s=!1;return(async()=>{i("automation"),ge(t.cookieId),te(!0);try{const[y,$,W]=await Promise.all([gs(),vt(),Xe().catch(xe=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",xe),[]))]);if(s)return;N(y),ce($),v(W);const ue=y.find(xe=>xe.cookie_id===t.cookieId&&xe.item_id===t.itemId&&xe.trigger_type==="order_paid");if(ue)Ue(ue);else{const xe=$.find($e=>$e.cookie_id===t.cookieId&&$e.item_id===t.itemId);T({..._e("order_paid",t.cookieId,t.itemId),item_title:(xe==null?void 0:xe.item_title)||"",item_keyword:(xe==null?void 0:xe.item_title)||t.itemId,name:Pt("order_paid",(xe==null?void 0:xe.item_title)||t.itemId)}),Se(!0)}}catch(y){console.error("打开商品自动化规则失败",y),alert("无法加载该商品的自动化规则")}finally{s||(te(!1),a==null||a())}})(),()=>{s=!0}},[_e,t,a,Ue]);const Fe=(s="order_paid")=>{if(!z){alert("请先选择账号");return}T(_e(s)),Se(!0)},tt=s=>{var $,W,ue,xe,$e;if(!d)return;const o=((W=($=d.variants)==null?void 0:$.find(ie=>ie.card_id))==null?void 0:W.card_id)||((xe=(ue=d.actions)==null?void 0:ue.find(ie=>ie.action_type==="send_card"))==null?void 0:xe.card_id)||d.card_group_id||0,y=(G==null?void 0:G.item_title)||d.item_title||d.item_id||"";T({...d,trigger_type:s,name:na(d.name)?Pt(s,y):d.name,card_group_id:o,config_json:s==="review_missing_timeout"?ct(d.config_json):"{}",actions:Et(s,o),variants:s==="review_missing_timeout"?[]:($e=d.variants)!=null&&$e.length?d.variants:[{...Rt(),card_id:o}]})},kt=s=>{if(!d)return;const o=F.find($=>$.cookie_id===(d.cookie_id||z)&&$.item_id===s),y=(o==null?void 0:o.item_title)||s;T({...d,item_id:s,item_title:(o==null?void 0:o.item_title)||"",item_keyword:y,name:na(d.name)?Pt(u,y):d.name})},Je=(w=d==null?void 0:d.variants)!=null&&w.length?d.variants:[Rt()],We=(s,o)=>{var $;if(!d)return;const y=Je.map((W,ue)=>ue===s?{...W,...o}:W);T({...d,variants:y,card_group_id:(($=y[0])==null?void 0:$.card_id)||0})},Ct=()=>{if(!d)return;const s=Je[Je.length-1];T({...d,variants:[...Je,{...Rt(),spec_name:ye&&(s==null?void 0:s.spec_name)||"",spec_value:ye&&(s==null?void 0:s.spec_value)||""}]})},St=async()=>{var $,W,ue,xe,$e;if(!d)return;const s=d.trigger_type||"order_paid";if(!d.cookie_id){alert("请选择账号");return}const o=($=d.variants)!=null&&$.length?d.variants:[];if(s!=="review_missing_timeout"){if(!o.length||o.some(ie=>!ie.card_id)){alert(s==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");return}if(ye&&o.some(ie=>!ie.spec_name.trim()||!ie.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}}if(s==="review_missing_timeout"&&!(((ue=(W=d.actions)==null?void 0:W.find(Ye=>Ye.action_type==="send_text"))==null?void 0:ue.message_template)||"").trim()){alert("请填写求评价文案");return}const y=s==="review_missing_timeout"?[]:o.map(ie=>({...ie,spec_name:ye?ie.spec_name.trim():"",spec_value:ye?ie.spec_value.trim():"",delivery_count:Math.max(1,Number(ie.delivery_count)||1),enabled:ie.enabled!==!1}));try{await Zs({...d,trigger_type:s,name:(d.name||"").trim()||Pt(s,(G==null?void 0:G.item_title)||d.item_id||""),config_json:s==="review_missing_timeout"?ct(d.config_json):d.config_json||"{}",actions:(xe=d.actions)!=null&&xe.length?d.actions:Et(s,(($e=y[0])==null?void 0:$e.card_id)||d.card_group_id||0),variants:y}),Se(!1),await Promise.all([fe(),Oe()]),alert("保存成功")}catch(ie){console.error("保存自动化规则失败:",ie),alert("保存失败:"+ie.message)}},mt=async s=>{if(confirm("确定删除该自动化规则吗?"))try{await Lr(s),await fe(),alert("删除成功")}catch(o){alert("删除失败:"+o.message)}},Lt=async s=>{try{await Zs({...s,enabled:!s.enabled}),await fe()}catch(o){alert("操作失败:"+o.message)}},nt=async(s,o)=>{if(confirm(o==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":o==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Ir(s,o),await fe()}catch($){alert("处理失败:"+$.message)}},it=async(s,o)=>{if(confirm(o==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Ar(s,o),await fe()}catch(y){alert("处理失败:"+y.message)}},Ot=()=>{if(!z){alert("请先选择账号");return}X({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),V(!0)},pt=async()=>{var o,y,$;if(!S||!z)return;const s=S.type==="image"?!!((o=S.image_url)!=null&&o.trim()):!!((y=S.reply_content)!=null&&y.trim());if(!(($=S.keyword)!=null&&$.trim())||!s){alert("请填写关键词和回复内容");return}try{await Er({...S,match_type:"fuzzy",enabled:!0},z),V(!1),await Ae(),alert("保存成功")}catch(W){alert("保存失败:"+W.message)}},ut=async s=>{if(!(!z||!confirm("确定删除该回复规则吗?")))try{await Dr(s,z),await Ae(),alert("删除成功")}catch(o){alert("删除失败:"+o.message)}},st=async(s=z)=>{if(!s){alert("请先选择账号");return}try{const o=await Jr(s);de({cookie_id:s,enabled:o.enabled,reply_content:o.reply_content,reply_once:o.reply_once,reply_image_url:o.reply_image_url||""})}catch{de({cookie_id:s,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}c(!0)},ht=async()=>{if(!O.cookie_id){alert("请先选择账号");return}if(O.enabled&&!O.reply_content.trim()&&!O.reply_image_url.trim()){alert("启用默认回复时,请填写回复内容或图片 URL");return}try{await Vr(O.cookie_id,{enabled:O.enabled,reply_content:O.reply_content,reply_once:O.reply_once,reply_image_url:O.reply_image_url}),c(!1),await ne(),alert("保存成功")}catch(s){alert("保存失败:"+s.message)}},Ke=async s=>{if(confirm("确定删除该账号默认回复吗?"))try{await Qr(s),await ne(),alert("删除成功")}catch(o){alert("删除失败:"+o.message)}},ot=async s=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Gr(s),alert("清空成功")}catch(o){alert("清空失败:"+o.message)}},n=l==="automation"?"新建自动化":l==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"min-w-0 space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row 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:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap gap-3",children:[e.jsxs("select",{value:z,onChange:s=>{ge(s.target.value),P(1)},className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),K.map(s=>e.jsx("option",{value:s.id,children:Qt(s)},s.id))]}),e.jsxs("button",{onClick:h,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 whitespace-nowrap transition-colors",children:[e.jsx(ze,{className:`w-4 h-4 ${Q?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:l==="automation"?()=>Fe("order_paid"):l==="reply"?Ot:()=>void st(),disabled:!z,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50",children:[e.jsx(et,{className:"w-4 h-4"}),n]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:cs},{id:"reply",label:"关键词回复",icon:Tt},{id:"default",label:"账号默认回复",icon:yt}].map(s=>{const o=s.icon;return e.jsxs("button",{onClick:()=>i(s.id),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${l===s.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(o,{className:"w-4 h-4"}),s.label]},s.id)})}),l==="automation"&&(D.runs.length>0||D.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(rt,{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:[D.runs.map(s=>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:["账号 ",s.cookie_id," · 订单 ",s.order_id||"-"," · 已记录发送 ",s.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:wn(s.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:s.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[ns(s,"continue")&&e.jsx("button",{onClick:()=>void nt(s.id,"continue"),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),ns(s,"retry")&&e.jsx("button",{onClick:()=>void nt(s.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),ns(s,"cancel")&&e.jsx("button",{onClick:()=>void nt(s.id,"cancel"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${s.id}`)),D.pending_tasks.map(s=>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:["账号 ",s.cookie_id," · 延迟任务重试已达 ",s.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:s.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>void it(s.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 it(s.id,"dismiss"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${s.id}`))]})]}),l==="automation"&&e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]",children:[e.jsxs("aside",{className:"min-w-0 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:Vt.map(s=>{const o=at[s],y=o.icon;return e.jsx("button",{type:"button",onClick:()=>Fe(s),className:`w-full text-left rounded-2xl border p-4 transition-colors ${ia(o.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(y,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:o.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:o.description})]})]})},s)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"font-black text-gray-900",children:"筛选结果构成"}),e.jsxs("span",{className:"text-xs font-bold text-gray-400",children:["共 ",ae," 条"]})]}),e.jsx("div",{className:"space-y-3",children:Vt.map(s=>{const o=at[s],y=o.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(y,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:o.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:U[s]||0})]},s)})})]})]}),e.jsxs("section",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-surface-muted p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(Nt,{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:"搜索规则名、商品名或商品 ID...",value:he,onChange:s=>{k(s.target.value),P(1)},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:"relative xl:w-52",children:[e.jsx(wa,{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:H,onChange:s=>{ve(s.target.value),P(1)},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:"全部自动化类型"}),Vt.map(s=>e.jsx("option",{value:s,children:at[s].shortLabel},s))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:J,onChange:s=>{A(s.target.value),P(1)},className:"ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36",children:[e.jsx("option",{value:"all",children:"全部状态"}),e.jsx("option",{value:"enabled",children:"已启用"}),e.jsx("option",{value:"disabled",children:"已禁用"})]}),Ce&&e.jsx("button",{type:"button",onClick:ke,className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900",title:"清除筛选","aria-label":"清除筛选",children:e.jsx(Me,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs font-bold text-gray-400",children:[e.jsxs("span",{children:["找到 ",ae," 条规则"]}),Q&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ze,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),Q&&f.length===0?e.jsxs("div",{className:"flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400",children:[e.jsx(ze,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):f.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(cs,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:Ce?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:Ce?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):f.map(s=>{const o=at[s.trigger_type],y=o.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 ${ia(o.accent,!0)}`,children:e.jsx(y,{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:s.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Ln(s.enabled)}`,children:s.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:o.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:s.item_title||s.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:Sn(s)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:()=>Ue(s),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(_t,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:()=>Lt(s),className:`px-4 py-2 rounded-xl text-sm font-bold ${s.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:s.enabled?"禁用":"启用"}),e.jsx("button",{onClick:()=>mt(s.id),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ge,{className:"w-4 h-4"})})]})]})},s.id)}),ae>0&&e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm font-medium text-gray-500",children:[e.jsxs("span",{children:["第 ",E," / ",Math.max(p,1)," 页"]}),e.jsx("span",{className:"h-4 w-px bg-gray-200"}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"sr-only",children:"每页显示数量"}),e.jsx("select",{value:be,onChange:s=>{Pe(Number(s.target.value)),P(1)},className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(s=>e.jsxs("option",{value:s,children:[s," 条/页"]},s))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:E<=1||Q,onClick:()=>P(s=>Math.max(1,s-1)),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"上一页",title:"上一页",children:e.jsx(Ns,{className:"h-4 w-4"})}),we.map(s=>e.jsx("button",{type:"button",disabled:Q,onClick:()=>P(s),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${s===E?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${s} 页`,"aria-current":s===E?"page":void 0,children:s},s)),e.jsx("button",{type:"button",disabled:E>=p||Q,onClick:()=>P(s=>Math.min(p,s+1)),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"下一页",title:"下一页",children:e.jsx(_s,{className:"h-4 w-4"})})]})]})]})]}),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(rt,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[g.map(s=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle 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:["“",s.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:s.type==="image"&&s.image_url?s.image_url:s.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({...s}),V(!0)},className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(_t,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>ut(s.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ge,{className:"w-5 h-5"})})]})]},s.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(rt,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[R.map(s=>{const o=j[s.id],y=!!(o!=null&&o.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 ${y?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-surface-subtle 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 ${y?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(yt,{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:Qt(s)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${y?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:y?"已启用":"未启用"}),(o==null?void 0:o.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:y?o.reply_content||o.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 st(s.id),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(_t,{className:"w-4 h-4"})}),y&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>void ot(s.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 Ke(s.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ge,{className:"w-5 h-5"})})]})]})]},s.id)}),R.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),Ee&&d&&qe.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:d.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:L.description})]}),e.jsx("button",{onClick:()=>Se(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(Me,{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:Vt.map(s=>{const o=at[s],y=o.icon,$=u===s;return e.jsx("button",{type:"button",onClick:()=>tt(s),className:`w-full rounded-2xl p-4 text-left border transition-all ${$?"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(y,{className:`w-5 h-5 mt-0.5 ${$?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:o.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${$?"text-gray-500":"text-gray-400"}`,children:o.description})]})]})},s)})}),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:L.flow.map((s,o)=>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:o+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:s})]},s))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-surface-subtle",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(ds,{className:"w-5 h-5 text-brand"}),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:d.name||"",onChange:s=>T({...d,name:s.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:d.cookie_id||"",onChange:s=>T({...d,cookie_id:s.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:"选择账号"}),K.map(s=>e.jsx("option",{value:s.id,children:Qt(s)},s.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:d.item_id||"",onChange:s=>kt(s.target.value),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),De.map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.item_id}`))]})]})]}),G&&u!=="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:G.item_title||G.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${ye?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:ye?"多规格商品":"普通商品"}),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:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),u!=="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(xl,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:u==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:ye?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:Ct,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(et,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:Je.map((s,o)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${ye?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[ye&&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:s.spec_name,onChange:y=>We(o,{spec_name:y.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:s.spec_value,onChange:y=>We(o,{spec_value:y.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:s.card_id||"",onChange:y=>We(o,{card_id:Number(y.target.value)}),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),oe.filter(y=>y.enabled&&y.type!=="api").map(y=>e.jsx("option",{value:y.id,children:y.name},y.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:s.delivery_count,onChange:y=>We(o,{delivery_count:Math.max(1,Number(y.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:s.delay_override===!0,onChange:y=>We(o,{delay_override:y.target.checked}),className:"accent-brand"}),"覆盖卡密默认延时"]}),s.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:s.delay_seconds||0,onChange:y=>We(o,{delay_seconds:Math.max(0,Number(y.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:s.delay_override?`本动作延时 ${s.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:Je.length===1,onClick:()=>T({...d,variants:Je.filter((y,$)=>$!==o)}),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(Ge,{className:"w-4 h-4"})})]},s.id||o))})]}):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(ka,{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(le.after_shipped_hours||72),onChange:s=>T({...d,config_json:ct(d.config_json,{after_shipped_hours:Math.max(1,Number(s.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(le.repeat_interval_hours||24),onChange:s=>T({...d,config_json:ct(d.config_json,{repeat_interval_hours:Math.max(1,Number(s.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(le.max_attempts||1),onChange:s=>T({...d,config_json:ct(d.config_json,{max_attempts:Math.max(1,Number(s.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:((Te=(Z=d.actions)==null?void 0:Z.find(s=>s.action_type==="send_text"))==null?void 0:Te.message_template)||"",onChange:s=>{var o;return T({...d,actions:((o=d.actions)!=null&&o.length?d.actions:Et("review_missing_timeout")).map(y=>y.action_type==="send_text"?{...y,message_template:s.target.value}:y)})},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:d.priority||100,onChange:s=>T({...d,priority:Number(s.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:d.enabled!==!1,onChange:s=>T({...d,enabled:s.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:()=>Se(!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:St,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),x&&S&&qe.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:S.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:()=>V(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{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:S.item_id||"",onChange:s=>X({...S,item_id:s.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),F.filter(s=>!z||s.cookie_id===z).map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.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:S.type||"text",onChange:s=>{const o=s.target.value;X({...S,type:o,reply_content:o==="text"?S.reply_content:"",image_url:o==="image"?S.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:S.keyword||"",onChange:s=>X({...S,keyword:s.target.value}),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),S.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:S.image_url||"",onChange:s=>X({...S,image_url:s.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:S.reply_content||"",onChange:s=>X({...S,reply_content:s.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:()=>V(!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:pt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),ee&&qe.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:()=>c(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(Me,{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:O.cookie_id,onChange:s=>de({...O,cookie_id:s.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),K.map(s=>e.jsx("option",{value:s.id,children:Qt(s)},s.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:()=>de({...O,enabled:!O.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${O.enabled?"bg-brand":"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 ${O.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:O.reply_content,onChange:s=>de({...O,reply_content:s.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:O.reply_image_url,onChange:s=>de({...O,reply_image_url:s.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:O.reply_once,onChange:s=>de({...O,reply_once:s.target.checked}),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",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:ht,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})},An=t=>{const a=String(t.smtp_from||"").trim(),l=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a);return{...t,smtp_from_name:t.smtp_from_name||(l?"":a),smtp_from_address:t.smtp_from_address||(l?a:t.smtp_user||""),smtp_use_tls:oa(t.smtp_use_tls,!0),smtp_use_ssl:oa(t.smtp_use_ssl,!1)}},oa=(t,a)=>{if(typeof t=="boolean")return t;if(typeof t=="string"){if(["true","1","yes","on"].includes(t.toLowerCase()))return!0;if(["false","0","no","off"].includes(t.toLowerCase()))return!1}return a},ks=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],fs=(t,a)=>{if(typeof t=="boolean")return t;if(typeof t=="string"){if(["true","1","yes","on"].includes(t.toLowerCase()))return!0;if(["false","0","no","off"].includes(t.toLowerCase()))return!1}return a},Ma=t=>{const a=Object.prototype.hasOwnProperty.call(t,"use_custom_smtp"),l=ks.some(i=>String(t[i]??"").trim()!=="");return{...t,use_custom_smtp:a?fs(t.use_custom_smtp,!1):l}},ca=(t,a)=>{const l={...t,use_custom_smtp:!0};for(const i of ks)String(l[i]??"").trim()===""&&a[i]!==void 0&&(l[i]=a[i]);return l.smtp_port||(l.smtp_port=587),l.smtp_from_address||(l.smtp_from_address=l.smtp_user||""),l.smtp_use_tls=fs(l.smtp_use_tls,!0),l.smtp_use_ssl=fs(l.smtp_use_ssl,!1),l},$n=t=>{const a=Ma(t),l={to_email:String(a.to_email??"").trim(),use_custom_smtp:a.use_custom_smtp===!0};if(l.use_custom_smtp)for(const i of ks)l[i]=a[i];return l},ft={bark:{label:"Bark",icon:jt,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:"Ydisks闲鱼助手"},{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:Tt,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:Tt,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:Tt,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:ml,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:Zt,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:Ca,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},qa=[{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:"后台任务或系统级异常"}],Rn=t=>!t||t.length===0?"全部事件":t.map(l=>{var i;return((i=qa.find(m=>m.value===l))==null?void 0:i.label)||l}).join("、"),Pn=({isAdmin:t=!1})=>{const[a,l]=r.useState([]),[i,m]=r.useState(!0),[N,_]=r.useState(!1),[I,g]=r.useState(null),[C,j]=r.useState(!1),[B,K]=r.useState(""),[me,oe]=r.useState(null),[v,F]=r.useState({}),[ce,Q]=r.useState(!1),[te,z]=r.useState(!1),[ge,he]=r.useState(!1),[k,Y]=r.useState({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),se=async()=>{m(!0);try{const p=await Da();l(p.data||[])}catch(p){console.error("加载通知渠道失败",p)}finally{m(!1)}},H=async()=>{try{const p=await Ra();F(An(p||{}))}catch(p){console.error("加载 SMTP 配置失败",p)}},ve=async()=>{Q(!0);try{await Pa({smtp_server:v.smtp_server||"",smtp_port:v.smtp_port||587,smtp_user:v.smtp_user||"",smtp_password:v.smtp_password||"",smtp_from_name:v.smtp_from_name||"",smtp_from_address:v.smtp_from_address||v.smtp_user||"",smtp_use_tls:v.smtp_use_tls!==!1,smtp_use_ssl:v.smtp_use_ssl===!0}),J("success","SMTP 配置已保存")}catch(p){J("error",(p==null?void 0:p.message)||"保存失败")}finally{Q(!1)}};r.useEffect(()=>{se(),t?H():F({})},[t]);const J=(p,b)=>{oe({type:p,text:b}),window.setTimeout(()=>oe(null),3e3)},A=()=>{g(null),Y({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),he(!1),_(!0)},E=p=>{g(p);const b=p.type==="email"?Ma({...p.config||{}}):null,U=b?b.use_custom_smtp===!0?ca(b,v):b:{...p.config||{}};Y({name:p.name,type:p.type,enabled:p.enabled,config:U,event_types:p.event_types||[]}),he(!1),_(!0)},P=async()=>{const p=ft[k.type];for(const U of p.fields)if(U.required&&!String(k.config[U.key]||"").trim()){J("error",`请填写 ${U.label}`);return}if(!k.name.trim()){J("error","请填写渠道名称");return}let b=k.config;if(k.type==="email"&&(b=$n(k.config),b.use_custom_smtp)){const q=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([re])=>!String(b[re]||"").trim());if(q){J("error",`请填写 ${q[1]}`);return}}j(!0);try{const U={name:k.name.trim(),type:k.type,config:b,event_types:k.event_types,enabled:k.enabled};I?await Ys(I.id,U):await Br(U),_(!1),await se(),J("success",I?"已更新":"已创建")}catch(U){console.error("保存失败",U),J("error",(U==null?void 0:U.message)||"保存失败")}finally{j(!1)}},be=async p=>{if(confirm(`确认删除渠道「${p.name}」吗?已绑定该渠道的账号会自动解绑。`))try{await zr(p.id),await se(),J("success","已删除")}catch(b){J("error",(b==null?void 0:b.message)||"删除失败")}},Pe=async p=>{try{await Ys(p.id,{enabled:!p.enabled}),l(b=>b.map(U=>U.id===p.id?{...U,enabled:!U.enabled}:U))}catch(b){J("error",(b==null?void 0:b.message)||"切换失败")}},ae=async p=>{K(p.id);try{await Wr(p.id),J("success","测试通知已发送,请检查对应渠道")}catch(b){J("error",(b==null?void 0:b.message)||"发送失败")}finally{K("")}},M=ft[k.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:se,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(ze,{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(et,{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(jt,{className:"w-5 h-5 text-brand 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:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),i?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Re,{className:"w-8 h-8 text-brand animate-spin"})}):a.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(jt,{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:a.map(p=>{const b=ft[p.type]||ft.webhook,U=b.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(U,{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:p.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:b.label}),!p.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:b.fields.map(q=>{var re;return(re=p.config)==null?void 0:re[q.key]}).filter(Boolean).map((q,re)=>e.jsx("span",{className:"mr-3",children:String(q).length>40?String(q).slice(0,40)+"…":String(q)},re))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Rn(p.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:()=>Pe(p),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${p.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:p.enabled?"启用中":"已停用"}),e.jsxs("button",{onClick:()=>ae(p),disabled:B===p.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[B===p.id?e.jsx(Re,{className:"w-3 h-3 animate-spin"}):e.jsx(Zt,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{onClick:()=>E(p),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(va,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>be(p),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(Ge,{className:"w-4 h-4"})})]})]},p.id)})}),t&&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(Ca,{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:v.smtp_server||"",onChange:p=>F({...v,smtp_server:p.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:v.smtp_port||587,onChange:p=>F({...v,smtp_port:parseInt(p.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:v.smtp_user||"",onChange:p=>F({...v,smtp_user:p.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:te?"text":"password",value:v.smtp_password||"",onChange:p=>F({...v,smtp_password:p.target.value}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>z(!te),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:te?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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:v.smtp_from_name||"",onChange:p=>F({...v,smtp_from_name:p.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:v.smtp_from_address||v.smtp_user||"",onChange:p=>F({...v,smtp_from_address:p.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:v.smtp_use_tls!==!1,onChange:p=>F({...v,smtp_use_tls:p.target.checked,smtp_use_ssl:p.target.checked?!1:v.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:v.smtp_use_ssl===!0,onChange:p=>F({...v,smtp_use_ssl:p.target.checked,smtp_use_tls:p.target.checked?!1:v.smtp_use_tls})}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:ve,disabled:ce,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[ce?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),ce?"保存中...":"保存 SMTP 配置"]})]}),N&&qe.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:I?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:()=>_(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Me,{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:k.name,onChange:p=>Y({...k,name:p.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(ft).map(p=>{const b=ft[p],U=b.icon,q=k.type===p;return e.jsxs("button",{type:"button",onClick:()=>Y({...k,type:p,config:{}}),className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${q?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(U,{className:`w-5 h-5 ${q?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${q?"text-brand":"text-gray-600"}`,children:b.label})]},p)})})]}),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(jt,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",M.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:M.guide.steps.map((p,b)=>e.jsx("li",{children:p},b))}),M.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:M.guide.urlFormat})]}),M.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",M.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:M.fields.map(p=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[p.label,p.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{type:p.type==="password"?"password":p.type==="number"?"number":"text",value:String(k.config[p.key]||""),onChange:b=>Y({...k,config:{...k.config,[p.key]:b.target.value}}),placeholder:p.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),p.help&&e.jsx("p",{className:"text-xs text-gray-500",children:p.help})]},p.key))}),k.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:k.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:()=>{const p=k.config.use_custom_smtp===!0;Y({...k,config:p?{...k.config,use_custom_smtp:!1}:ca(k.config,v)})},className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${k.config.use_custom_smtp===!0?"bg-brand":"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 ${k.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),k.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(k.config.smtp_server||""),onChange:p=>Y({...k,config:{...k.config,smtp_server:p.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(k.config.smtp_port||587),onChange:p=>Y({...k,config:{...k.config,smtp_port:p.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(k.config.smtp_user||""),onChange:p=>Y({...k,config:{...k.config,smtp_user:p.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:ge?"text":"password",value:String(k.config.smtp_password||""),onChange:p=>Y({...k,config:{...k.config,smtp_password:p.target.value}}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>he(p=>!p),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:ge?e.jsx(dt,{className:"w-4 h-4"}):e.jsx(lt,{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(k.config.smtp_from_name||""),onChange:p=>Y({...k,config:{...k.config,smtp_from_name:p.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(k.config.smtp_from_address||""),onChange:p=>Y({...k,config:{...k.config,smtp_from_address:p.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:k.config.smtp_use_tls!==!1,onChange:p=>Y({...k,config:{...k.config,smtp_use_tls:p.target.checked,smtp_use_ssl:p.target.checked?!1:k.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:k.config.smtp_use_ssl===!0,onChange:p=>Y({...k,config:{...k.config,smtp_use_ssl:p.target.checked,smtp_use_tls:p.target.checked?!1:k.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:qa.map(p=>{const b=k.event_types.includes(p.value);return e.jsxs("button",{type:"button",onClick:()=>{const U=b?k.event_types.filter(q=>q!==p.value):[...k.event_types,p.value];Y({...k,event_types:U})},className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${b?"border-brand 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 ${b?"bg-brand border-brand":"border-gray-300"}`,children:b&&e.jsx(Qe,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${b?"text-brand":"text-gray-800"}`,children:p.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:p.description})]},p.value)})})]}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:()=>Y({...k,enabled:!k.enabled}),className:`relative w-11 h-6 rounded-full transition-colors ${k.enabled?"bg-brand":"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 ${k.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:()=>_(!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:P,disabled:C,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[C?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(Qe,{className:"w-4 h-4"}),C?"保存中...":"保存"]})]})]})}),document.body),me&&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 text-white ${me.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[me.type==="success"?e.jsx(Qe,{className:"w-4 h-4"}):e.jsx(Me,{className:"w-4 h-4"}),me.text]})]})},Fa=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"],["流汗","https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"],["憨笑","https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"],["耶","https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"],["奋斗","https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"],["咒骂","https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"],["疑问","https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"],["嘘","https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"],["晕","https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"],["开心到模糊","https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"],["衰","https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"],["委屈","https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"],["再见","https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"],["鼓掌","https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"],["吐","https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"],["坏笑","https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"],["抠鼻","https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"],["叹气","https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"],["无聊","https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"],["思考","https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"],["呆","https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["哇哦","https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"],["飞吻","https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"],["好喜欢","https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"],["拜托","https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"],["真棒","https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"],["流鼻血","https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"],["费解","https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"],["秃头","https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"],["嘿哈","https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"],["吃土","https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"],["机智","https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"],["举杯","https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"],["握手","https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"],["挥手","https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"],["yeah","https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"],["666","https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"],["棒","https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"],["爱你","https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"],["比心","https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"],["感谢","https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"],["拍手","https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"],["拉钩","https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"],["没钱","https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"],["小刀","https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"],["不刀","https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"],["同出","https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"],["递钱","https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"],["数钱","https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"],["打call","https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"],["号外","https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"],["包邮","https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"],["求赞","https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"],["非主流","https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"],["吃瓜","https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"],["种草","https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"],["佛系","https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"],["超便宜","https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"],["拥抱","https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"],["摊手","https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"],["举手","https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"],["蹲","https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"],["跪了","https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"],["拜","https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"],["排","https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"],["旺财","https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"],["招财猫","https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"],["酸了","https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"],["鸭鸭","https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"],["方了","https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"],["白菜","https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"],["桃子","https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"],["打包","https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"],["沙发","https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["南","https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"],["盯","https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"],["hot","https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"],["new","https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"],["cool","https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"],["1","https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"],["可","https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"],["搬砖","https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"],["菜狗","https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"],["开心面具","https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"],["快递","https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["裂开","https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"],["啤酒","https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"],["瑞思拜","https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"],["小丑","https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"],["爱心","https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"]],En=t=>t,Dn=new Map(Fa.map(([t,a])=>[t,a])),da=t=>t.split(/(\[[^\]]+\])/g).map((a,l)=>{const i=a.startsWith("[")?Dn.get(a.slice(1,-1)):void 0;return i?e.jsx("img",{src:i,alt:a,title:a,className:"mx-0.5 inline-block h-7 w-7 align-middle"},l):e.jsx(ys.Fragment,{children:a},l)}),xa="ydisks.chat.account.v1",ma=t=>{const a=Number.isFinite(t)?Math.max(0,Math.floor(t)):0;return a>99?"99+":String(a)},pa=({count:t,className:a=""})=>!Number.isFinite(t)||t<=0?null:e.jsx("span",{"aria-label":`未读消息 ${ma(t)} 条`,className:`inline-flex h-5 min-w-5 shrink-0 items-center justify-center whitespace-nowrap rounded-full bg-red-500 px-1.5 text-[10px] font-bold leading-none text-white ${a}`,children:ma(t)}),Tn=t=>{if(!t)return"";const a=new Date(t<1e10?t*1e3:t),l=new Date;return a.toDateString()===l.toDateString()?a.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):a.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},ua=t=>new Date(t<1e10?t*1e3:t).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),Mn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState(""),[m,N]=r.useState({}),[_,I]=r.useState(""),[g,C]=r.useState([]),[j,B]=r.useState(""),[K,me]=r.useState(!1),[oe,v]=r.useState(""),[F,ce]=r.useState(!0),[Q,te]=r.useState(!1),[z,ge]=r.useState(!1),[he,k]=r.useState(!1),[Y,se]=r.useState(),[H,ve]=r.useState({}),[J,A]=r.useState({}),[E,P]=r.useState(!1),[be,Pe]=r.useState(!1),[ae,M]=r.useState(!1),[p,b]=r.useState(""),[U,q]=r.useState("connecting"),re=r.useRef(""),pe=r.useRef(""),je=r.useRef(null),Ee=r.useRef({accountID:"",chatID:""}),Se=r.useRef(!0),x=r.useRef(!1),V=r.useRef(null),ee=r.useRef(new Set);r.useEffect(()=>{re.current=l},[l]),r.useEffect(()=>{pe.current=_},[_]);const c=async h=>{const f=await as(h,void 0,void 0,!0),D=f.sessions.map(R=>h===re.current&&R.chat_id===pe.current?{...R,unread_count:0}:R);return N(R=>({...R,[h]:D})),ve(R=>({...R,[h]:f.next_cursor})),A(R=>({...R,[h]:f.has_more})),D};r.useEffect(()=>{let h=!1;return(async()=>{var D;ce(!0);try{const[R,we]=await Promise.all([Ft(),hs()]),ke=R.map(u=>{var L,le;return{...u,runtime_state:((L=we[u.id])==null?void 0:L.state)||(u.enabled?"connecting":"disabled"),runtime_connected:((le=we[u.id])==null?void 0:le.connected)===!0}}).filter(u=>u.enabled),De=await Promise.all(ke.map(async u=>[u.id,await as(u.id)]));if(h)return;a(ke),N(Object.fromEntries(De.map(([u,L])=>[u,L.sessions]))),ve(Object.fromEntries(De.map(([u,L])=>[u,L.next_cursor]))),A(Object.fromEntries(De.map(([u,L])=>[u,L.has_more])));const G=window.localStorage.getItem(xa)||"",ye=ke.some(u=>u.id===G)?G:((D=ke[0])==null?void 0:D.id)||"";i(ye)}catch(R){h||b(R instanceof Error?R.message:"加载聊天数据失败")}finally{h||ce(!1)}})(),()=>{h=!0}},[]),r.useEffect(()=>{let h=!1,f=0,D=null;const R=async()=>{D=new AbortController;try{const we=await hs({signal:D.signal,timeoutMs:1e4});h||a(Ce=>Ce.map(ke=>{var De,G;return{...ke,runtime_state:((De=we[ke.id])==null?void 0:De.state)||ke.runtime_state,runtime_connected:((G=we[ke.id])==null?void 0:G.connected)??ke.runtime_connected}}))}catch{}finally{h||(f=window.setTimeout(R,3e3))}};return f=window.setTimeout(R,3e3),()=>{h=!0,window.clearTimeout(f),D==null||D.abort()}},[]),r.useEffect(()=>{if(!l)return;window.localStorage.setItem(xa,l);const h=m[l]||[];I(f=>{var D;return h.some(R=>R.chat_id===f)?f:((D=h[0])==null?void 0:D.chat_id)||""})},[l,m]),r.useEffect(()=>{!l||ee.current.has(l)||(ee.current.add(l),c(l).catch(h=>{b(h instanceof Error?h.message:"同步会话失败")}))},[l]),r.useEffect(()=>{if(!l||!_){C([]);return}const h=new AbortController;return N(f=>({...f,[l]:(f[l]||[]).map(D=>D.chat_id===_?{...D,unread_count:0}:D)})),te(!0),us(l,_,void 0,void 0,{signal:h.signal}).then(f=>{const D=f.messages.filter(R=>R.direction==="incoming"&&R.message_type!=="system"&&!R.message_key.startsWith("in-")).map(R=>({messageId:R.message_key,sessionId:_,cid:`${_}@goofish`,conversationType:1}));console.info("[聊天已读] 打开会话上报",{accountID:l,chatID:_,messageCount:D.length,messageIds:D.map(R=>R.messageId)}),Qs(l,_,D),C(f.messages),k(f.has_more),se(f.next_cursor),f.session&&N(R=>({...R,[l]:(R[l]||[]).map(we=>{var Ce;return we.chat_id===((Ce=f.session)==null?void 0:Ce.chat_id)?f.session:we})})),N(R=>({...R,[l]:(R[l]||[]).map(we=>we.chat_id===_?{...we,unread_count:0}:we)}))}).catch(f=>{h.signal.aborted||b(f instanceof Error?f.message:"加载消息失败")}).finally(()=>{h.signal.aborted||te(!1)}),()=>h.abort()},[l,_]);const d=async()=>{var D;if(!l||!_||z||!he)return;const h=je.current,f=(h==null?void 0:h.scrollHeight)||0;x.current=!0,ge(!0),b("");try{const R=(D=g[0])==null?void 0:D.id,we=await us(l,_,Y,R);C(Ce=>{const ke=new Set(Ce.map(De=>De.message_key));return[...we.messages.filter(De=>!ke.has(De.message_key)),...Ce]}),k(we.has_more),se(we.next_cursor),requestAnimationFrame(()=>{h&&(h.scrollTop+=h.scrollHeight-f)})}catch(R){x.current=!1,b(R instanceof Error?R.message:"加载历史消息失败")}finally{ge(!1)}};r.useEffect(()=>{let h=!1,f=0,D=0,R=null;const we=()=>{if(h)return;q("connecting");const Ce=window.location.protocol==="https:"?"wss:":"ws:";R=new WebSocket(`${Ce}//${window.location.host}/api/chat/ws`),R.onopen=()=>{D=0,q("online")},R.onmessage=ke=>{try{const G=JSON.parse(ke.data).message;if(!G)return;const ye=G.account_id;if(N(u=>{const L=u[ye]||[];return L.some(_e=>_e.chat_id===G.chat_id)?{...u,[ye]:L.map(_e=>_e.chat_id===G.chat_id?{..._e,last_message:G.content,last_message_at:G.sent_at,unread_count:G.direction==="incoming"&&G.message_type!=="system"&&(re.current!==ye||pe.current!==G.chat_id)?_e.unread_count+1:_e.unread_count}:_e).sort((_e,Ue)=>Ue.last_message_at-_e.last_message_at)}:(c(ye),u)}),re.current===ye&&pe.current===G.chat_id&&(C(u=>{const L=u.findIndex(le=>le.message_key===G.message_key);return L>=0?u.map((le,_e)=>_e===L?G:le):[...u,G]}),G.direction==="incoming"&&G.message_type!=="system")){const u=[{messageId:G.message_key,sessionId:G.chat_id,cid:`${G.chat_id}@goofish`,conversationType:1}];console.info("[聊天已读] 收到实时消息上报",{accountID:ye,chatID:G.chat_id,messageKey:G.message_key,messageType:G.message_type}),Qs(ye,G.chat_id,u)}}catch{}},R.onclose=()=>{if(h)return;q("offline");const ke=Math.min(15e3,1e3*2**Math.min(D++,4));f=window.setTimeout(we,ke)},R.onerror=()=>R==null?void 0:R.close()};return we(),()=>{h=!0,window.clearTimeout(f),R==null||R.close()}},[]);const T=()=>{const h=je.current;if(!h)return;const f=h.scrollHeight-h.scrollTop-h.clientHeight;Se.current=f<=48};r.useLayoutEffect(()=>{const h=Ee.current.accountID!==l||Ee.current.chatID!==_;Ee.current={accountID:l,chatID:_},h&&(Se.current=!0);const f=je.current;if(f){if(x.current){x.current=!1;return}(Q||Se.current)&&(f.scrollTop=f.scrollHeight)}},[l,_,g,Q]);const S=t.find(h=>h.id===l),X=m[l]||[],O=X.find(h=>h.chat_id===_),de=r.useMemo(()=>{const h=j.trim().toLowerCase();return X.filter(f=>K&&f.unread_count<=0?!1:h?[f.buyer_name,f.buyer_id,f.item_title,f.last_message].some(D=>(D||"").toLowerCase().includes(h)):!0)},[X,j,K]),Oe=h=>(m[h]||[]).reduce((f,D)=>f+D.unread_count,0),fe=async()=>{if(!(!l||E||!J[l])){P(!0),b("");try{const h=await as(l,H[l],void 0,!0);N(f=>({...f,[l]:h.sessions})),ve(f=>({...f,[l]:h.next_cursor})),A(f=>({...f,[l]:h.has_more}))}catch(h){b(h instanceof Error?h.message:"加载历史联系人失败")}finally{P(!1)}}},Ae=async()=>{const h=oe.trim();if(!(!h||!O||!l||ae)){M(!0),b("");try{const f=await ql({account_id:l,chat_id:O.chat_id,buyer_id:O.buyer_id,buyer_name:O.buyer_name,item_id:O.item_id,item_title:O.item_title,text:h});v(""),C(D=>D.some(R=>R.message_key===f.message.message_key)?D.map(R=>R.message_key===f.message.message_key?f.message:R):[...D,f.message])}catch(f){b(f instanceof Error?f.message:"消息发送失败"),Ml(l,O.chat_id).then(C)}finally{M(!1)}}},ne=async h=>{if(!(!h||!O||!l||ae)){M(!0),b("");try{const f=await Fl({account_id:l,chat_id:O.chat_id,buyer_id:O.buyer_id,buyer_name:O.buyer_name,buyer_avatar_url:O.buyer_avatar_url,item_id:O.item_id,item_title:O.item_title,image:h});C(D=>D.some(R=>R.message_key===f.message.message_key)?D.map(R=>R.message_key===f.message.message_key?f.message:R):[...D,f.message])}catch(f){b(f instanceof Error?f.message:"图片发送失败")}finally{M(!1),V.current&&(V.current.value="")}}};return F?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(Re,{className:"h-8 w-8 animate-spin text-sky-500"})}):e.jsxs("section",{className:"flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat",children:[e.jsxs("header",{className:"border-b border-slate-200 bg-slate-50/70 px-5 pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-black tracking-tight text-slate-950",children:"在线聊天"}),e.jsx("p",{className:"mt-0.5 text-xs font-medium text-slate-500",children:"复用账号实时连接,消息按账号完全隔离"})]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${U==="online"?"bg-emerald-50 text-emerald-700":U==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[U==="online"?e.jsx(pl,{className:"h-3.5 w-3.5"}):e.jsx(ul,{className:"h-3.5 w-3.5"}),U==="online"?"实时同步中":U==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:t.map(h=>{const f=h.id===l,D=Oe(h.id),R=h.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":f,onClick:()=>i(h.id),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${f?"border-sky-500 text-sky-700":"border-transparent text-slate-500 hover:text-slate-900"}`,children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${R?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:h.nickname||h.remark||h.id}),e.jsx(pa,{count:D})]},h.id)})})]}),t.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(is,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-800",children:"暂无启用账号"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"先在账号管理中启用账号,聊天会话会自动出现。"})]}):e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40",children:[e.jsxs("div",{className:"space-y-3 border-b border-slate-200 p-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Nt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:j,onChange:h=>B(h.target.value),placeholder:"搜索用户、商品或消息",className:"h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:()=>me(h=>!h),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${K?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:K?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:()=>void c(l),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(ze,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[de.map(h=>e.jsxs("button",{type:"button",onClick:()=>I(h.chat_id),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${h.chat_id===_?"bg-white shadow-chat-active":"hover:bg-white/80"}`,children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500",children:h.buyer_avatar_url?e.jsx("img",{src:h.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(Gt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-extrabold text-slate-900",children:h.buyer_name||`用户 ${h.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:Tn(h.last_message_at)})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs text-slate-500",children:h.last_message||"暂无消息"}),e.jsx(pa,{count:h.unread_count,className:"ml-auto"})]}),h.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",h.item_title]})]})]},h.chat_id)),de.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),J[l]&&!j&&!K&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:()=>void fe(),disabled:E,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[E&&e.jsx(Re,{className:"h-3.5 w-3.5 animate-spin"}),E?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:O?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-black text-slate-950",children:O.buyer_name||O.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",O.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(S==null?void 0:S.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(S==null?void 0:S.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:je,onScroll:T,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:Q?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Re,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[he&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:()=>void d(),disabled:z,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[z&&e.jsx(Re,{className:"h-3.5 w-3.5 animate-spin"}),z?"正在加载":"加载更早消息"]})}),g.map(h=>{const f=h.direction==="outgoing";return h.message_type==="system"?e.jsx("div",{className:"flex justify-center py-1",children:e.jsxs("div",{className:"max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500",children:[da(h.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:ua(h.sent_at)})]})},h.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${f?"justify-end":"justify-start"}`,children:[!f&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:O.buyer_avatar_url?e.jsx("img",{src:O.buyer_avatar_url,alt:O.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(Gt,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${f?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:f?(S==null?void 0:S.nickname)||(S==null?void 0:S.remark)||"我":O.buyer_name||h.sender_name||O.buyer_id}),h.message_type==="image"?e.jsx("a",{href:h.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${f?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:h.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):h.message_type==="video"?e.jsx("video",{src:h.content,controls:!0,preload:"metadata",className:"max-h-80 max-w-full rounded-2xl bg-black"}):e.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${f?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:da(h.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[ua(h.sent_at),f&&(h.status==="failed"?e.jsx(rt,{className:"h-3 w-3 text-red-500"}):h.read_status===2?e.jsx(hl,{className:"h-3 w-3 text-sky-500"}):h.status==="sent"?e.jsx(Qe,{className:"h-3 w-3 text-sky-500"}):e.jsx(Qe,{className:"h-3 w-3"}))]})]}),f&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:S!=null&&S.avatar_url?e.jsx("img",{src:S.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(Gt,{className:"m-2 h-5 w-5 text-sky-600"})})]},h.message_key)})]})}),p&&e.jsx("div",{className:"border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:p}),e.jsxs("div",{className:"relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>Pe(h=>!h),disabled:ae||(S==null?void 0:S.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"闲鱼表情",children:e.jsx(gl,{className:"h-5 w-5"})}),be&&e.jsxs("div",{className:"absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl",children:[e.jsx("div",{className:"mb-2 text-xs font-bold text-slate-500",children:"全部表情"}),e.jsx("div",{className:"grid max-h-72 grid-cols-8 gap-1 overflow-y-auto",children:Fa.map(([h,f])=>e.jsx("button",{type:"button",title:`[${h}]`,onClick:()=>{v(D=>D+`[${h}]`),Pe(!1)},className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:En(f),alt:`[${h}]`,className:"h-8 w-8 object-contain"})},h))})]})]}),e.jsx("input",{ref:V,type:"file",accept:"image/*",className:"hidden",onChange:h=>{var f;return void ne((f=h.target.files)==null?void 0:f[0])}}),e.jsx("button",{type:"button",onClick:()=>{var h;return(h=V.current)==null?void 0:h.click()},disabled:ae||(S==null?void 0:S.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"发送图片(最大 10MB)",children:e.jsx(bl,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100",children:[e.jsx("textarea",{value:oe,onChange:h=>v(h.target.value),rows:2,maxLength:2e3,onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),Ae())},disabled:(S==null?void 0:S.runtime_state)!=="online",placeholder:(S==null?void 0:S.runtime_state)==="online"?"输入消息,Enter 发送,Shift + Enter 换行":"账号离线,暂时无法发送",className:"max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed"}),e.jsx("button",{type:"button",onClick:()=>void Ae(),disabled:!oe.trim()||ae||(S==null?void 0:S.runtime_state)!=="online",className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none","aria-label":"发送消息",children:ae?e.jsx(Re,{className:"h-4 w-4 animate-spin"}):e.jsx(Zt,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(is,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-700",children:"选择一个用户开始聊天"}),e.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})},Ba="ydisks.sidebar.v1",qn=()=>{try{return window.localStorage.getItem(Ba)==="collapsed"}catch{return!1}},Fn=t=>{try{window.localStorage.setItem(Ba,t?"collapsed":"expanded")}catch{}},za={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/chat":"chat","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},ha=Object.fromEntries(Object.entries(za).map(([t,a])=>[a,t])),ga=()=>za[window.location.pathname]||"dashboard",Bn=()=>{const[t,a]=r.useState(!1),[l,i]=r.useState(!1),[m,N]=r.useState(ga),[_,I]=r.useState(!0),[g,C]=r.useState(!1),[j,B]=r.useState(""),[K,me]=r.useState(""),[oe,v]=r.useState(!1),[F,ce]=r.useState(""),[Q,te]=r.useState(""),[z,ge]=r.useState(""),[he,k]=r.useState(!1),[Y,se]=r.useState(""),[H,ve]=r.useState(),[J,A]=r.useState(qn),E=M=>{const p=M==="settings"&&!l?"dashboard":M,b=ha[p];b&&b!==window.location.pathname&&window.history.pushState({},"",b),N(p)};r.useEffect(()=>{const M=()=>N(ga());return window.addEventListener("popstate",M),()=>window.removeEventListener("popstate",M)},[]),r.useEffect(()=>{Oa().then(p=>{if((p==null?void 0:p.initialized)===!1){C(!0),a(!1),i(!1);return}C(!1),p!=null&&p.authenticated?(a(!0),i(p.is_admin===!0)):i(!1)}).catch(()=>{a(!1),i(!1)}).finally(()=>I(!1));const M=()=>{a(!1),i(!1)};return window.addEventListener("auth:logout",M),()=>window.removeEventListener("auth:logout",M)},[]),r.useEffect(()=>{!_&&t&&!l&&m==="settings"&&(window.history.replaceState({},"",ha.dashboard),N("dashboard"))},[_,t,l,m]);const P=async M=>{M.preventDefault(),v(!0),ce("");try{const p=await Al({username:j,password:K});p.success?(a(!0),i(p.is_admin===!0)):ce(p.message||"登录失败")}catch(p){const b=p instanceof Error?p.message:String(p);ce(b||"登录失败")}finally{v(!1)}},be=async M=>{if(M.preventDefault(),se(""),Q.length<8){se("密码至少需要 8 个字符");return}if(Q!==z){se("两次输入的密码不一致");return}k(!0);try{const p=await $l(Q);if(!p.success){se(p.message||"初始化失败,请重试");return}C(!1),a(!0),i(p.is_admin===!0),te(""),ge("")}catch(p){const b=p instanceof Error?p.message:String(p);se(b||"初始化失败,请重试")}finally{k(!1)}},Pe=async()=>{try{await Rl()}catch(M){console.error("退出登录失败",M)}finally{a(!1),i(!1)}};if(_)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface",children:e.jsx(Re,{className:"w-8 h-8 text-brand animate-spin"})});if(g)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas 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-panel 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(ms,{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:"设置完成后会自动进入系统,管理员账号为 admin。"})]}),e.jsxs("form",{onSubmit:be,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(Fs,{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:"设置管理员密码(至少 8 个字符)",value:Q,onChange:M=>te(M.target.value),autoFocus:!0,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(Mt,{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:z,onChange:M=>ge(M.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),Y&&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(Mt,{className:"w-4 h-4"})," ",Y]}),e.jsx("button",{type:"submit",disabled:he,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:he?e.jsx(Re,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["设置密码并进入系统 ",e.jsx(xs,{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(!t)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas 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-panel 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(ms,{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:P,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(xt,{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:M=>B(M.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(Fs,{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:K,onChange:M=>me(M.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),F&&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(Mt,{className:"w-4 h-4"})," ",F]}),e.jsx("button",{type:"submit",disabled:oe,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:oe?e.jsx(Re,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["立即登录 ",e.jsx(xs,{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 ae=()=>{switch(m){case"dashboard":return e.jsx(rs,{});case"accounts":return e.jsx(rn,{});case"chat":return e.jsx(Mn,{});case"orders":return e.jsx(cn,{});case"cards":return e.jsx(xn,{});case"items":return e.jsx(yn,{onConfigureDelivery:M=>{ve({cookieId:M.cookie_id,itemId:M.item_id,requestId:Date.now()}),E("rules")}});case"rules":return e.jsx(In,{initialDeliveryTarget:H,onDeliveryTargetHandled:()=>ve(void 0)});case"notifications":return e.jsx(Pn,{isAdmin:l});case"settings":return l?e.jsx(Nn,{}):e.jsx(rs,{});default:return e.jsx(rs,{})}};return e.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[e.jsx(kl,{activeTab:m,isAdmin:l,collapsed:J,onToggleCollapsed:()=>A(M=>{const p=!M;return Fn(p),p}),onNavigate:E,onLogout:Pe}),e.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${J?"ml-16":"ml-64"} ${m==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,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:`${m==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:ae()})]})]})},Ua=document.getElementById("root");if(!Ua)throw new Error("Could not find root element to mount to");const zn=Ja.createRoot(Ua);zn.render(e.jsx(ys.StrictMode,{children:e.jsx(Bn,{})})); diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html index 3408f55..3685e61 100644 --- a/internal/webui/static/index.html +++ b/internal/webui/static/index.html @@ -6,7 +6,7 @@ Ydisks闲鱼助手 - 自动发货与管家系统 - + diff --git a/internal/xianyu/ws/client.go b/internal/xianyu/ws/client.go index 9c6bc03..c6aad37 100644 --- a/internal/xianyu/ws/client.go +++ b/internal/xianyu/ws/client.go @@ -766,6 +766,27 @@ func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error return c.sendChatContent(ctx, myID, cid, toID, content) } +// MarkChatRead notifies the platform that the conversation was opened. +func (c *Conn) MarkChatRead(ctx context.Context, cid string, messageIDs []map[string]any) error { + ids := make([]string, 0, len(messageIDs)) + for _, item := range messageIDs { + if id := strings.TrimSpace(fmt.Sprint(item["messageId"])); id != "" && id != "" { + ids = append(ids, id) + } + } + c.logger.Info("准备上报闲鱼已读", "cid", cid, "message_count", len(ids), "message_ids", ids) + // MessageStatusService.read takes one argument: list messageIds. + response, err := c.request(ctx, "/r/MessageStatus/read", map[string]any{}, []any{ids}, regResponseTimeout) + if err == nil { + if code, ok := responseCode(response["code"]); ok && code >= 400 { + c.logger.Warn("闲鱼已读上报被拒绝", "cid", cid, "message_count", len(ids), "code", code, "body", response["body"]) + } else { + c.logger.Info("闲鱼已读上报成功", "cid", cid, "message_count", len(ids), "message_ids", ids, "code", response["code"]) + } + } + return err +} + // SendImage 发送一条闲鱼聊天图片消息。imageURL 应为闲鱼可访问的 CDN/公网 URL。 func (c *Conn) SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error { if width <= 0 {