diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 64a6902..430a0aa 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -191,6 +191,7 @@ app shell / routes - 已完成阶段 7 当前 PR 切片“React OrderList 完整页面行为边界”:新增真实挂载 `OrderList` 的组合测试,覆盖筛选栏状态转发、同步与导入入口、详情弹窗、编辑字段映射、状态发货、单笔同步、删除分页分支和上一页/下一页函数式更新;分页按钮补充稳定的无障碍名称,测试隔离订单查询 Hook、导入状态、API 和筛选子组件,不跳过页面协调逻辑。OrderList 动作协调器进一步 feature 化、Rules/ItemList/CardList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍待完成; - 已完成阶段 7 当前 PR 切片“React OrderList 动作协调器 feature 化”:新增 `app/features/orders/orderActions.ts` 与对应 Hook 测试,将订单同步、发货、详情、编辑草稿、单笔同步、删除分页回退和弹窗生命周期从 `OrderList` 根组件迁入 feature;根组件只保留查询、筛选、页面组合和展示字段更新,编辑字段通过函数式补丁进入协调器;成功、失败、取消和异常结果均有 Hook/页面回归证据。Rules/ItemList/CardList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍待完成; - 已完成阶段 7 当前 PR 切片“React CardList 动作协调器 feature 化”:新增 `app/features/cards/cardActions.ts`,将卡密新增、编辑、删除、启停、筛选、复制和模板下载从 `CardList` 根组件迁入 cards feature;批量导入仍复用既有批量 Hook,页面根组件只负责状态组合和表单展示;新增动作 Hook 与真实页面组合测试,覆盖筛选、批量入口、新增/编辑字段映射、启停、复制和删除。Rules/ItemList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍待完成; +- 已完成阶段 7 当前 PR 切片“React Rules 动作协调器 feature 化”:新增 `app/features/rules/ruleActions.ts`,将自动化规则草稿、触发类型/规格编辑、保存删除、异常恢复、关键词回复和默认回复动作,以及商品页联动加载从 `Rules` 根组件迁入 rules feature;同步更新路由静态契约测试,新增 Hook 测试覆盖自动化规则归一化保存、三类回复保存、触发/规格编辑、删除和异常恢复;前端全量 366 个测试、类型检查、中文注释门禁和生产构建通过。ItemList 其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍待完成; - 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。 ## 6. 阶段 0:治理文档与强约束 @@ -779,3 +780,4 @@ npm --prefix frontend run build | 2026-08-15 | P2 React OrderList 完整页面行为边界 | 已完成本切片 | 新增 `frontend/components/OrderList.test.tsx`,真实挂载订单页面并隔离查询/导入 Hook、订单 API 和筛选/导入子组件;覆盖筛选转发、同步提示、导入入口、详情打开关闭、编辑字段转换、状态发货结果、单笔同步、删除时分页回退和分页函数式更新;分页按钮增加“上一页/下一页”无障碍名称。OrderList 动作协调器、Rules/ItemList/CardList 等其他大型页面、页面级 Provider 组合和阶段 7 总体验收仍未完成 | | 2026-08-15 | P2 React OrderList 动作协调器 feature 化 | 已完成本切片 | 新增 `frontend/app/features/orders/orderActions.ts` 与 `orderActions.test.tsx`,将同步、发货、详情、编辑、单笔同步、删除分页回退和弹窗关闭状态从 `OrderList` 根组件迁入订单 feature;编辑表单通过 `updateEditingOrder` 函数式补丁更新,保留原有 API、提示和结果语义;Hook 测试覆盖同步/发货/编辑/删除异常、确认取消和弹窗清理,页面组合测试继续覆盖成功流程。Rules/ItemList/CardList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍未完成 | | 2026-08-15 | P2 React CardList 动作协调器 feature 化 | 已完成本切片 | 新增 `frontend/app/features/cards/cardActions.ts` 和 `cardActions.test.tsx`,将卡密新增、编辑、删除、启停、筛选、复制和模板下载状态/动作从 `CardList` 根组件迁入 cards feature;新增 `CardList.test.tsx` 真实挂载页面,覆盖筛选计数、批量导入入口、新增/编辑字段映射、启停、复制和删除;补充行级按钮无障碍名称。Rules/ItemList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍未完成 | +| 2026-08-15 | P2 React Rules 动作协调器 feature 化 | 已完成本切片 | 新增 `frontend/app/features/rules/ruleActions.ts` 和 `ruleActions.test.tsx`,将自动化规则、关键词回复、默认回复的草稿与动作状态从 `Rules` 根组件迁入 rules feature;保留商品页联动加载、触发/规格编辑、归一化保存、异常恢复与确认语义,更新路由静态契约测试以跟随实现边界;前端全量 366 个测试、类型检查、中文注释门禁和生产构建通过。ItemList 其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍未完成 | diff --git a/frontend/app/features/rules/ruleActions.test.tsx b/frontend/app/features/rules/ruleActions.test.tsx new file mode 100644 index 0000000..5b14626 --- /dev/null +++ b/frontend/app/features/rules/ruleActions.test.tsx @@ -0,0 +1,157 @@ +// @vitest-environment jsdom +import { act, renderHook } from '@testing-library/react'; +import { useState } from 'react'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import type { Card, DefaultReply, Item, ShippingRule } from './types'; +import { clearDefaultReplyRecords, deleteDefaultReply, deleteReplyRule, deleteShippingRule, getDefaultReply, resolveAutomationRun, resolveDeferredAutomationTask, updateDefaultReply, updateReplyRule, updateShippingRule } from './api'; +import { useRuleActions, type RuleActionsOptions } from './ruleActions'; + +vi.mock('./api', /* ruleActionsApiMockFactory 提供规则动作 Hook 的确定性 API 替身。 */ () => ({ + clearDefaultReplyRecords: vi.fn(), + deleteDefaultReply: vi.fn(), + deleteReplyRule: vi.fn(), + deleteShippingRule: vi.fn(), + getCards: vi.fn(), + getDefaultReply: vi.fn(), + getItems: vi.fn(), + getShippingRules: vi.fn(), + resolveAutomationRun: vi.fn(), + resolveDeferredAutomationTask: vi.fn(), + updateDefaultReply: vi.fn(), + updateReplyRule: vi.fn(), + updateShippingRule: vi.fn(), +})); + +// defaultReplyMock 是默认回复读取接口的可控替身。 +const defaultReplyMock = vi.mocked(getDefaultReply); +// updateDefaultMock 是默认回复保存接口的可控替身。 +const updateDefaultMock = vi.mocked(updateDefaultReply); +// updateReplyMock 是关键词回复保存接口的可控替身。 +const updateReplyMock = vi.mocked(updateReplyRule); +// updateShippingMock 是自动化规则保存接口的可控替身。 +const updateShippingMock = vi.mocked(updateShippingRule); +// deleteShippingMock 是自动化规则删除接口的可控替身。 +const deleteShippingMock = vi.mocked(deleteShippingRule); +// resolveRunMock 是自动化运行恢复接口的可控替身。 +const resolveRunMock = vi.mocked(resolveAutomationRun); +// resolveDeferredMock 是延迟任务恢复接口的可控替身。 +const resolveDeferredMock = vi.mocked(resolveDeferredAutomationTask); +// deleteReplyMock 是关键词回复删除接口的可控替身。 +const deleteReplyMock = vi.mocked(deleteReplyRule); +// deleteDefaultMock 是默认回复删除接口的可控替身。 +const deleteDefaultMock = vi.mocked(deleteDefaultReply); +// clearRecordsMock 是默认回复记录清理接口的可控替身。 +const clearRecordsMock = vi.mocked(clearDefaultReplyRecords); + +// itemFixture 是自动化规则草稿使用的商品。 +const itemFixture = { cookie_id: 'account-1', item_id: 'item-1', item_title: '测试商品', is_multi_spec: false } as Item; +// cardFixture 是规则动作依赖的卡密库存。 +const cardFixture = { id: 7, name: '测试卡密', type: 'data' } as Card; +// defaultReplyFixture 是默认回复读取结果。 +const defaultReplyFixture = { cookie_id: 'account-1', enabled: true, reply_content: '欢迎', reply_once: false, reply_image_url: '' } as DefaultReply; + +// useRuleActionsHarness 创建带有真实 React 状态容器的规则动作 Hook。 +const useRuleActionsHarness = () => { + // selectedAccountId 保存测试中的当前账号。 + const [selectedAccountId, setSelectedAccountId] = useState('account-1'); + // activeTab 保存测试中的当前页签。 + const [, setActiveTab] = useState<'automation' | 'reply' | 'default'>('automation'); + // items 保存测试中的商品参考数据。 + const [items] = useState([itemFixture]); + // automationRules 保存外部联动写入的规则列表。 + const [, setAutomationRules] = useState([]); + // cards 保存外部联动写入的卡密列表。 + const [, setCards] = useState([cardFixture]); + // linkedItems 保存外部联动写入的商品列表。 + const [, setItems] = useState([itemFixture]); + // loading 保存测试中的加载指示器。 + const [, setLoading] = useState(false); + // loadAutomationRules 是自动化规则刷新替身。 + const loadAutomationRules = vi.fn(async () => undefined); + // loadReferenceData 是规则参考数据刷新替身。 + const loadReferenceData = vi.fn(async () => undefined); + // loadReplyRules 是关键词回复刷新替身。 + const loadReplyRules = vi.fn(async () => undefined); + // loadDefaultReplies 是默认回复刷新替身。 + const loadDefaultReplies = vi.fn(async () => undefined); + // options 是规则动作 Hook 的完整依赖。 + const options: RuleActionsOptions = { selectedAccountId, setSelectedAccountId, setActiveTab, items, setAutomationRules, setCards, setItems: /* setItemsAction 写入外部联动商品列表。 */ linkedItems => setItems(linkedItems), setLoading, loadAutomationRules, loadReferenceData, loadReplyRules, loadDefaultReplies }; + return useRuleActions(options); +}; + +describe('useRuleActions', /* 当前回调验证规则页面动作协调器的核心状态和副作用。 */ () => { + beforeEach(/* 当前回调重置规则动作 API 替身。 */ () => { + vi.clearAllMocks(); + defaultReplyMock.mockResolvedValue(defaultReplyFixture); + updateDefaultMock.mockResolvedValue({ success: true }); + updateReplyMock.mockResolvedValue({ success: true }); + updateShippingMock.mockResolvedValue({ success: true }); + deleteShippingMock.mockResolvedValue({ success: true }); + resolveRunMock.mockResolvedValue({ success: true }); + resolveDeferredMock.mockResolvedValue({ success: true }); + deleteReplyMock.mockResolvedValue({ success: true }); + deleteDefaultMock.mockResolvedValue({ success: true }); + clearRecordsMock.mockResolvedValue({ success: true }); + vi.stubGlobal('alert', vi.fn()); + vi.stubGlobal('confirm', vi.fn(() => true)); + }); + + afterEach(/* 当前回调清理规则动作测试中的全局替身。 */ () => vi.unstubAllGlobals()); + + test('创建并保存自动化规则时归一化规格和刷新数据', /* 当前回调验证自动化规则草稿与保存边界。 */ async () => { + // hook 是规则动作 Hook 的真实 React 状态实例。 + const hook = renderHook(() => useRuleActionsHarness()); + act(/* 当前回调打开新建自动化规则弹窗。 */ () => hook.result.current.openNewAutomationRule()); + expect(hook.result.current.showAutomationModal).toBe(true); + act(/* 当前回调写入需要保存的卡密规格。 */ () => hook.result.current.setEditingAutomationRule(/* currentDraft 更新自动化规则草稿。 */ current => ({ ...current, cookie_id: 'account-1', variants: [{ id: 'variant-1', spec_name: '', spec_value: '', card_id: 7, delivery_count: 0, enabled: true }] }))); + await act(/* 当前回调执行自动化规则保存。 */ async () => hook.result.current.handleSaveAutomationRule()); + expect(updateShippingMock).toHaveBeenCalledWith(expect.objectContaining({ cookie_id: 'account-1', variants: [expect.objectContaining({ card_id: 7, delivery_count: 1 })] })); + expect(hook.result.current.showAutomationModal).toBe(false); + hook.unmount(); + }); + + test('关键词和默认回复动作分别读取、保存并刷新', /* 当前回调验证两个回复页签的动作边界。 */ async () => { + // hook 是规则动作 Hook 的真实 React 状态实例。 + const hook = renderHook(() => useRuleActionsHarness()); + act(/* 当前回调打开关键词新增弹窗。 */ () => hook.result.current.handleAddReplyRule()); + act(/* 当前回调填写关键词回复草稿。 */ () => hook.result.current.setEditingReplyRule(/* currentDraft 更新关键词回复草稿。 */ current => ({ ...current, keyword: '你好', reply_content: '您好' }))); + await act(/* 当前回调保存关键词回复规则。 */ async () => hook.result.current.handleSaveReplyRule()); + expect(updateReplyMock).toHaveBeenCalledWith(expect.objectContaining({ keyword: '你好', match_type: 'fuzzy', enabled: true }), 'account-1'); + + await act(/* 当前回调打开默认回复弹窗并加载服务端数据。 */ async () => hook.result.current.openDefaultReplyModal()); + expect(hook.result.current.defaultForm).toEqual(expect.objectContaining({ reply_content: '欢迎', enabled: true })); + await act(/* 当前回调保存默认回复配置。 */ async () => hook.result.current.handleSaveDefaultReply()); + expect(updateDefaultMock).toHaveBeenCalledWith('account-1', expect.objectContaining({ reply_content: '欢迎', enabled: true })); + hook.unmount(); + }); + + test('规则编辑、异常恢复和删除动作均通过统一协调器', /* 当前回调覆盖规则动作 Hook 的剩余公开方法。 */ async () => { + // hook 是规则动作 Hook 的真实 React 状态实例。 + const hook = renderHook(() => useRuleActionsHarness()); + act(/* 当前回调打开自动化规则草稿。 */ () => hook.result.current.openNewAutomationRule()); + act(/* 当前回调切换规则触发类型。 */ () => hook.result.current.handleTriggerChange('buyer_reviewed')); + act(/* 当前回调更新第一行规格。 */ () => hook.result.current.updateVariant(0, { card_id: 7 })); + act(/* 当前回调追加第二行规格。 */ () => hook.result.current.appendDeliveryContent()); + expect(hook.result.current.displayVariants).toHaveLength(2); + act(/* 当前回调切换规则绑定商品。 */ () => hook.result.current.handleAutomationItemChange('item-1')); + + // rule 是用于切换和删除动作的自动化规则样本。 + const rule = { id: 'rule-1', cookie_id: 'account-1', trigger_type: 'order_paid', enabled: true } as ShippingRule; + await act(/* 当前回调切换规则启用状态。 */ async () => hook.result.current.handleToggleAutomation(rule)); + await act(/* 当前回调删除自动化规则。 */ async () => hook.result.current.handleDeleteAutomation('rule-1')); + await act(/* 当前回调恢复暂停中的自动化运行。 */ async () => hook.result.current.handleResolveRunIssue(1, 'retry')); + await act(/* 当前回调恢复延迟自动化任务。 */ async () => hook.result.current.handleResolveDeferredIssue(2, 'dismiss')); + await act(/* 当前回调删除关键词回复规则。 */ async () => hook.result.current.handleDeleteReply('reply-1')); + await act(/* 当前回调删除默认回复配置。 */ async () => hook.result.current.handleDeleteDefaultReply('account-1')); + await act(/* 当前回调清空默认回复记录。 */ async () => hook.result.current.handleClearDefaultReplyRecords('account-1')); + + expect(updateShippingMock).toHaveBeenCalledWith(expect.objectContaining({ id: 'rule-1', enabled: false })); + expect(deleteShippingMock).toHaveBeenCalledWith('rule-1'); + expect(resolveRunMock).toHaveBeenCalledWith(1, 'retry'); + expect(resolveDeferredMock).toHaveBeenCalledWith(2, 'dismiss'); + expect(deleteReplyMock).toHaveBeenCalledWith('reply-1', 'account-1'); + expect(deleteDefaultMock).toHaveBeenCalledWith('account-1'); + expect(clearRecordsMock).toHaveBeenCalledWith('account-1'); + hook.unmount(); + }); +}); diff --git a/frontend/app/features/rules/ruleActions.ts b/frontend/app/features/rules/ruleActions.ts new file mode 100644 index 0000000..64336c0 --- /dev/null +++ b/frontend/app/features/rules/ruleActions.ts @@ -0,0 +1,460 @@ +import { useCallback, useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react'; +import type { AutomationTriggerType, Card, Item, ReplyRule, ShippingRule, ShippingVariant } from './types'; +import { + clearDefaultReplyRecords, + deleteDefaultReply, + deleteReplyRule, + deleteShippingRule, + getCards, + getDefaultReply, + getItems, + getShippingRules, + resolveAutomationRun, + resolveDeferredAutomationTask, + updateDefaultReply, + updateReplyRule, + updateShippingRule, +} from './api'; +import { boolFlag, buildReviewConfig, cardActionsForTrigger, defaultRuleName, emptyVariant, parseJSONObject, shouldReplaceGeneratedName, triggerMeta } from './utils'; +import type { DefaultReplyForm, RulesProps, RulesTab } from './types'; +import { finishRuleSubmission, idleRuleSubmitState, startRuleSubmission, type RuleSubmitState } from './interactionState'; + +// RuleActionsOptions 描述规则动作协调器依赖的页面数据、刷新函数和外部联动目标。 +export interface RuleActionsOptions { + // selectedAccountId 保存当前规则页面选择的账号。 + selectedAccountId: string; + // setSelectedAccountId 更新当前规则页面选择的账号。 + setSelectedAccountId: Dispatch>; + // setActiveTab 将外部联动切换到自动化页签。 + setActiveTab: Dispatch>; + // items 保存规则编辑器可绑定的商品列表。 + items: Item[]; + // setAutomationRules 写入外部联动场景加载的自动化规则。 + setAutomationRules: Dispatch>; + // setCards 写入外部联动场景加载的卡密库存。 + setCards: Dispatch>; + // setItems 写入外部联动场景加载的商品列表。 + setItems: Dispatch>; + // setLoading 更新规则页面的加载指示器。 + setLoading: Dispatch>; + // loadAutomationRules 刷新自动化规则和异常任务。 + loadAutomationRules: () => Promise; + // loadReferenceData 刷新规则编辑器参考数据。 + loadReferenceData: () => Promise; + // loadReplyRules 刷新关键词回复规则。 + loadReplyRules: () => Promise; + // loadDefaultReplies 刷新账号默认回复。 + loadDefaultReplies: () => Promise; + // initialDeliveryTarget 保存商品页跳转到规则页的目标。 + initialDeliveryTarget?: RulesProps['initialDeliveryTarget']; + // onDeliveryTargetHandled 通知父页面外部跳转已完成。 + onDeliveryTargetHandled?: () => void; +} + +// RuleActionsState 暴露规则页弹窗状态、编辑草稿和业务动作。 +export interface RuleActionsState { + // showAutomationModal 表示自动化规则弹窗是否打开。 + showAutomationModal: boolean; + // setShowAutomationModal 更新自动化规则弹窗展示状态。 + setShowAutomationModal: Dispatch>; + // showReplyModal 表示关键词回复弹窗是否打开。 + showReplyModal: boolean; + // setShowReplyModal 更新关键词回复弹窗展示状态。 + setShowReplyModal: Dispatch>; + // showDefaultModal 表示默认回复弹窗是否打开。 + showDefaultModal: boolean; + // setShowDefaultModal 更新默认回复弹窗展示状态。 + setShowDefaultModal: Dispatch>; + // automationSubmitState 保存自动化规则提交状态。 + automationSubmitState: RuleSubmitState; + // replySubmitState 保存关键词回复提交状态。 + replySubmitState: RuleSubmitState; + // defaultReplySubmitState 保存默认回复提交状态。 + defaultReplySubmitState: RuleSubmitState; + // editingAutomationRule 保存当前自动化规则草稿。 + editingAutomationRule: Partial | null; + // setEditingAutomationRule 更新自动化规则草稿。 + setEditingAutomationRule: Dispatch | null>>; + // editingReplyRule 保存当前关键词回复草稿。 + editingReplyRule: Partial | null; + // setEditingReplyRule 更新关键词回复草稿。 + setEditingReplyRule: Dispatch | null>>; + // defaultForm 保存当前默认回复草稿。 + defaultForm: DefaultReplyForm; + // setDefaultForm 更新默认回复草稿。 + setDefaultForm: Dispatch>; + // selectedRuleItem 保存当前规则草稿绑定的商品。 + selectedRuleItem: Item | undefined; + // isMultiSpecRule 表示当前商品是否需要多规格字段。 + isMultiSpecRule: boolean; + // currentTrigger 保存当前规则草稿的触发类型。 + currentTrigger: AutomationTriggerType; + // currentMeta 保存当前触发类型的展示元数据。 + currentMeta: typeof triggerMeta[AutomationTriggerType]; + // reviewConfig 保存当前评价规则配置对象。 + reviewConfig: Record; + // displayVariants 保存至少包含一行的规格草稿。 + displayVariants: ShippingVariant[]; + // buildAutomationDraft 创建指定触发类型的规则草稿。 + buildAutomationDraft: (trigger?: AutomationTriggerType, cookieID?: string, itemID?: string) => Partial; + // openAutomationRule 打开指定自动化规则的编辑弹窗。 + openAutomationRule: (rule: ShippingRule) => void; + // openNewAutomationRule 打开新建自动化规则弹窗。 + openNewAutomationRule: (trigger?: AutomationTriggerType) => void; + // handleTriggerChange 切换当前规则的触发类型。 + handleTriggerChange: (trigger: AutomationTriggerType) => void; + // handleAutomationItemChange 切换当前规则绑定的商品。 + handleAutomationItemChange: (itemID: string) => void; + // updateVariant 更新指定发货规格的字段。 + updateVariant: (index: number, patch: Partial) => void; + // appendDeliveryContent 追加一行发货规格。 + appendDeliveryContent: () => void; + // handleSaveAutomationRule 保存当前自动化规则。 + handleSaveAutomationRule: () => Promise; + // handleDeleteAutomation 删除指定自动化规则。 + handleDeleteAutomation: (id: string) => Promise; + // handleToggleAutomation 切换指定自动化规则启用状态。 + handleToggleAutomation: (rule: ShippingRule) => Promise; + // handleResolveRunIssue 处理暂停中的自动化运行。 + handleResolveRunIssue: (id: number, resolution: 'continue' | 'retry' | 'cancel') => Promise; + // handleResolveDeferredIssue 处理等待重试的自动化任务。 + handleResolveDeferredIssue: (id: number, resolution: 'retry' | 'dismiss') => Promise; + // handleAddReplyRule 打开新增关键词回复弹窗。 + handleAddReplyRule: () => void; + // handleSaveReplyRule 保存当前关键词回复规则。 + handleSaveReplyRule: () => Promise; + // handleDeleteReply 删除指定关键词回复规则。 + handleDeleteReply: (id: string) => Promise; + // openDefaultReplyModal 打开指定账号的默认回复弹窗。 + openDefaultReplyModal: (cookieID?: string) => Promise; + // handleSaveDefaultReply 保存当前默认回复配置。 + handleSaveDefaultReply: () => Promise; + // handleDeleteDefaultReply 删除指定账号的默认回复配置。 + handleDeleteDefaultReply: (cookieID: string) => Promise; + // handleClearDefaultReplyRecords 清空指定账号的默认回复记录。 + handleClearDefaultReplyRecords: (cookieID: string) => Promise; +} + +// useRuleActions 集中管理规则页三类规则的编辑、保存、删除和异常恢复动作。 +export const useRuleActions = ({ + selectedAccountId, + setSelectedAccountId, + setActiveTab, + items, + setAutomationRules, + setCards, + setItems, + setLoading, + loadAutomationRules, + loadReferenceData, + loadReplyRules, + loadDefaultReplies, + initialDeliveryTarget, + onDeliveryTargetHandled, +}: RuleActionsOptions): RuleActionsState => { + // showAutomationModal 表示自动化规则弹窗是否打开。 + const [showAutomationModal, setShowAutomationModal] = useState(false); + // showReplyModal 表示关键词回复弹窗是否打开。 + const [showReplyModal, setShowReplyModal] = useState(false); + // showDefaultModal 表示默认回复弹窗是否打开。 + const [showDefaultModal, setShowDefaultModal] = useState(false); + // automationSubmitState 保存自动化规则提交状态。 + const [automationSubmitState, setAutomationSubmitState] = useState(idleRuleSubmitState); + // replySubmitState 保存关键词回复提交状态。 + const [replySubmitState, setReplySubmitState] = useState(idleRuleSubmitState); + // defaultReplySubmitState 保存默认回复提交状态。 + const [defaultReplySubmitState, setDefaultReplySubmitState] = useState(idleRuleSubmitState); + // editingAutomationRule 保存当前自动化规则草稿。 + const [editingAutomationRule, setEditingAutomationRule] = useState | null>(null); + // editingReplyRule 保存当前关键词回复草稿。 + const [editingReplyRule, setEditingReplyRule] = useState | null>(null); + // defaultForm 保存当前默认回复草稿。 + const [defaultForm, setDefaultForm] = useState({ cookie_id: '', enabled: false, reply_content: '', reply_once: false, reply_image_url: '' }); + + // selectedRuleItem 查找当前自动化规则草稿绑定的商品。 + const selectedRuleItem = useMemo( + /* 当前回调计算规则草稿绑定的商品。 */ () => editingAutomationRule?.cookie_id && editingAutomationRule.item_id + ? items.find(/* 当前回调查找匹配的商品。 */ item => item.cookie_id === editingAutomationRule.cookie_id && item.item_id === editingAutomationRule.item_id) + : undefined, + [editingAutomationRule?.cookie_id, editingAutomationRule?.item_id, items], + ); + // isMultiSpecRule 表示当前商品是否需要填写规格名称和值。 + const isMultiSpecRule = boolFlag(selectedRuleItem?.is_multi_spec); + // currentTrigger 保存当前规则草稿的触发类型。 + const currentTrigger = (editingAutomationRule?.trigger_type || 'order_paid') as AutomationTriggerType; + // currentMeta 保存当前触发类型的页面展示元数据。 + const currentMeta = triggerMeta[currentTrigger]; + // reviewConfig 将当前评价规则配置解析为对象。 + const reviewConfig = parseJSONObject(editingAutomationRule?.config_json); + // displayVariants 为编辑器提供至少一行规格数据。 + const displayVariants = editingAutomationRule?.variants?.length ? editingAutomationRule.variants : [emptyVariant()]; + + // buildAutomationDraft 创建指定触发类型的默认规则草稿。 + const buildAutomationDraft = useCallback(/* buildDraftAction 创建规则默认草稿。 */ (trigger: AutomationTriggerType = 'order_paid', cookieID = selectedAccountId, itemID = ''): Partial => { + // item 保存规则绑定的商品。 + const item = items.find(/* 当前回调查找规则绑定的商品。 */ candidate => candidate.cookie_id === cookieID && candidate.item_id === itemID); + // itemLabel 保存规则名称使用的商品标签。 + const itemLabel = item?.item_title || itemID; + return { + name: defaultRuleName(trigger, itemLabel), trigger_type: trigger, cookie_id: cookieID, item_id: itemID, + item_title: item?.item_title || '', item_keyword: itemLabel, card_group_id: 0, priority: 100, enabled: true, + config_json: trigger === 'review_missing_timeout' ? buildReviewConfig() : '{}', actions: cardActionsForTrigger(trigger), + variants: trigger === 'review_missing_timeout' ? [] : [emptyVariant()], + }; + }, [items, selectedAccountId]); + + // openAutomationRule 将已有规则复制为草稿并打开编辑弹窗。 + const openAutomationRule = useCallback(/* openRuleAction 打开已有规则草稿。 */ (rule: ShippingRule) => { + // trigger 保存已有规则的触发类型。 + const trigger = (rule.trigger_type || 'order_paid') as AutomationTriggerType; + setEditingAutomationRule({ + ...rule, + trigger_type: trigger, + config_json: trigger === 'review_missing_timeout' ? buildReviewConfig(rule.config_json) : (rule.config_json || '{}'), + actions: rule.actions?.length ? rule.actions.map(/* 当前回调复制自动化动作。 */ action => ({ ...action })) : cardActionsForTrigger(trigger, rule.card_group_id), + variants: rule.variants?.length ? rule.variants.map(/* 当前回调复制发货规格。 */ variant => ({ ...variant })) : (trigger === 'review_missing_timeout' ? [] : [emptyVariant()]), + }); + setShowAutomationModal(true); + }, []); + + // useEffect 处理商品页跳转到规则页时的异步加载和取消。 + useEffect(/* 当前回调处理外部商品联动。 */ () => { + if (!initialDeliveryTarget) return; + // cancelled 标记外部跳转加载是否已经失效。 + let cancelled = false; + // openLinkedRule 加载跳转目标对应的规则、商品和卡密数据。 + const openLinkedRule = async () => { + setActiveTab('automation'); + setSelectedAccountId(initialDeliveryTarget.cookieId); + setLoading(true); + try { + // ruleList 保存当前账号的自动化规则。 + const [ruleList, itemList, cardList] = await Promise.all([ + getShippingRules(), getItems(), getCards().catch(/* error 表示卡密参考数据加载异常。 */ error => { + console.warn('加载卡密库存失败,不阻断打开自动化规则', error); + return []; + }), + ]); + if (cancelled) return; + setAutomationRules(ruleList); + setItems(itemList); + setCards(cardList); + // rule 保存跳转商品已有的订单支付规则。 + const rule = ruleList.find(/* 当前回调查找跳转目标规则。 */ candidate => candidate.cookie_id === initialDeliveryTarget.cookieId && candidate.item_id === initialDeliveryTarget.itemId && candidate.trigger_type === 'order_paid'); + if (rule) { + openAutomationRule(rule); + } else { + // item 保存跳转商品的参考数据。 + const item = itemList.find(/* 当前回调查找跳转目标商品。 */ candidate => candidate.cookie_id === initialDeliveryTarget.cookieId && candidate.item_id === initialDeliveryTarget.itemId); + setEditingAutomationRule({ + ...buildAutomationDraft('order_paid', initialDeliveryTarget.cookieId, initialDeliveryTarget.itemId), + item_title: item?.item_title || '', item_keyword: item?.item_title || initialDeliveryTarget.itemId, + name: defaultRuleName('order_paid', item?.item_title || initialDeliveryTarget.itemId), + }); + setShowAutomationModal(true); + } + } catch (/* error 表示外部联动加载异常。 */ error) { + console.error('打开商品自动化规则失败', error); + alert('无法加载该商品的自动化规则'); + } finally { + if (!cancelled) { + setLoading(false); + onDeliveryTargetHandled?.(); + } + } + }; + void openLinkedRule(); + return /* 当前回调取消外部联动请求。 */ () => { cancelled = true; }; + }, [buildAutomationDraft, initialDeliveryTarget, onDeliveryTargetHandled, openAutomationRule, setActiveTab, setAutomationRules, setCards, setItems, setLoading, setSelectedAccountId]); + + // openNewAutomationRule 创建指定类型的规则草稿并打开弹窗。 + const openNewAutomationRule = useCallback(/* openNewAction 创建新规则草稿。 */ (trigger: AutomationTriggerType = 'order_paid') => { + if (!selectedAccountId) { + alert('请先选择账号'); + return; + } + setEditingAutomationRule(buildAutomationDraft(trigger)); + setShowAutomationModal(true); + }, [buildAutomationDraft, selectedAccountId]); + + // handleTriggerChange 切换规则触发类型并保留当前卡密组。 + const handleTriggerChange = useCallback(/* triggerAction 切换规则触发类型。 */ (trigger: AutomationTriggerType) => { + if (!editingAutomationRule) return; + // currentCardID 保存当前规则选中的卡密组。 + const currentCardID = editingAutomationRule.variants?.find(/* 当前回调查找当前卡密组。 */ variant => variant.card_id)?.card_id || editingAutomationRule.actions?.find(/* 当前回调查找发卡动作。 */ action => action.action_type === 'send_card')?.card_id || editingAutomationRule.card_group_id || 0; + // itemLabel 保存当前规则商品名称。 + const itemLabel = selectedRuleItem?.item_title || editingAutomationRule.item_title || editingAutomationRule.item_id || ''; + setEditingAutomationRule({ + ...editingAutomationRule, trigger_type: trigger, + name: shouldReplaceGeneratedName(editingAutomationRule.name) ? defaultRuleName(trigger, itemLabel) : editingAutomationRule.name, + card_group_id: currentCardID, config_json: trigger === 'review_missing_timeout' ? buildReviewConfig(editingAutomationRule.config_json) : '{}', + actions: cardActionsForTrigger(trigger, currentCardID), + variants: trigger === 'review_missing_timeout' ? [] : (editingAutomationRule.variants?.length ? editingAutomationRule.variants : [{ ...emptyVariant(), card_id: currentCardID }]), + }); + }, [editingAutomationRule, selectedRuleItem]); + + // handleAutomationItemChange 切换规则商品并同步商品标题和默认名称。 + const handleAutomationItemChange = useCallback(/* itemAction 切换规则绑定商品。 */ (itemID: string) => { + if (!editingAutomationRule) return; + // item 保存当前账号下选择的商品。 + const item = items.find(/* 当前回调查找切换后的商品。 */ candidate => candidate.cookie_id === (editingAutomationRule.cookie_id || selectedAccountId) && candidate.item_id === itemID); + // itemLabel 保存商品名称或商品 ID。 + const itemLabel = item?.item_title || itemID; + setEditingAutomationRule({ + ...editingAutomationRule, item_id: itemID, item_title: item?.item_title || '', item_keyword: itemLabel, + name: shouldReplaceGeneratedName(editingAutomationRule.name) ? defaultRuleName(currentTrigger, itemLabel) : editingAutomationRule.name, + }); + }, [currentTrigger, editingAutomationRule, items, selectedAccountId]); + + // updateVariant 更新规则中的一行发货规格。 + const updateVariant = useCallback(/* variantAction 更新规则规格。 */ (index: number, patch: Partial) => { + if (!editingAutomationRule) return; + // next 保存合并后的规格列表。 + const next = displayVariants.map(/* 当前回调合并指定规格字段。 */ (variant, variantIndex) => variantIndex === index ? { ...variant, ...patch } : variant); + setEditingAutomationRule({ ...editingAutomationRule, variants: next, card_group_id: next[0]?.card_id || 0 }); + }, [displayVariants, editingAutomationRule]); + + // appendDeliveryContent 在规格编辑器末尾追加一行。 + const appendDeliveryContent = useCallback(/* appendVariantAction 追加规则规格。 */ () => { + if (!editingAutomationRule) return; + // previous 保存上一行规格,用于多规格商品复制规格名称和值。 + const previous = displayVariants[displayVariants.length - 1]; + setEditingAutomationRule({ + ...editingAutomationRule, + variants: [...displayVariants, { ...emptyVariant(), spec_name: isMultiSpecRule ? previous?.spec_name || '' : '', spec_value: isMultiSpecRule ? previous?.spec_value || '' : '' }], + }); + }, [displayVariants, editingAutomationRule, isMultiSpecRule]); + + // handleSaveAutomationRule 校验并保存当前自动化规则。 + const handleSaveAutomationRule = useCallback(/* saveRuleAction 保存自动化规则。 */ async () => { + if (!editingAutomationRule || automationSubmitState.submitting) return; + // trigger 保存当前规则触发类型。 + const trigger = (editingAutomationRule.trigger_type || 'order_paid') as AutomationTriggerType; + if (!editingAutomationRule.cookie_id) return alert('请选择账号'); + // variants 保存当前规格列表。 + const variants = editingAutomationRule.variants?.length ? editingAutomationRule.variants : []; + if (trigger !== 'review_missing_timeout') { + if (!variants.length || variants.some(/* 当前回调校验卡密组是否已选择。 */ variant => !variant.card_id)) return alert(trigger === 'buyer_reviewed' ? '请选择评价赠品卡密库存' : '请选择发货卡密库存'); + if (isMultiSpecRule && variants.some(/* 当前回调校验多规格字段。 */ variant => !variant.spec_name.trim() || !variant.spec_value.trim())) return alert('多规格商品必须填写每一行的规格名称和规格值'); + } + if (trigger === 'review_missing_timeout') { + // text 保存求评价动作的文案。 + const text = editingAutomationRule.actions?.find(/* 当前回调查找求评价文案动作。 */ action => action.action_type === 'send_text')?.message_template || ''; + if (!text.trim()) return alert('请填写求评价文案'); + } + // saveVariants 保存归一化后的发货规格。 + const saveVariants = trigger === 'review_missing_timeout' ? [] : variants.map(/* 当前回调归一化发货规格字段。 */ variant => ({ ...variant, spec_name: isMultiSpecRule ? variant.spec_name.trim() : '', spec_value: isMultiSpecRule ? variant.spec_value.trim() : '', delivery_count: Math.max(1, Number(variant.delivery_count) || 1), enabled: variant.enabled !== false })); + setAutomationSubmitState(startRuleSubmission(automationSubmitState)); + // succeeded 记录保存是否成功。 + let succeeded = false; + try { + await updateShippingRule({ ...editingAutomationRule, trigger_type: trigger, name: (editingAutomationRule.name || '').trim() || defaultRuleName(trigger, selectedRuleItem?.item_title || editingAutomationRule.item_id || ''), config_json: trigger === 'review_missing_timeout' ? buildReviewConfig(editingAutomationRule.config_json) : (editingAutomationRule.config_json || '{}'), actions: editingAutomationRule.actions?.length ? editingAutomationRule.actions : cardActionsForTrigger(trigger, saveVariants[0]?.card_id || editingAutomationRule.card_group_id || 0), variants: saveVariants }); + setShowAutomationModal(false); + await Promise.all([loadAutomationRules(), loadReferenceData()]); + alert('保存成功'); + succeeded = true; + } catch (/* error 表示自动化规则保存异常。 */ error) { + console.error('保存自动化规则失败:', error); + alert('保存失败:' + (error as Error).message); + } finally { + setAutomationSubmitState(/* current 保存自动化提交状态。 */ current => finishRuleSubmission(current, succeeded)); + } + }, [automationSubmitState, editingAutomationRule, isMultiSpecRule, loadAutomationRules, loadReferenceData, selectedRuleItem]); + + // handleDeleteAutomation 删除自动化规则并刷新列表。 + const handleDeleteAutomation = useCallback(/* deleteRuleAction 删除自动化规则。 */ async (id: string) => { + if (!confirm('确定删除该自动化规则吗?')) return; + try { await deleteShippingRule(id); await loadAutomationRules(); alert('删除成功'); } catch (/* error 表示自动化规则删除异常。 */ error) { alert('删除失败:' + (error as Error).message); } + }, [loadAutomationRules]); + + // handleToggleAutomation 切换规则启用状态并刷新列表。 + const handleToggleAutomation = useCallback(/* toggleRuleAction 切换自动化规则状态。 */ async (rule: ShippingRule) => { + try { await updateShippingRule({ ...rule, enabled: !rule.enabled }); await loadAutomationRules(); } catch (/* error 表示自动化规则状态更新异常。 */ error) { alert('操作失败:' + (error as Error).message); } + }, [loadAutomationRules]); + + // handleResolveRunIssue 处理自动化运行的人工恢复决策。 + const handleResolveRunIssue = useCallback(/* resolveRunAction 处理自动化运行异常。 */ async (id: number, resolution: 'continue' | 'retry' | 'cancel') => { + // prompt 保存当前恢复操作的确认文案。 + const prompt = resolution === 'continue' ? '确认外部动作已经执行成功,并跳到下一步吗?' : resolution === 'retry' ? '确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。' : '确认终止该自动化运行吗?'; + if (!confirm(prompt)) return; + try { await resolveAutomationRun(id, resolution); await loadAutomationRules(); } catch (/* error 表示自动化运行恢复异常。 */ error) { alert('处理失败:' + (error as Error).message); } + }, [loadAutomationRules]); + + // handleResolveDeferredIssue 处理延迟自动化任务的重试或忽略。 + const handleResolveDeferredIssue = useCallback(/* resolveDeferredAction 处理延迟任务异常。 */ async (id: number, resolution: 'retry' | 'dismiss') => { + if (!confirm(resolution === 'retry' ? '确认重新执行该任务吗?' : '确认忽略并删除该异常任务吗?')) return; + try { await resolveDeferredAutomationTask(id, resolution); await loadAutomationRules(); } catch (/* error 表示延迟任务恢复异常。 */ error) { alert('处理失败:' + (error as Error).message); } + }, [loadAutomationRules]); + + // handleAddReplyRule 打开一个空的关键词回复草稿。 + const handleAddReplyRule = useCallback(/* addReplyAction 创建关键词回复草稿。 */ () => { + if (!selectedAccountId) return alert('请先选择账号'); + setEditingReplyRule({ keyword: '', reply_content: '', image_url: '', item_id: '', type: 'text', match_type: 'fuzzy', enabled: true }); + setShowReplyModal(true); + }, [selectedAccountId]); + + // handleSaveReplyRule 校验并保存关键词回复规则。 + const handleSaveReplyRule = useCallback(/* saveReplyAction 保存关键词回复。 */ async () => { + if (!editingReplyRule || !selectedAccountId || replySubmitState.submitting) return; + // hasReplyContent 表示当前回复是否填写了文字或图片。 + const hasReplyContent = editingReplyRule.type === 'image' ? Boolean(editingReplyRule.image_url?.trim()) : Boolean(editingReplyRule.reply_content?.trim()); + if (!editingReplyRule.keyword?.trim() || !hasReplyContent) return alert('请填写关键词和回复内容'); + setReplySubmitState(startRuleSubmission(replySubmitState)); + // succeeded 记录保存是否成功。 + let succeeded = false; + try { await updateReplyRule({ ...editingReplyRule, match_type: 'fuzzy', enabled: true }, selectedAccountId); setShowReplyModal(false); await loadReplyRules(); alert('保存成功'); succeeded = true; } catch (/* error 表示关键词回复保存异常。 */ error) { alert('保存失败:' + (error as Error).message); } finally { setReplySubmitState(/* current 保存关键词提交状态。 */ current => finishRuleSubmission(current, succeeded)); } + }, [editingReplyRule, loadReplyRules, replySubmitState, selectedAccountId]); + + // handleDeleteReply 删除指定关键词回复并刷新列表。 + const handleDeleteReply = useCallback(/* deleteReplyAction 删除关键词回复。 */ async (id: string) => { + if (!selectedAccountId || !confirm('确定删除该回复规则吗?')) return; + try { await deleteReplyRule(id, selectedAccountId); await loadReplyRules(); alert('删除成功'); } catch (/* error 表示关键词回复删除异常。 */ error) { alert('删除失败:' + (error as Error).message); } + }, [loadReplyRules, selectedAccountId]); + + // openDefaultReplyModal 加载指定账号的默认回复配置并打开弹窗。 + const openDefaultReplyModal = useCallback(/* openDefaultAction 加载默认回复草稿。 */ async (cookieID = selectedAccountId) => { + if (!cookieID) return alert('请先选择账号'); + try { + // data 保存服务端返回的默认回复配置。 + const data = await getDefaultReply(cookieID); + setDefaultForm({ cookie_id: cookieID, enabled: data.enabled, reply_content: data.reply_content, reply_once: data.reply_once, reply_image_url: data.reply_image_url || '' }); + } catch { + setDefaultForm({ cookie_id: cookieID, enabled: false, reply_content: '', reply_once: false, reply_image_url: '' }); + } + setShowDefaultModal(true); + }, [selectedAccountId]); + + // handleSaveDefaultReply 校验并保存账号默认回复。 + const handleSaveDefaultReply = useCallback(/* saveDefaultAction 保存默认回复。 */ async () => { + if (defaultReplySubmitState.submitting) return; + if (!defaultForm.cookie_id) return alert('请先选择账号'); + if (defaultForm.enabled && !defaultForm.reply_content.trim() && !defaultForm.reply_image_url.trim()) return alert('启用默认回复时,请填写回复内容或图片 URL'); + setDefaultReplySubmitState(startRuleSubmission(defaultReplySubmitState)); + // succeeded 记录保存是否成功。 + let succeeded = false; + try { await updateDefaultReply(defaultForm.cookie_id, { enabled: defaultForm.enabled, reply_content: defaultForm.reply_content, reply_once: defaultForm.reply_once, reply_image_url: defaultForm.reply_image_url }); setShowDefaultModal(false); await loadDefaultReplies(); alert('保存成功'); succeeded = true; } catch (/* error 表示默认回复保存异常。 */ error) { alert('保存失败:' + (error as Error).message); } finally { setDefaultReplySubmitState(/* current 保存默认回复提交状态。 */ current => finishRuleSubmission(current, succeeded)); } + }, [defaultForm, defaultReplySubmitState, loadDefaultReplies]); + + // handleDeleteDefaultReply 删除账号默认回复配置。 + const handleDeleteDefaultReply = useCallback(/* deleteDefaultAction 删除默认回复。 */ async (cookieID: string) => { + if (!confirm('确定删除该账号默认回复吗?')) return; + try { await deleteDefaultReply(cookieID); await loadDefaultReplies(); alert('删除成功'); } catch (/* error 表示默认回复删除异常。 */ error) { alert('删除失败:' + (error as Error).message); } + }, [loadDefaultReplies]); + + // handleClearDefaultReplyRecords 清空账号默认回复的会话记录。 + const handleClearDefaultReplyRecords = useCallback(/* clearDefaultRecordsAction 清空默认回复记录。 */ async (cookieID: string) => { + if (!confirm('确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。')) return; + try { await clearDefaultReplyRecords(cookieID); alert('清空成功'); } catch (/* error 表示默认回复记录清理异常。 */ error) { alert('清空失败:' + (error as Error).message); } + }, []); + + return { + showAutomationModal, setShowAutomationModal, showReplyModal, setShowReplyModal, showDefaultModal, setShowDefaultModal, + automationSubmitState, replySubmitState, defaultReplySubmitState, editingAutomationRule, setEditingAutomationRule, + editingReplyRule, setEditingReplyRule, defaultForm, setDefaultForm, selectedRuleItem, isMultiSpecRule, currentTrigger, + currentMeta, reviewConfig, displayVariants, buildAutomationDraft, openAutomationRule, openNewAutomationRule, + handleTriggerChange, handleAutomationItemChange, updateVariant, appendDeliveryContent, handleSaveAutomationRule, + handleDeleteAutomation, handleToggleAutomation, handleResolveRunIssue, handleResolveDeferredIssue, handleAddReplyRule, + handleSaveReplyRule, handleDeleteReply, openDefaultReplyModal, handleSaveDefaultReply, handleDeleteDefaultReply, + handleClearDefaultReplyRecords, + }; +}; diff --git a/frontend/components/Rules.tsx b/frontend/components/Rules.tsx index 3b9b324..8ee39bc 100644 --- a/frontend/components/Rules.tsx +++ b/frontend/components/Rules.tsx @@ -1,21 +1,6 @@ -import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import React, { useEffect, useMemo, useState } from 'react'; import { createPortal } from 'react-dom'; -import type { AutomationTriggerType, ReplyRule, ShippingRule, ShippingVariant } from '../app/features/rules/types'; -import { - clearDefaultReplyRecords, - deleteDefaultReply, - deleteReplyRule, - deleteShippingRule, - getCards, - getDefaultReply, - getItems, - getShippingRules, - updateDefaultReply, - updateReplyRule, - updateShippingRule, - resolveAutomationRun, - resolveDeferredAutomationTask, -} from '../app/features/rules/api'; +import type { AutomationTriggerType } from '../app/features/rules/types'; import { AlertCircle, Bot, @@ -39,9 +24,9 @@ import { import { AutomationIssuePanel } from '../app/features/rules/components/AutomationIssuePanel'; import { useRulesData } from '../app/features/rules/hooks'; import { filterAutomationIssues } from '../app/features/rules/issueState'; -import { triggerMeta, triggerOrder, emptyVariant, parseJSONObject, buildReviewConfig, defaultRuleName, shouldReplaceGeneratedName, cardActionsForTrigger, actionSummary, accentClasses, statusPill, accountLabel, boolFlag } from '../app/features/rules/utils'; -import type { RulesProps, RulesTab, DefaultReplyForm } from '../app/features/rules/types'; -import { finishRuleSubmission, idleRuleSubmitState, startRuleSubmission, type RuleSubmitState } from '../app/features/rules/interactionState'; +import { triggerMeta, triggerOrder, actionSummary, accentClasses, statusPill, accountLabel, buildReviewConfig, cardActionsForTrigger } from '../app/features/rules/utils'; +import type { RulesProps, RulesTab } from '../app/features/rules/types'; +import { useRuleActions } from '../app/features/rules/ruleActions'; // Rules 是规则 feature 在旧页面目录下保留的兼容入口组件。 const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHandled }) => { @@ -98,32 +83,33 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa refresh, } = rulesData; - // [showAutomationModal, 解构得到当前 Hook 返回的状态和操作函数。 - const [showAutomationModal, setShowAutomationModal] = useState(false); - // [showReplyModal, 解构得到当前 Hook 返回的状态和操作函数。 - const [showReplyModal, setShowReplyModal] = useState(false); - // [showDefaultModal, 解构得到当前 Hook 返回的状态和操作函数。 - const [showDefaultModal, setShowDefaultModal] = useState(false); - // automationSubmitState 防止自动化规则保存按钮在请求期间重复提交。 - const [automationSubmitState, setAutomationSubmitState] = useState(idleRuleSubmitState); - // replySubmitState 防止关键词回复保存按钮在请求期间重复提交。 - const [replySubmitState, setReplySubmitState] = useState(idleRuleSubmitState); - // defaultReplySubmitState 防止默认回复保存按钮在请求期间重复提交。 - const [defaultReplySubmitState, setDefaultReplySubmitState] = useState(idleRuleSubmitState); - // [editingAutomationRule, 解构得到当前 Hook 返回的状态和操作函数。 - const [editingAutomationRule, setEditingAutomationRule] = useState | null>(null); - // [editingReplyRule, 解构得到当前 Hook 返回的状态和操作函数。 - const [editingReplyRule, setEditingReplyRule] = useState | null>(null); - // [defaultForm, 解构得到当前 Hook 返回的状态和操作函数。 - const [defaultForm, setDefaultForm] = useState({ - cookie_id: '', - enabled: false, - reply_content: '', - reply_once: false, - reply_image_url: '', + // ruleActions 规则 feature 提供弹窗状态、编辑草稿和所有保存删除动作。 + const ruleActions = useRuleActions({ + selectedAccountId, + setSelectedAccountId, + setActiveTab, + items, + setAutomationRules, + setCards, + setItems, + setLoading, + loadAutomationRules, + loadReferenceData, + loadReplyRules, + loadDefaultReplies, + initialDeliveryTarget, + onDeliveryTargetHandled, }); - // selectedAccount 处理当前选择(ed账号)。 - const selectedAccount = accounts.find(/* 当前回调处理集合中的单个元素。 */ account => account.id === selectedAccountId); + // 解构规则动作,保持旧页面 JSX 的字段名称和行为不变。 + const { + showAutomationModal, setShowAutomationModal, showReplyModal, setShowReplyModal, showDefaultModal, setShowDefaultModal, + automationSubmitState, replySubmitState, defaultReplySubmitState, editingAutomationRule, setEditingAutomationRule, + editingReplyRule, setEditingReplyRule, defaultForm, setDefaultForm, selectedRuleItem, isMultiSpecRule, currentTrigger, + currentMeta, reviewConfig, displayVariants, openAutomationRule, openNewAutomationRule, handleTriggerChange, + handleAutomationItemChange, updateVariant, appendDeliveryContent, handleSaveAutomationRule, handleDeleteAutomation, + handleToggleAutomation, handleResolveRunIssue, handleResolveDeferredIssue, handleAddReplyRule, handleSaveReplyRule, + handleDeleteReply, openDefaultReplyModal, handleSaveDefaultReply, handleDeleteDefaultReply, handleClearDefaultReplyRecords, + } = ruleActions; useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => { // timer 定时器。 @@ -191,478 +177,6 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa return items.filter(/* 当前回调处理集合中的单个元素。 */ item => item.cookie_id === cookieID); }, [editingAutomationRule?.cookie_id, items, selectedAccountId]); - // selectedRuleItem 处理当前选择(ed规则商品)。 - const selectedRuleItem = useMemo(/* 当前回调计算并缓存派生数据。 */ () => { - if (!editingAutomationRule?.cookie_id || !editingAutomationRule?.item_id) return undefined; - return items.find(/* 当前回调处理集合中的单个元素。 */ item => item.cookie_id === editingAutomationRule.cookie_id && item.item_id === editingAutomationRule.item_id); - }, [editingAutomationRule?.cookie_id, editingAutomationRule?.item_id, items]); - - // isMultiSpecRule isMultiSpec规则,负责当前功能中的对应处理。 - const isMultiSpecRule = boolFlag(selectedRuleItem?.is_multi_spec); - // currentTrigger 当前触发条件。 - const currentTrigger = (editingAutomationRule?.trigger_type || 'order_paid') as AutomationTriggerType; - // currentMeta 当前触发元数据。 - const currentMeta = triggerMeta[currentTrigger]; - // reviewConfig 评价配置。 - const reviewConfig = parseJSONObject(editingAutomationRule?.config_json); - - // buildAutomationDraft 构建自动化Draft,负责当前功能中的对应处理。 - const buildAutomationDraft = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ ( - trigger: AutomationTriggerType = 'order_paid', - cookieID = selectedAccountId, - itemID = '', - ): Partial => { - // item 商品。 - const item = items.find(/* 当前回调处理集合中的单个元素。 */ candidate => candidate.cookie_id === cookieID && candidate.item_id === itemID); - // itemLabel 商品标签,负责当前功能中的对应处理。 - const itemLabel = item?.item_title || itemID; - return { - name: defaultRuleName(trigger, itemLabel), - trigger_type: trigger, - cookie_id: cookieID, - item_id: itemID, - item_title: item?.item_title || '', - item_keyword: itemLabel, - card_group_id: 0, - priority: 100, - enabled: true, - config_json: trigger === 'review_missing_timeout' ? buildReviewConfig() : '{}', - actions: cardActionsForTrigger(trigger), - variants: trigger === 'review_missing_timeout' ? [] : [emptyVariant()], - }; - }, [items, selectedAccountId]); - - // openAutomationRule 打开当前界面(自动化规则)。 - const openAutomationRule = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ (rule: ShippingRule) => { - // trigger 触发条件。 - const trigger = (rule.trigger_type || 'order_paid') as AutomationTriggerType; - setEditingAutomationRule({ - ...rule, - trigger_type: trigger, - config_json: trigger === 'review_missing_timeout' ? buildReviewConfig(rule.config_json) : (rule.config_json || '{}'), - actions: rule.actions?.length ? rule.actions.map(/* 当前回调处理集合中的单个元素。 */ action => ({ ...action })) : cardActionsForTrigger(trigger, rule.card_group_id), - variants: rule.variants?.length ? rule.variants.map(/* 当前回调处理集合中的单个元素。 */ variant => ({ ...variant })) : (trigger === 'review_missing_timeout' ? [] : [emptyVariant()]), - }); - setShowAutomationModal(true); - }, []); - - useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => { - if (!initialDeliveryTarget) return; - // cancelled 取消当前操作(led)。 - let cancelled = false; - - // openLinkedRule 打开当前界面(Linked规则)。 - const openLinkedRule = async () => { - setActiveTab('automation'); - setSelectedAccountId(initialDeliveryTarget.cookieId); - setLoading(true); - try { - // [ruleList, 解构得到当前 Hook 返回的状态和操作函数。 - const [ruleList, itemList, cardList] = await Promise.all([ - getShippingRules(), - getItems(), - getCards().catch(/* 当前回调处理异步操作结果。 */ error => { - console.warn('加载卡密库存失败,不阻断打开自动化规则', error); - return []; - }), - ]); - if (cancelled) return; - setAutomationRules(ruleList); - setItems(itemList); - setCards(cardList); - // rule 规则。 - const rule = ruleList.find(/* 当前回调处理集合中的单个元素。 */ candidate => - candidate.cookie_id === initialDeliveryTarget.cookieId && - candidate.item_id === initialDeliveryTarget.itemId && - candidate.trigger_type === 'order_paid' - ); - if (rule) { - openAutomationRule(rule); - } else { - // item 商品。 - const item = itemList.find(/* 当前回调处理集合中的单个元素。 */ candidate => - candidate.cookie_id === initialDeliveryTarget.cookieId && - candidate.item_id === initialDeliveryTarget.itemId - ); - setEditingAutomationRule({ - ...buildAutomationDraft('order_paid', initialDeliveryTarget.cookieId, initialDeliveryTarget.itemId), - item_title: item?.item_title || '', - item_keyword: item?.item_title || initialDeliveryTarget.itemId, - name: defaultRuleName('order_paid', item?.item_title || initialDeliveryTarget.itemId), - }); - setShowAutomationModal(true); - } - } catch (/* error 表示错误。 */ error) { - console.error('打开商品自动化规则失败', error); - alert('无法加载该商品的自动化规则'); - } finally { - if (!cancelled) { - setLoading(false); - onDeliveryTargetHandled?.(); - } - } - }; - - void openLinkedRule(); - return /* 当前回调处理用户交互或异步状态变化。 */ () => { cancelled = true; }; - }, [buildAutomationDraft, initialDeliveryTarget, onDeliveryTargetHandled, openAutomationRule]); - - // openNewAutomationRule 打开当前界面(New自动化规则)。 - const openNewAutomationRule = (trigger: AutomationTriggerType = 'order_paid') => { - if (!selectedAccountId) { - alert('请先选择账号'); - return; - } - setEditingAutomationRule(buildAutomationDraft(trigger)); - setShowAutomationModal(true); - }; - - // handleTriggerChange 处理当前用户操作(触发条件Change)。 - const handleTriggerChange = (trigger: AutomationTriggerType) => { - if (!editingAutomationRule) return; - // currentCardID 当前卡密组标识。 - const currentCardID = - editingAutomationRule.variants?.find(/* 当前回调处理集合中的单个元素。 */ variant => variant.card_id)?.card_id || - editingAutomationRule.actions?.find(/* 当前回调处理集合中的单个元素。 */ action => action.action_type === 'send_card')?.card_id || - editingAutomationRule.card_group_id || - 0; - // itemLabel 商品标签,负责当前功能中的对应处理。 - const itemLabel = selectedRuleItem?.item_title || editingAutomationRule.item_title || editingAutomationRule.item_id || ''; - setEditingAutomationRule({ - ...editingAutomationRule, - trigger_type: trigger, - name: shouldReplaceGeneratedName(editingAutomationRule.name) - ? defaultRuleName(trigger, itemLabel) - : editingAutomationRule.name, - card_group_id: currentCardID, - config_json: trigger === 'review_missing_timeout' ? buildReviewConfig(editingAutomationRule.config_json) : '{}', - actions: cardActionsForTrigger(trigger, currentCardID), - variants: trigger === 'review_missing_timeout' - ? [] - : (editingAutomationRule.variants?.length ? editingAutomationRule.variants : [{ ...emptyVariant(), card_id: currentCardID }]), - }); - }; - - // handleAutomationItemChange 处理当前用户操作(自动化商品Change)。 - const handleAutomationItemChange = (itemID: string) => { - if (!editingAutomationRule) return; - // item 商品。 - const item = items.find(/* 当前回调处理集合中的单个元素。 */ candidate => - candidate.cookie_id === (editingAutomationRule.cookie_id || selectedAccountId) && - candidate.item_id === itemID - ); - // itemLabel 商品标签,负责当前功能中的对应处理。 - const itemLabel = item?.item_title || itemID; - setEditingAutomationRule({ - ...editingAutomationRule, - item_id: itemID, - item_title: item?.item_title || '', - item_keyword: itemLabel, - name: shouldReplaceGeneratedName(editingAutomationRule.name) - ? defaultRuleName(currentTrigger, itemLabel) - : editingAutomationRule.name, - }); - }; - - // displayVariants 展示规格列表。 - const displayVariants = editingAutomationRule?.variants?.length - ? editingAutomationRule.variants - : [emptyVariant()]; - - // updateVariant 更新当前数据(Variant)。 - const updateVariant = (index: number, patch: Partial) => { - if (!editingAutomationRule) return; - // next 下一项。 - const next = displayVariants.map(/* 当前回调处理集合中的单个元素。 */ (variant, variantIndex) => - variantIndex === index ? { ...variant, ...patch } : variant - ); - setEditingAutomationRule({ - ...editingAutomationRule, - variants: next, - card_group_id: next[0]?.card_id || 0, - }); - }; - - // appendDeliveryContent 追加发货内容。 - const appendDeliveryContent = () => { - if (!editingAutomationRule) return; - // previous 上一项。 - const previous = displayVariants[displayVariants.length - 1]; - setEditingAutomationRule({ - ...editingAutomationRule, - variants: [ - ...displayVariants, - { - ...emptyVariant(), - spec_name: isMultiSpecRule ? previous?.spec_name || '' : '', - spec_value: isMultiSpecRule ? previous?.spec_value || '' : '', - }, - ], - }); - }; - - // handleSaveAutomationRule 处理当前用户操作(Save自动化规则)。 - const handleSaveAutomationRule = async () => { - if (!editingAutomationRule || automationSubmitState.submitting) return; - // trigger 触发条件。 - const trigger = (editingAutomationRule.trigger_type || 'order_paid') as AutomationTriggerType; - if (!editingAutomationRule.cookie_id) { - alert('请选择账号'); - return; - } - - // variants 规格列表。 - const variants = editingAutomationRule.variants?.length ? editingAutomationRule.variants : []; - if (trigger !== 'review_missing_timeout') { - if (!variants.length || variants.some(/* 当前回调处理集合中的单个元素。 */ variant => !variant.card_id)) { - alert(trigger === 'buyer_reviewed' ? '请选择评价赠品卡密库存' : '请选择发货卡密库存'); - return; - } - if (isMultiSpecRule && variants.some(/* 当前回调处理集合中的单个元素。 */ variant => !variant.spec_name.trim() || !variant.spec_value.trim())) { - alert('多规格商品必须填写每一行的规格名称和规格值'); - return; - } - } - - if (trigger === 'review_missing_timeout') { - // text 文本。 - const text = editingAutomationRule.actions?.find(/* 当前回调处理集合中的单个元素。 */ action => action.action_type === 'send_text')?.message_template || ''; - if (!text.trim()) { - alert('请填写求评价文案'); - return; - } - } - - // saveVariants 保存当前数据(Variants)。 - const saveVariants = trigger === 'review_missing_timeout' - ? [] - : variants.map(variant => ({/* 当前回调处理集合中的单个元素。 */ - ...variant, - spec_name: isMultiSpecRule ? variant.spec_name.trim() : '', - spec_value: isMultiSpecRule ? variant.spec_value.trim() : '', - delivery_count: Math.max(1, Number(variant.delivery_count) || 1), - enabled: variant.enabled !== false, - })); - - setAutomationSubmitState(startRuleSubmission(automationSubmitState)); - // succeeded 是否成功。 - let succeeded = false; - try { - await updateShippingRule({ - ...editingAutomationRule, - trigger_type: trigger, - name: (editingAutomationRule.name || '').trim() || - defaultRuleName(trigger, selectedRuleItem?.item_title || editingAutomationRule.item_id || ''), - config_json: trigger === 'review_missing_timeout' - ? buildReviewConfig(editingAutomationRule.config_json) - : (editingAutomationRule.config_json || '{}'), - actions: editingAutomationRule.actions?.length - ? editingAutomationRule.actions - : cardActionsForTrigger(trigger, saveVariants[0]?.card_id || editingAutomationRule.card_group_id || 0), - variants: saveVariants, - }); - setShowAutomationModal(false); - await Promise.all([loadAutomationRules(), loadReferenceData()]); - alert('保存成功'); - succeeded = true; - } catch (/* error 表示错误。 */ error) { - console.error('保存自动化规则失败:', error); - alert('保存失败:' + (error as Error).message); - } finally { - setAutomationSubmitState(/* 当前回调处理用户交互或异步状态变化。 */ current => finishRuleSubmission(current, succeeded)); - } - }; - - // handleDeleteAutomation 处理当前用户操作(Delete自动化)。 - const handleDeleteAutomation = async (id: string) => { - if (!confirm('确定删除该自动化规则吗?')) return; - try { - await deleteShippingRule(id); - await loadAutomationRules(); - alert('删除成功'); - } catch (/* error 表示错误。 */ error) { - alert('删除失败:' + (error as Error).message); - } - }; - - // handleToggleAutomation 处理当前用户操作(Toggle自动化)。 - const handleToggleAutomation = async (rule: ShippingRule) => { - try { - await updateShippingRule({ ...rule, enabled: !rule.enabled }); - await loadAutomationRules(); - } catch (/* error 表示错误。 */ error) { - alert('操作失败:' + (error as Error).message); - } - }; - - // handleResolveRunIssue 处理当前用户操作(ResolveRun问题)。 - const handleResolveRunIssue = async (id: number, resolution: 'continue' | 'retry' | 'cancel') => { - // prompt 提示文案。 - const prompt = resolution === 'continue' - ? '确认外部动作已经执行成功,并跳到下一步吗?' - : resolution === 'retry' - ? '确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。' - : '确认终止该自动化运行吗?'; - if (!confirm(prompt)) return; - try { - await resolveAutomationRun(id, resolution); - await loadAutomationRules(); - } catch (/* error 表示错误。 */ error) { - alert('处理失败:' + (error as Error).message); - } - }; - - // handleResolveDeferredIssue 处理当前用户操作(ResolveDeferred问题)。 - const handleResolveDeferredIssue = async (id: number, resolution: 'retry' | 'dismiss') => { - if (!confirm(resolution === 'retry' ? '确认重新执行该任务吗?' : '确认忽略并删除该异常任务吗?')) return; - try { - await resolveDeferredAutomationTask(id, resolution); - await loadAutomationRules(); - } catch (/* error 表示错误。 */ error) { - alert('处理失败:' + (error as Error).message); - } - }; - - // handleAddReplyRule 处理当前用户操作(Add回复规则)。 - const handleAddReplyRule = () => { - if (!selectedAccountId) { - alert('请先选择账号'); - return; - } - setEditingReplyRule({ - keyword: '', - reply_content: '', - image_url: '', - item_id: '', - type: 'text', - match_type: 'fuzzy', - enabled: true, - }); - setShowReplyModal(true); - }; - - // handleSaveReplyRule 处理当前用户操作(Save回复规则)。 - const handleSaveReplyRule = async () => { - if (!editingReplyRule || !selectedAccountId || replySubmitState.submitting) return; - // hasReplyContent 是否包含回复内容。 - const hasReplyContent = editingReplyRule.type === 'image' - ? Boolean(editingReplyRule.image_url?.trim()) - : Boolean(editingReplyRule.reply_content?.trim()); - if (!editingReplyRule.keyword?.trim() || !hasReplyContent) { - alert('请填写关键词和回复内容'); - return; - } - setReplySubmitState(startRuleSubmission(replySubmitState)); - // succeeded 是否成功。 - let succeeded = false; - try { - await updateReplyRule({ ...editingReplyRule, match_type: 'fuzzy', enabled: true }, selectedAccountId); - setShowReplyModal(false); - await loadReplyRules(); - alert('保存成功'); - succeeded = true; - } catch (/* error 表示错误。 */ error) { - alert('保存失败:' + (error as Error).message); - } finally { - setReplySubmitState(/* 当前回调处理用户交互或异步状态变化。 */ current => finishRuleSubmission(current, succeeded)); - } - }; - - // handleDeleteReply 处理当前用户操作(Delete回复)。 - const handleDeleteReply = async (id: string) => { - if (!selectedAccountId || !confirm('确定删除该回复规则吗?')) return; - try { - await deleteReplyRule(id, selectedAccountId); - await loadReplyRules(); - alert('删除成功'); - } catch (/* error 表示错误。 */ error) { - alert('删除失败:' + (error as Error).message); - } - }; - - // openDefaultReplyModal 打开当前界面(Default回复Modal)。 - const openDefaultReplyModal = async (cookieID = selectedAccountId) => { - if (!cookieID) { - alert('请先选择账号'); - return; - } - try { - // data 数据。 - const data = await getDefaultReply(cookieID); - setDefaultForm({ - cookie_id: cookieID, - enabled: data.enabled, - reply_content: data.reply_content, - reply_once: data.reply_once, - reply_image_url: data.reply_image_url || '', - }); - } catch { - setDefaultForm({ - cookie_id: cookieID, - enabled: false, - reply_content: '', - reply_once: false, - reply_image_url: '', - }); - } - setShowDefaultModal(true); - }; - - // handleSaveDefaultReply 处理当前用户操作(SaveDefault回复)。 - const handleSaveDefaultReply = async () => { - if (defaultReplySubmitState.submitting) return; - if (!defaultForm.cookie_id) { - alert('请先选择账号'); - return; - } - if (defaultForm.enabled && !defaultForm.reply_content.trim() && !defaultForm.reply_image_url.trim()) { - alert('启用默认回复时,请填写回复内容或图片 URL'); - return; - } - setDefaultReplySubmitState(startRuleSubmission(defaultReplySubmitState)); - // succeeded 是否成功。 - let succeeded = false; - try { - await updateDefaultReply(defaultForm.cookie_id, { - enabled: defaultForm.enabled, - reply_content: defaultForm.reply_content, - reply_once: defaultForm.reply_once, - reply_image_url: defaultForm.reply_image_url, - }); - setShowDefaultModal(false); - await loadDefaultReplies(); - alert('保存成功'); - succeeded = true; - } catch (/* error 表示错误。 */ error) { - alert('保存失败:' + (error as Error).message); - } finally { - setDefaultReplySubmitState(/* 当前回调处理用户交互或异步状态变化。 */ current => finishRuleSubmission(current, succeeded)); - } - }; - - // handleDeleteDefaultReply 处理当前用户操作(DeleteDefault回复)。 - const handleDeleteDefaultReply = async (cookieID: string) => { - if (!confirm('确定删除该账号默认回复吗?')) return; - try { - await deleteDefaultReply(cookieID); - await loadDefaultReplies(); - alert('删除成功'); - } catch (/* error 表示错误。 */ error) { - alert('删除失败:' + (error as Error).message); - } - }; - - // handleClearDefaultReplyRecords 处理当前用户操作(ClearDefault回复Records)。 - const handleClearDefaultReplyRecords = async (cookieID: string) => { - if (!confirm('确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。')) return; - try { - await clearDefaultReplyRecords(cookieID); - alert('清空成功'); - } catch (/* error 表示错误。 */ error) { - alert('清空失败:' + (error as Error).message); - } - }; - // primaryActionLabel 主操作按钮文案。 const primaryActionLabel = activeTab === 'automation' ? '新建自动化' diff --git a/frontend/routing.test.ts b/frontend/routing.test.ts index 577ef4c..13c8240 100644 --- a/frontend/routing.test.ts +++ b/frontend/routing.test.ts @@ -144,25 +144,26 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('item delivery shortcut opens existing automation rule modal', () => { - const rules = readFrontendFile('components/Rules.tsx'); /* rules 表示规则集合。 */ - const existingRuleBranch = rules.match(/if \(rule\) \{([\s\S]*?)\} else \{/); /* existingRuleBranch 表示existing当前规则Branch。 */ + const actions = readFrontendFile('app/features/rules/ruleActions.ts'); /* actions 表示规则动作协调器源码。 */ + const existingRuleBranch = actions.match(/if \(rule\) \{([\s\S]*?)\} else \{/); /* existingRuleBranch 表示existing当前规则Branch。 */ expect(existingRuleBranch?.[1]).toContain('openAutomationRule(rule)'); } /* 回调函数负责当前业务流程。 */); test('item delivery shortcut is not marked handled before async open completes', () => { - const rules = readFrontendFile('components/Rules.tsx'); /* rules 表示规则集合。 */ + const actions = readFrontendFile('app/features/rules/ruleActions.ts'); /* actions 表示规则动作协调器源码。 */ - expect(rules).not.toContain('handledDeliveryTarget.current = initialDeliveryTarget.requestId'); - expect(rules).toContain('onDeliveryTargetHandled?.();'); + expect(actions).not.toContain('handledDeliveryTarget.current = initialDeliveryTarget.requestId'); + expect(actions).toContain('onDeliveryTargetHandled?.();'); } /* 回调函数负责当前业务流程。 */); test('automation editor keeps multiple delivery contents for normal products', () => { const rules = readFrontendFile('components/Rules.tsx'); /* rules 表示规则集合。 */ + const actions = readFrontendFile('app/features/rules/ruleActions.ts'); /* actions 表示规则动作协调器源码。 */ expect(rules).toContain('添加发货内容'); expect(rules).toContain('{displayVariants.map((variant, index) => ('); - expect(rules).toContain(': variants.map(variant => ({'); + expect(actions).toContain('variants.map('); expect(rules).not.toContain(': (isMultiSpecRule ? variants : [variants[0]]).map'); } /* 回调函数负责当前业务流程。 */); diff --git a/internal/webui/static/assets/AccountList-Bqs514En.js b/internal/webui/static/assets/AccountList-HAZWMDQe.js similarity index 99% rename from internal/webui/static/assets/AccountList-Bqs514En.js rename to internal/webui/static/assets/AccountList-HAZWMDQe.js index fffa671..a80c2fb 100644 --- a/internal/webui/static/assets/AccountList-Bqs514En.js +++ b/internal/webui/static/assets/AccountList-HAZWMDQe.js @@ -1,3 +1,3 @@ -import{r as l,j as e,b as ne,c as Ee}from"./react-vendor-C_od1ZSF.js";import{f as Ne,u as ve,r as Qe,h as $e,i as Ue,j as Be,k as Me,l as Oe,m as ze,n as Ge,o as We,p as Ve,s as Ke,q as He,t as Xe,v as Je,w as Ye,x as Ze,y as Fe,z as es,A as ss,B as ts,C as as}from"./index-CFJ5pUjO.js";import{X as oe,n as rs,f as K,o as ls,p as Se,q as Re,r as qe,s as se,t as Ae,K as ns,u as os,v as is,a as ds,w as ie,b as cs,i as Pe,x as xs,k as je,Q as we,R as us,y as ms,z as bs,F as ye,H as hs}from"./icons-vendor-ThcsWkZG.js";const _e=t=>({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}),J=(t,s,r)=>t===s&&!r.aborted,fe=(t,s)=>t instanceof Error?t.message:s,pe=t=>t instanceof Error&&t.message==="请求已取消",ke=(t,s)=>!t&&s==="",gs=({account:t,onSaved:s})=>{const[r,a]=l.useState(()=>_e(t)),[u,x]=l.useState(!0),[o,i]=l.useState(!1),[b,m]=l.useState(""),[p,h]=l.useState(""),[d,q]=l.useState(null),[k,g]=l.useState(null),f=l.useRef(0),L=l.useRef(null);l.useEffect(()=>{var v;const S=++f.current;(v=L.current)==null||v.abort();const w=new AbortController;return L.current=w,a(_e(t)),q(null),h(""),i(!1),m(""),g(null),x(!0),Ne(t.id,{signal:w.signal}).then(R=>{J(f.current,S,w.signal)&&a(R)}).catch(R=>{J(f.current,S,w.signal)&&!pe(R)&&h(fe(R,"加载任务设置失败"))}).finally(()=>{J(f.current,S,w.signal)&&x(!1)}),(()=>w.abort())},[t.id]),l.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=l.useCallback(async()=>{var v;if(!ke(o,b))return;const S=++f.current;(v=L.current)==null||v.abort();const w=new AbortController;L.current=w,i(!0),h(""),g(null);try{const R=await ve(t.id,r,{signal:w.signal});if(!J(f.current,S,w.signal))return;a(R),s(R)}catch(R){J(f.current,S,w.signal)&&!pe(R)&&(h(fe(R,"保存失败")),g(()=>U))}finally{J(f.current,S,w.signal)&&i(!1)}},[t.id,r,s,b,o]),B=l.useCallback(async S=>{var R;if(!ke(o,b)||!t.enabled)return;const w=++f.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),q(null),g(null);try{await ve(t.id,r,{signal:v.signal});const y=await Qe(t.id,S,{signal:v.signal}),A=await Ne(t.id,{signal:v.signal});if(!J(f.current,w,v.signal))return;q(y.summary),a(A),s(A)}catch(y){J(f.current,w,v.signal)&&!pe(y)&&(h(fe(y,"任务执行失败")),g(()=>(()=>B(S))))}finally{J(f.current,w,v.signal)&&m("")}},[t.enabled,t.id,r,s,b,o]),T=l.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:u,saving:o,running:b,summary:d,error:p,retryAvailable:k!==null,setForm:a,save:U,run:B,retry:T}},Ce=({checked:t,onChange:s,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":t,onClick:s,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":""}`})}),fs=({account:t,onClose:s,onSaved:r})=>{const{form:a,loading:u,saving:x,running:o,error:i,summary:b,retryAvailable:m,setForm:p,save:h,run:d,retry:q}=gs({account:t,onSaved:r});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:s,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(oe,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[u&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",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(rs,{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(Ce,{checked:a.auto_rate_enabled,onChange:(()=>p(k=>({...k,auto_rate_enabled:!k.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:a.rate_content,maxLength:500,onChange:(k=>p(g=>({...g,rate_content:k.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:["最近扫描:",a.last_rate_scan_at?new Date(a.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:o!==""||!t.enabled,onClick:(()=>void d("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:[o==="auto_rate"?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(ls,{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(Se,{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(Ce,{checked:a.auto_polish_enabled,onChange:(()=>p(k=>({...k,auto_polish_enabled:!k.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:a.polish_time,onChange:(k=>p(g=>({...g,polish_time:k.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:o!==""||!t.enabled,onClick:(()=>void d("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:[o==="auto_polish"?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(Re,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",a.last_polish_at?new Date(a.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||""]}),i&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:[e.jsx("span",{children:i}),m&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void q()),children:"重试"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:s,disabled:x||o!=="",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 h()),disabled:x||o!==""||a.auto_rate_enabled&&!a.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:[x?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(qe,{className:"h-4 w-4"}),"保存"]})]})})]})})},Le=({src:t,alt:s,className:r=""})=>e.jsx("img",{src:t,alt:s,className:`block aspect-square h-auto w-full object-contain ${r}`.trim()}),ps=({account:t,editForm:s,setEditForm:r,saving:a,onClose:u,onSave:x,onRestartPause:o,longLogin:i,onToggleLongLogin:b,passwordLoginView:m,onPasswordLogin:p,onCancelPasswordLogin:h,notifChannels:d,selectedChannelIds:q,bindingsLoaded:k,bindingsLoading:g,bindingsLoadError:f,onRetryBindings:L,onToggleChannel:U,onSettingsDirty:B})=>{const T=(C,W)=>{r(F=>({...F,[C]:W}))},S=()=>void u(),w=()=>void x(),v=C=>T("remark",C.target.value),R=C=>T("cookie",C.target.value),y=()=>T("auto_confirm",!s.auto_confirm),A=C=>T("pause_duration",parseInt(C.target.value,10)||0),E=()=>void o(),X=()=>void b(),H=C=>T("username",C.target.value),G=C=>r(W=>({...W,login_password:C.target.value,clear_password:!1})),V=()=>T("showLoginPassword",!s.showLoginPassword),O=C=>r(W=>({...W,clear_password:C.target.checked,login_password:C.target.checked?"":W.login_password})),I=()=>T("show_browser",!s.show_browser),z=()=>void h(),Q=()=>void p(),$=()=>void L(),Z=C=>{k&&(U(C),B())},te=C=>{const W=q.includes(Number(C.id)),F=()=>Z(Number(C.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:F,disabled:!k,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${W?"bg-brand border-brand":"bg-white border-gray-300"}`,children:W&&e.jsx(se,{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:C.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[C.type,C.enabled?"":" · 已停用"]})]})]},C.id)};return ne.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:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:S,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(oe,{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:t.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:s.remark,onChange:v,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:s.cookie,onChange:R,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长度: ",s.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(se,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:y,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.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 ${s.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(Ae,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:s.pause_duration,onChange:A,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:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),s.pause_duration>0&&!t.paused&&s.pause_duration===(t.pause_duration||0)&&e.jsx("button",{type:"button",disabled:a,onClick:E,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(ns,{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:"状态直接读取并修改闲鱼官方长登录设置"}),i.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:i.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:i.loading||i.saving||!i.canOpen,onClick:X,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${i.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 ${i.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:s.username,onChange:H,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:s.showLoginPassword?"text":"password",value:s.login_password,onChange:G,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:V,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:s.showLoginPassword?e.jsx(os,{className:"w-5 h-5"}):e.jsx(is,{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:s.clear_password,onChange:O,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:I,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.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 ${s.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 和保存的登录信息。"})]}),m.status==="processing"||m.status==="verification_required"?e.jsx("button",{type:"button",onClick:z,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:Q,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),m.message&&e.jsx("div",{className:`text-sm font-medium ${m.status==="failed"?"text-red-700":m.status==="success"?"text-green-700":"text-blue-800"}`,children:m.message}),m.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 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),m.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(Le,{src:m.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(d.length>0||g||f)&&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(ds,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),g&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(K,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),f&&!g&&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:f}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:$,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:d.map(te)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:S,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:a,children:"取消"}),e.jsxs("button",{onClick:w,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:a,children:[a?e.jsx(K,{className:"w-4 h-4 animate-spin"}):e.jsx(se,{className:"w-4 h-4"}),a?"保存中...":"保存"]})]})})]})}),document.body)},js=({account:t,settings:s,saving:r,onChange:a,onClose:u,onSave:x})=>{const o=d=>a({...s,...d}),i=()=>o({ai_enabled:!s.ai_enabled}),b=d=>o({max_discount_percent:parseInt(d.target.value,10)||0}),m=d=>o({max_discount_amount:parseInt(d.target.value,10)||0}),p=d=>o({max_bargain_rounds:parseInt(d.target.value,10)||1}),h=d=>o({custom_prompts:d.target.value});return ne.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(ie,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:u,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(oe,{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(ie,{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:i,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.ai_enabled?"bg-brand":"bg-gray-300"}`,"aria-label":"切换 AI 自动回复",children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.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:s.max_discount_percent,onChange:b,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:s.max_discount_amount,onChange:m,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:s.max_bargain_rounds,onChange:p,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:s.custom_prompts,onChange:h,placeholder:`输入自定义的AI回复规则或风格指引... +import{r as l,j as e,b as ne,c as Ee}from"./react-vendor-C_od1ZSF.js";import{f as Ne,u as ve,r as Qe,h as $e,i as Ue,j as Be,k as Me,l as Oe,m as ze,n as Ge,o as We,p as Ve,s as Ke,q as He,t as Xe,v as Je,w as Ye,x as Ze,y as Fe,z as es,A as ss,B as ts,C as as}from"./index-CsLZwESi.js";import{X as oe,n as rs,f as K,o as ls,p as Se,q as Re,r as qe,s as se,t as Ae,K as ns,u as os,v as is,a as ds,w as ie,b as cs,i as Pe,x as xs,k as je,Q as we,R as us,y as ms,z as bs,F as ye,H as hs}from"./icons-vendor-ThcsWkZG.js";const _e=t=>({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}),J=(t,s,r)=>t===s&&!r.aborted,fe=(t,s)=>t instanceof Error?t.message:s,pe=t=>t instanceof Error&&t.message==="请求已取消",ke=(t,s)=>!t&&s==="",gs=({account:t,onSaved:s})=>{const[r,a]=l.useState(()=>_e(t)),[u,x]=l.useState(!0),[o,i]=l.useState(!1),[b,m]=l.useState(""),[p,h]=l.useState(""),[d,q]=l.useState(null),[k,g]=l.useState(null),f=l.useRef(0),L=l.useRef(null);l.useEffect(()=>{var v;const S=++f.current;(v=L.current)==null||v.abort();const w=new AbortController;return L.current=w,a(_e(t)),q(null),h(""),i(!1),m(""),g(null),x(!0),Ne(t.id,{signal:w.signal}).then(R=>{J(f.current,S,w.signal)&&a(R)}).catch(R=>{J(f.current,S,w.signal)&&!pe(R)&&h(fe(R,"加载任务设置失败"))}).finally(()=>{J(f.current,S,w.signal)&&x(!1)}),(()=>w.abort())},[t.id]),l.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=l.useCallback(async()=>{var v;if(!ke(o,b))return;const S=++f.current;(v=L.current)==null||v.abort();const w=new AbortController;L.current=w,i(!0),h(""),g(null);try{const R=await ve(t.id,r,{signal:w.signal});if(!J(f.current,S,w.signal))return;a(R),s(R)}catch(R){J(f.current,S,w.signal)&&!pe(R)&&(h(fe(R,"保存失败")),g(()=>U))}finally{J(f.current,S,w.signal)&&i(!1)}},[t.id,r,s,b,o]),B=l.useCallback(async S=>{var R;if(!ke(o,b)||!t.enabled)return;const w=++f.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),q(null),g(null);try{await ve(t.id,r,{signal:v.signal});const y=await Qe(t.id,S,{signal:v.signal}),A=await Ne(t.id,{signal:v.signal});if(!J(f.current,w,v.signal))return;q(y.summary),a(A),s(A)}catch(y){J(f.current,w,v.signal)&&!pe(y)&&(h(fe(y,"任务执行失败")),g(()=>(()=>B(S))))}finally{J(f.current,w,v.signal)&&m("")}},[t.enabled,t.id,r,s,b,o]),T=l.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:u,saving:o,running:b,summary:d,error:p,retryAvailable:k!==null,setForm:a,save:U,run:B,retry:T}},Ce=({checked:t,onChange:s,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":t,onClick:s,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":""}`})}),fs=({account:t,onClose:s,onSaved:r})=>{const{form:a,loading:u,saving:x,running:o,error:i,summary:b,retryAvailable:m,setForm:p,save:h,run:d,retry:q}=gs({account:t,onSaved:r});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:s,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(oe,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[u&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",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(rs,{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(Ce,{checked:a.auto_rate_enabled,onChange:(()=>p(k=>({...k,auto_rate_enabled:!k.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:a.rate_content,maxLength:500,onChange:(k=>p(g=>({...g,rate_content:k.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:["最近扫描:",a.last_rate_scan_at?new Date(a.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:o!==""||!t.enabled,onClick:(()=>void d("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:[o==="auto_rate"?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(ls,{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(Se,{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(Ce,{checked:a.auto_polish_enabled,onChange:(()=>p(k=>({...k,auto_polish_enabled:!k.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:a.polish_time,onChange:(k=>p(g=>({...g,polish_time:k.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:o!==""||!t.enabled,onClick:(()=>void d("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:[o==="auto_polish"?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(Re,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",a.last_polish_at?new Date(a.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||""]}),i&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:[e.jsx("span",{children:i}),m&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void q()),children:"重试"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:s,disabled:x||o!=="",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 h()),disabled:x||o!==""||a.auto_rate_enabled&&!a.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:[x?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(qe,{className:"h-4 w-4"}),"保存"]})]})})]})})},Le=({src:t,alt:s,className:r=""})=>e.jsx("img",{src:t,alt:s,className:`block aspect-square h-auto w-full object-contain ${r}`.trim()}),ps=({account:t,editForm:s,setEditForm:r,saving:a,onClose:u,onSave:x,onRestartPause:o,longLogin:i,onToggleLongLogin:b,passwordLoginView:m,onPasswordLogin:p,onCancelPasswordLogin:h,notifChannels:d,selectedChannelIds:q,bindingsLoaded:k,bindingsLoading:g,bindingsLoadError:f,onRetryBindings:L,onToggleChannel:U,onSettingsDirty:B})=>{const T=(C,W)=>{r(F=>({...F,[C]:W}))},S=()=>void u(),w=()=>void x(),v=C=>T("remark",C.target.value),R=C=>T("cookie",C.target.value),y=()=>T("auto_confirm",!s.auto_confirm),A=C=>T("pause_duration",parseInt(C.target.value,10)||0),E=()=>void o(),X=()=>void b(),H=C=>T("username",C.target.value),G=C=>r(W=>({...W,login_password:C.target.value,clear_password:!1})),V=()=>T("showLoginPassword",!s.showLoginPassword),O=C=>r(W=>({...W,clear_password:C.target.checked,login_password:C.target.checked?"":W.login_password})),I=()=>T("show_browser",!s.show_browser),z=()=>void h(),Q=()=>void p(),$=()=>void L(),Z=C=>{k&&(U(C),B())},te=C=>{const W=q.includes(Number(C.id)),F=()=>Z(Number(C.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:F,disabled:!k,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${W?"bg-brand border-brand":"bg-white border-gray-300"}`,children:W&&e.jsx(se,{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:C.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[C.type,C.enabled?"":" · 已停用"]})]})]},C.id)};return ne.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:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:S,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(oe,{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:t.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:s.remark,onChange:v,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:s.cookie,onChange:R,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长度: ",s.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(se,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:y,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.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 ${s.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(Ae,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:s.pause_duration,onChange:A,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:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),s.pause_duration>0&&!t.paused&&s.pause_duration===(t.pause_duration||0)&&e.jsx("button",{type:"button",disabled:a,onClick:E,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(ns,{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:"状态直接读取并修改闲鱼官方长登录设置"}),i.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:i.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:i.loading||i.saving||!i.canOpen,onClick:X,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${i.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 ${i.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:s.username,onChange:H,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:s.showLoginPassword?"text":"password",value:s.login_password,onChange:G,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:V,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:s.showLoginPassword?e.jsx(os,{className:"w-5 h-5"}):e.jsx(is,{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:s.clear_password,onChange:O,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:I,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.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 ${s.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 和保存的登录信息。"})]}),m.status==="processing"||m.status==="verification_required"?e.jsx("button",{type:"button",onClick:z,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:Q,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),m.message&&e.jsx("div",{className:`text-sm font-medium ${m.status==="failed"?"text-red-700":m.status==="success"?"text-green-700":"text-blue-800"}`,children:m.message}),m.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 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),m.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(Le,{src:m.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(d.length>0||g||f)&&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(ds,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),g&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(K,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),f&&!g&&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:f}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:$,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:d.map(te)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:S,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:a,children:"取消"}),e.jsxs("button",{onClick:w,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:a,children:[a?e.jsx(K,{className:"w-4 h-4 animate-spin"}):e.jsx(se,{className:"w-4 h-4"}),a?"保存中...":"保存"]})]})})]})}),document.body)},js=({account:t,settings:s,saving:r,onChange:a,onClose:u,onSave:x})=>{const o=d=>a({...s,...d}),i=()=>o({ai_enabled:!s.ai_enabled}),b=d=>o({max_discount_percent:parseInt(d.target.value,10)||0}),m=d=>o({max_discount_amount:parseInt(d.target.value,10)||0}),p=d=>o({max_bargain_rounds:parseInt(d.target.value,10)||1}),h=d=>o({custom_prompts:d.target.value});return ne.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(ie,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:u,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(oe,{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(ie,{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:i,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.ai_enabled?"bg-brand":"bg-gray-300"}`,"aria-label":"切换 AI 自动回复",children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.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:s.max_discount_percent,onChange:b,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:s.max_discount_amount,onChange:m,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:s.max_bargain_rounds,onChange:p,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:s.custom_prompts,onChange:h,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(cs,{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:u,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void x()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(K,{className:"w-4 h-4 animate-spin"}):e.jsx(qe,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},ws=(t,s)=>{if(!t||!s)return!1;const r=Date.parse(t),a=Date.parse(s);return Number.isFinite(r)&&Number.isFinite(a)&&at.map(r=>{const a=s[r.id];return!a||ws(r.runtime_updated_at,a.updated_at)?r:{...r,runtime_state:a.state,runtime_message:a.message||"",runtime_connected:a.connected,runtime_updated_at:a.updated_at}}),Ns=t=>{if(!t.enabled||t.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(t.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"}}},vs=Ee.memo(function({account:s,refreshing:r,deleting:a,onRefreshProfile:u,onReauthorize:x,onEdit:o,onAI:i,onTasks:b,onToggle:m,onDelete:p}){const h=Ns(s),d=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(Pe,{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 ${h.dot}`,children:s.runtime_state==="online"&&e.jsx(se,{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 ${h.badge}`,children:h.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(ie,{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(xs,{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(Se,{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(se,{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(je,{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||"暂无备注"}),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 ${d?"text-red-700":"text-amber-700"}`,children:[e.jsx(je,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:s.runtime_message}),d&&e.jsxs("button",{type:"button",onClick:(()=>x(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(we,{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(Ae,{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:(()=>u(s)),disabled:r,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(us,{className:`w-5 h-5 ${r?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>x(s)),className:`p-3 rounded-xl transition-colors ${d?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(we,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>o(s)),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(ms,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>i(s)),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(ie,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>b(s)),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(Re,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>m(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(bs,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>p(s)),disabled:a,className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:a?"删除中…":`删除账号 ${s.nickname||s.remark||s.id}`,children:a?e.jsx(K,{className:"w-5 h-5 animate-spin"}):e.jsx(ye,{className:"w-5 h-5"})})]})]})]})]})})}),_s=({account:t,deleting:s,error:r,onClose:a,onConfirm:u})=>ne.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(ye,{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:a,disabled:s,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(oe,{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:t.nickname||t.remark||"未命名账号"}),t.remark&&t.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",t.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",t.id]})]}),s&&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(K,{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:"正在清理关联数据,请保持页面打开…"})]})]}),r&&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(je,{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:r})]})]})]}),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:a,disabled:s,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 u()),disabled:s,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:s?e.jsxs(e.Fragment,{children:[e.jsx(K,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(ye,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),ks=({faceQrUrl:t,verificationScreenshot:s})=>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(hs,{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"}):s?e.jsx("img",{src:s,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(K,{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:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),Cs=({target:t,status:s,codeUrl:r,errorMessage:a,faceQrUrl:u,verificationScreenshot:x,onClose:o})=>ne.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:o,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","aria-label":"关闭二维码登录",children:e.jsx(oe,{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:t?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:t?`请用闲鱼APP扫码,为「${t.nickname||t.remark||t.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 ${s==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[s==="loading"&&e.jsx(K,{className:"w-10 h-10 text-brand animate-spin"}),s==="waiting"&&e.jsx(Le,{src:r,alt:"闲鱼登录二维码",className:"p-2"}),s==="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(se,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),s==="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:a||"请关闭窗口后重新发起扫码登录。"})]}),s==="verification"&&e.jsx(ks,{faceQrUrl:u,verificationScreenshot:x})]}),s!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),Ss=(t,s)=>t.map(r=>{var a,u,x,o,i;return{...r,ai_enabled:((a=s[r.id])==null?void 0:a.ai_enabled)??!1,max_discount_percent:((u=s[r.id])==null?void 0:u.max_discount_percent)??10,max_discount_amount:((x=s[r.id])==null?void 0:x.max_discount_amount)??100,max_bargain_rounds:((o=s[r.id])==null?void 0:o.max_bargain_rounds)??3,custom_prompts:((i=s[r.id])==null?void 0:i.custom_prompts)??""}}),Rs=()=>{const[t,s]=l.useState([]),[r,a]=l.useState(!0),u=l.useRef(0),x=l.useRef(null),o=l.useCallback(async()=>{var m;const i=++u.current;(m=x.current)==null||m.abort();const b=new AbortController;x.current=b,a(!0);try{const p={signal:b.signal},[h,d]=await Promise.allSettled([$e(p),Ue(p)]);if(i!==u.current)return;if(h.status==="rejected")throw h.reason;const q=d.status==="fulfilled"?d.value:{};d.status==="rejected"&&console.error("加载 AI 设置失败:",d.reason),s(Ss(h.value,q))}catch(p){i===u.current&&!b.signal.aborted&&console.error("加载账号失败:",p)}finally{i===u.current&&a(!1)}},[]);return l.useEffect(()=>{let i=!1,b=null;const m=new AbortController,p=async()=>{try{const d=await Be({signal:m.signal,timeoutMs:1e4});i||s(q=>ys(q,d))}catch(d){i||console.error("加载账号运行状态失败:",d)}finally{i||(b=window.setTimeout(()=>void p(),2e3))}};return o().finally(()=>{i||p()}),()=>{var d;i=!0,m.abort(),u.current+=1,(d=x.current)==null||d.abort(),b!==null&&window.clearTimeout(b)}},[o]),{accounts:t,setAccounts:s,loading:r,loadAccounts:o}},qs=new Set(["expired","cancelled","error","not_found"]),As=()=>{let t=0;return{next:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:(s=>s===t)}},Ps=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let s=null,r=null,a=-1,u=0;const x=()=>{u+=1,r==null||r.abort(),r=null,s!==null&&(t.clearInterval(s),s=null)};return{start:(i,b,m,p=2e3)=>{x();const h=u;r=new AbortController;const d=r.signal;s=t.setInterval(()=>{a===h||h!==u||(a=h,(async()=>{var q,k;try{const g=await b(i,d);if(g.status==="success"){x(),await m.onSuccess(g);return}if(g.status==="scanned"){(q=m.onScanned)==null||q.call(m,g);return}if(g.status==="verification_required"){(k=m.onVerificationRequired)==null||k.call(m,g);return}g.status&&qs.has(g.status)&&(x(),m.onTerminalError(g))}catch(g){if(d.aborted||h!==u)return;x(),m.onPollError(g)}finally{a===h&&(a=-1)}})())},p)},stop:x,isActive:(()=>s!==null)}},Ls=({onLoginSuccess:t})=>{const[s,r]=l.useState(!1),[a,u]=l.useState(""),[x,o]=l.useState("pending"),[i,b]=l.useState(""),[m,p]=l.useState(""),[h,d]=l.useState(""),[q,k]=l.useState(null),g=l.useRef(null),f=l.useRef(null),L=l.useRef(null),U=l.useRef(null);g.current===null&&(g.current=Ps()),f.current===null&&(f.current=As());const B=()=>{U.current!==null&&(window.clearTimeout(U.current),U.current=null)},T=()=>{var y;(y=g.current)==null||y.stop()},S=()=>{var y,A;(y=L.current)==null||y.abort(),(A=f.current)==null||A.cancel(),T(),B(),r(!1)},w=()=>{B(),U.current=window.setTimeout(()=>{U.current=null,r(!1),t()},1e3)};l.useEffect(()=>()=>{var A,E;T(),(A=f.current)==null||A.cancel(),(E=L.current)==null||E.abort(),B()},[]);const v=async(y,A)=>{const E=await ze(y,A==null?void 0:A.id);if(!E.success||!E.account_id)throw new Error(E.message||"保存扫码授权失败");return E.account_id};return{showQRModal:s,qrCodeUrl:a,qrStatus:x,qrErrorMessage:i,verificationScreenshot:m,faceQrUrl:h,qrReauthTarget:q,startQRLogin:async y=>{var H,G,V,O;T(),(H=L.current)==null||H.abort();const A=new AbortController;L.current=A;const E=f.current.next();B();const X=y||null;k(X),r(!0),o("loading"),b(""),u(""),p(""),d("");try{const I=await Me({signal:A.signal});if(!((G=f.current)!=null&&G.isCurrent(E)))return;if(!I.success||!I.qr_code_url||!I.session_id)throw new Error(I.message||"闲鱼未返回可用的登录二维码");const z=I.session_id;u(I.qr_code_url),o("waiting"),(V=g.current)==null||V.start(z,Oe,{onSuccess:(async()=>{try{await v(z,X)}catch(Q){console.error("保存扫码授权失败",Q),o("error");return}o("success"),w()}),onScanned:(()=>{o("waiting")}),onTerminalError:(()=>{o("error")}),onPollError:(Q=>{console.error("轮询扫码状态失败",Q),o("error")}),onVerificationRequired:(Q=>{o("verification"),Q.face_qr_url&&d(Q.face_qr_url),Q.verification_screenshot&&p(Q.verification_screenshot)})})}catch(I){if(!((O=f.current)!=null&&O.isCurrent(E))||A.signal.aborted)return;b(I instanceof Error?I.message:"二维码获取失败,请稍后重试"),o("error")}finally{L.current===A&&(L.current=null)}},closeQRModal:S}},Is=(t,s)=>t!==(s.pause_duration||0),Ts=(t,s)=>{const r=s.username!==(t.username||""),a=s.show_browser!==(t.show_browser||!1),u=s.login_password!=="",x=s.clear_password===!0;if(!r&&!a&&!u&&!x)return null;const o={username:s.username,show_browser:s.show_browser};return x?o.clear_password=!0:u&&(o.login_password=s.login_password),o},Y=(t,s,r,a)=>t===s&&r===a,Ds=t=>t.status==="success"?{sessionId:"",status:"success",message:t.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}:t.status==="processing"||t.status==="verification_required"?{sessionId:"",status:t.status,message:t.message||(t.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:t.qr_code_url||""}:{sessionId:"",status:"failed",message:t.error||t.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""},Es=(t,s)=>t&&s,Qs=({editingAccount:t,setEditingAccount:s,setActiveModal:r,editForm:a,setEditForm:u,loadAccounts:x})=>{const[o,i]=l.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[b,m]=l.useState([]),[p,h]=l.useState([]),[d,q]=l.useState(!1),[k,g]=l.useState(!1),[f,L]=l.useState(!1),[U,B]=l.useState(""),[T,S]=l.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[w,v]=l.useState(!1),[R,y]=l.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),A=l.useRef(0),E=l.useRef(null),X=l.useRef(0),H=l.useRef(null),G=l.useRef(0),V=l.useRef(null),O=l.useRef(0),I=l.useRef(""),z=l.useRef(null),Q=l.useRef(null),$=l.useCallback(()=>{Q.current!==null&&(window.clearTimeout(Q.current),Q.current=null)},[]),Z=l.useCallback(async n=>{var M;const c=++A.current;(M=E.current)==null||M.abort();const _=new AbortController;E.current=_,g(!0),q(!1),L(!1),B("");const[D,N]=await Promise.allSettled([Ge({signal:_.signal}),We(n,{signal:_.signal})]);Y(c,A.current,n,n)&&(D.status==="fulfilled"?m(D.value.data||[]):(m([]),B("通知渠道列表加载失败,请重试")),N.status==="fulfilled"?(h(N.value||[]),q(!0)):(h([]),B("通知绑定加载失败;本次保存不会修改现有绑定")),g(!1))},[]),te=l.useCallback(n=>{h(c=>c.includes(n)?c.filter(_=>_!==n):[...c,n]),L(!0)},[]),C=l.useCallback(async n=>{var N,M;const c=++X.current;(N=H.current)==null||N.abort();const _=new AbortController;H.current=_,O.current+=1,I.current=n.id,(M=z.current)==null||M.abort(),$(),y({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),s(n),u({remark:n.remark||"",cookie:n.value||"",auto_confirm:n.auto_confirm||!1,pause_duration:n.pause_duration||0,username:n.username||"",login_password:n.login_password||"",show_browser:n.show_browser||!1,showLoginPassword:!1,clear_password:!1}),r("edit"),i({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,D]=await Promise.allSettled([Z(n.id),Ve(n.id,{signal:_.signal})]);c===X.current&&(D.status==="fulfilled"?i({loading:!1,saving:!1,canOpen:D.value.can_open_long_login,enabled:D.value.enabled,error:""}):i({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"}))},[$,Z,r,u,s]),W=l.useCallback(async()=>{if(!t||o.loading||o.saving||!o.canOpen)return;const n=!o.enabled;i(c=>({...c,saving:!0,error:""}));try{const c=await Ke(t.id,n);i({loading:!1,saving:!1,canOpen:c.can_open_long_login,enabled:c.enabled,error:""})}catch(c){i(_=>({..._,saving:!1,error:c instanceof Error?c.message:"保存登录信息设置失败"}))}},[t,o]),F=l.useCallback(async n=>{var D;const c=++G.current;(D=V.current)==null||D.abort();const _=new AbortController;V.current=_,s(n),r("ai-settings"),v(!0);try{const N=await He(n.id,{signal:_.signal});if(!Y(c,G.current,n.id,n.id))return;S({ai_enabled:N.ai_enabled??!1,max_discount_percent:N.max_discount_percent??10,max_discount_amount:N.max_discount_amount??100,max_bargain_rounds:N.max_bargain_rounds??3,custom_prompts:N.custom_prompts??""})}catch(N){Y(c,G.current,n.id,n.id)&&console.error("加载 AI 设置失败:",N)}finally{Y(c,G.current,n.id,n.id)&&v(!1)}},[r,s]),de=l.useCallback(async()=>{if(!(!t||w)){v(!0);try{await Xe(t.id,T),r(null),await x()}catch(n){console.error("更新 AI 设置失败:",n)}finally{v(!1)}}},[T,t,x,w,r]),ce=l.useCallback(async()=>{if(!(!t||w)){v(!0);try{const n={};a.remark!==(t.remark||"")&&(n.remark=a.remark),a.cookie&&a.cookie!==(t.value||"")&&(n.cookie=a.cookie),a.auto_confirm!==t.auto_confirm&&(n.auto_confirm=a.auto_confirm),Is(a.pause_duration,t)&&(n.pause_duration=a.pause_duration);const c=Ts(t,a);c&&Object.assign(n,c),Es(d,f)&&(n.channel_ids=p),Object.keys(n).length>0&&await Je(t.id,n),r(null),await x()}catch(n){console.error("更新账号失败:",n)}finally{v(!1)}}},[f,d,a,t,x,p,w,r]),xe=l.useCallback(async()=>{if(!(!t||a.pause_duration<=0||w)){v(!0);try{const n=await Ye(t.id,a.pause_duration);s(c=>c&&{...c,pause_duration:a.pause_duration,paused:(n==null?void 0:n.paused)===!0,paused_until:Number((n==null?void 0:n.paused_until)||0)}),await x()}catch(n){console.error("重新暂停失败:",n)}finally{v(!1)}}},[a.pause_duration,t,x,w,s]),ae=l.useCallback(async(n,c,_)=>{var N;(N=z.current)==null||N.abort();const D=new AbortController;z.current=D;try{const M=await Ze(n,D.signal);if(!Y(c,O.current,_,I.current))return;const le={...Ds(M),sessionId:n};if(M.status==="success"){$(),y(le),u(he=>({...he,login_password:"",showLoginPassword:!1})),await x();return}if(M.status==="processing"||M.status==="verification_required"){y(le),$(),Q.current=window.setTimeout(()=>void ae(n,c,_),1500);return}$(),y(le)}catch(M){if(!Y(c,O.current,_,I.current))return;$(),y({sessionId:n,status:"failed",message:M instanceof Error?M.message:"查询密码登录状态失败",qrCodeUrl:""})}},[$,x,u]),ue=l.useCallback(async()=>{var D;if(!t)return;const n=a.username.trim();if(!n||!a.login_password)return;$(),(D=z.current)==null||D.abort();const c=++O.current;I.current=t.id;const _=new AbortController;z.current=_,y({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const N=await Fe({account_id:t.id,account:n,password:a.login_password,show_browser:a.show_browser},{signal:_.signal});if(!Y(c,O.current,t.id,I.current))return;if(!N.success||!N.session_id)throw new Error(N.message||"无法启动密码登录");y({sessionId:N.session_id,status:"processing",message:N.message||"登录处理中",qrCodeUrl:""}),await ae(N.session_id,c,t.id)}catch(N){if(!Y(c,O.current,t.id,I.current))return;y({sessionId:"",status:"failed",message:N instanceof Error?N.message:"启动密码登录失败",qrCodeUrl:""})}},[$,a.login_password,a.show_browser,a.username,t,ae]),re=l.useCallback(async()=>{var c;const n=R.sessionId;O.current+=1,I.current="",(c=z.current)==null||c.abort(),$(),n&&await es(n).catch(()=>{}),y({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},[$,R.sessionId]),me=l.useCallback(async()=>{var n,c,_;(n=E.current)==null||n.abort(),X.current+=1,(c=H.current)==null||c.abort(),(_=V.current)==null||_.abort(),(R.status==="processing"||R.status==="verification_required")&&await re(),r(null)},[re,R.status,r]),be=l.useCallback(()=>{var n;G.current+=1,(n=V.current)==null||n.abort(),r(null)},[r]);return l.useEffect(()=>(()=>{var n,c,_,D;(n=E.current)==null||n.abort(),(c=H.current)==null||c.abort(),(_=V.current)==null||_.abort(),(D=z.current)==null||D.abort(),$()}),[$]),{longLogin:o,notifChannels:b,selectedChannelIds:p,bindingsLoaded:d,bindingsLoading:k,bindingsDirty:f,bindingsLoadError:U,aiSettings:T,saving:w,passwordLoginView:R,setAiSettings:S,setBindingsDirty:L,setEditForm:u,openEditModal:C,closeEditModal:me,openAIModal:F,closeAIModal:be,loadNotificationBindings:Z,toggleNotificationChannel:te,handleLongLoginToggle:W,handleSaveAISettings:de,handleSaveEdit:ce,handleRestartPause:xe,handlePasswordLogin:ue,handleCancelPasswordLogin:re}},Ms=()=>{const{accounts:t,setAccounts:s,loading:r,loadAccounts:a}=Rs(),[u,x]=l.useState(""),[o,i]=l.useState(""),[b,m]=l.useState(""),[p,h]=l.useState(null),[d,q]=l.useState(""),[k,g]=l.useState(null),[f,L]=l.useState(null),[U,B]=l.useState(null),[T,S]=l.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),w=Qs({editingAccount:f,setEditingAccount:L,setActiveModal:g,editForm:T,setEditForm:S,loadAccounts:a}),{longLogin:v,notifChannels:R,selectedChannelIds:y,bindingsLoaded:A,bindingsLoading:E,bindingsLoadError:X,aiSettings:H,saving:G,passwordLoginView:V,setAiSettings:O,setBindingsDirty:I,openEditModal:z,closeEditModal:Q,openAIModal:$,closeAIModal:Z,loadNotificationBindings:te,toggleNotificationChannel:C,handleLongLoginToggle:W,handleSaveAISettings:F,handleSaveEdit:de,handleRestartPause:ce,handlePasswordLogin:xe,handleCancelPasswordLogin:ae}=w,ue=Ls({onLoginSuccess:a}),{showQRModal:re,qrCodeUrl:me,qrStatus:be,qrErrorMessage:n,verificationScreenshot:c,faceQrUrl:_,qrReauthTarget:D,startQRLogin:N,closeQRModal:M}=ue,le=async(j,P)=>{await ss(j,!P),a()},he=j=>{b||(q(""),h(j))},Ie=()=>{b||(q(""),h(null))},Te=async()=>{const j=p;if(!(!j||b)){m(j.id),q("");try{await as(j.id),s(P=>P.filter(ee=>ee.id!==j.id)),h(null)}catch(P){console.error("删除账号失败:",P),q((P==null?void 0:P.message)||"删除账号失败,请稍后重试")}finally{m("")}}},De=async j=>{i(j.id);try{const P=await ts(j.id);P!=null&&P.profile_error&&alert("资料刷新失败:"+P.profile_error),await a()}catch(P){console.error("刷新账号资料失败:",P),alert((P==null?void 0:P.message)||"刷新账号资料失败,请先重新授权该账号")}finally{i("")}};if(r)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(K,{className:"w-8 h-8 text-brand animate-spin"})});const ge=t.filter(j=>{const P=u.trim().toLowerCase();return P?[j.id,j.nickname,j.remark,j.username,j.runtime_message].some(ee=>(ee||"").toLowerCase().includes(P)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:u,onChange:(j=>x(j.target.value)),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:(()=>N()),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(we,{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:["当前显示 ",ge.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[ge.map(j=>e.jsx(vs,{account:j,refreshing:o===j.id,deleting:b===j.id,onRefreshProfile:De,onReauthorize:N,onEdit:z,onAI:$,onTasks:B,onToggle:le,onDelete:he},j.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(Pe,{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&&ge.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。"})]})]}),U&&ne.createPortal(e.jsx(fs,{account:U,onClose:(()=>B(null)),onSaved:(j=>{s(P=>P.map(ee=>ee.id===U.id?{...ee,auto_rate_enabled:j.auto_rate_enabled,rate_content:j.rate_content,auto_polish_enabled:j.auto_polish_enabled,polish_time:j.polish_time,last_rate_scan_at:j.last_rate_scan_at,last_polish_date:j.last_polish_date,last_polish_at:j.last_polish_at}:ee))})}),document.body),p&&e.jsx(_s,{account:p,deleting:b===p.id,error:d,onClose:Ie,onConfirm:Te}),re&&e.jsx(Cs,{target:D,status:be,codeUrl:me,errorMessage:n,faceQrUrl:_,verificationScreenshot:c,onClose:M}),k==="edit"&&f&&e.jsx(ps,{account:f,editForm:T,setEditForm:S,saving:G,onClose:Q,onSave:de,onRestartPause:ce,longLogin:v,onToggleLongLogin:W,passwordLoginView:V,onPasswordLogin:xe,onCancelPasswordLogin:ae,notifChannels:R,selectedChannelIds:y,bindingsLoaded:A,bindingsLoading:E,bindingsLoadError:X,onRetryBindings:(()=>te(f.id)),onToggleChannel:C,onSettingsDirty:(()=>I(!0))}),k==="ai-settings"&&f&&e.jsx(js,{account:f,settings:H,saving:G,onChange:O,onClose:Z,onSave:F})]})};export{Ms as default}; diff --git a/internal/webui/static/assets/CardList-CRgXJn6O.js b/internal/webui/static/assets/CardList-DuMEp-gq.js similarity index 99% rename from internal/webui/static/assets/CardList-CRgXJn6O.js rename to internal/webui/static/assets/CardList-DuMEp-gq.js index ab42f7f..a08fe48 100644 --- a/internal/webui/static/assets/CardList-CRgXJn6O.js +++ b/internal/webui/static/assets/CardList-DuMEp-gq.js @@ -1,4 +1,4 @@ -import{b as z,j as e,r}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Y,J as $,Y as Q,f as U,N as V,C as H,_ as Z,$ as W,a0 as K,a1 as ee,I as te,a2 as ae,V as se,F as le,P as ne,r as re}from"./icons-vendor-ThcsWkZG.js";import{K as oe,L as ie,M as de,N as J,O as ce,P as xe}from"./index-CFJ5pUjO.js";const pe=({dataCards:c,downloadCardTemplate:d,...s})=>{var x;const u=a=>{var m;s.setBatchFile(((m=a.target.files)==null?void 0:m[0])||null)},p=a=>{s.setAppendContent(a.target.value)},_=a=>{s.setAppendTargetId(a.target.value)},j=()=>s.closeBatchModal(),f=()=>s.setBatchTab("create"),i=()=>s.setBatchTab("append"),A=()=>void s.handleRetryBatchCreate(),o=()=>void s.handleRetryBatchAppend(),y=s.batchResult&&"rows"in s.batchResult?s.batchResult:null,N=a=>e.jsxs("option",{value:String(a.id),children:[a.name,"(ID: ",a.id,")"]},a.id),b=()=>void s.handleBatchCreate(),l=()=>void s.handleBatchAppend();return s.showBatchModal?z.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:j,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{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:f,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${s.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Y,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:i,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${s.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx($,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),s.batchTab==="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:d,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(Q,{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($,{className:"w-4 h-4"}),s.batchFile?s.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=s.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!s.batchFile||s.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&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:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(a=>!a.success).map(a=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",a.row_no," 行「",a.name,"」:",a.error]},a.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:c.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:s.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:c.map(N)})]}),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:s.appendContent,onChange:p,placeholder:`VIP-001 +import{b as z,j as e,r}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Y,J as $,Y as Q,f as U,N as V,C as H,_ as Z,$ as W,a0 as K,a1 as ee,I as te,a2 as ae,V as se,F as le,P as ne,r as re}from"./icons-vendor-ThcsWkZG.js";import{K as oe,L as ie,M as de,N as J,O as ce,P as xe}from"./index-CsLZwESi.js";const pe=({dataCards:c,downloadCardTemplate:d,...s})=>{var x;const u=a=>{var m;s.setBatchFile(((m=a.target.files)==null?void 0:m[0])||null)},p=a=>{s.setAppendContent(a.target.value)},_=a=>{s.setAppendTargetId(a.target.value)},j=()=>s.closeBatchModal(),f=()=>s.setBatchTab("create"),i=()=>s.setBatchTab("append"),A=()=>void s.handleRetryBatchCreate(),o=()=>void s.handleRetryBatchAppend(),y=s.batchResult&&"rows"in s.batchResult?s.batchResult:null,N=a=>e.jsxs("option",{value:String(a.id),children:[a.name,"(ID: ",a.id,")"]},a.id),b=()=>void s.handleBatchCreate(),l=()=>void s.handleBatchAppend();return s.showBatchModal?z.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:j,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{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:f,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${s.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Y,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:i,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${s.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx($,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),s.batchTab==="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:d,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(Q,{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($,{className:"w-4 h-4"}),s.batchFile?s.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=s.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!s.batchFile||s.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&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:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(a=>!a.success).map(a=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",a.row_no," 行「",a.name,"」:",a.error]},a.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:c.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:s.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:c.map(N)})]}),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:s.appendContent,onChange:p,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.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",s.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),s.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.appendError}),e.jsx("button",{type:"button",onClick:o,disabled:s.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",s.appendResult.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:j,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),s.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!s.batchFile||s.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[s.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx($,{className:"w-4 h-4"}),s.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:l,disabled:!s.appendTargetId||s.appendPreview.length===0||s.batchBusy||c.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[s.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx(V,{className:"w-4 h-4"}),s.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},me=({type:c})=>{switch(c){case"text":return e.jsx(K,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(W,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(Z,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(H,{className:"w-5 h-5 text-gray-500"})}},he=(c,d,s)=>{const u=s.trim().toLocaleLowerCase();return c.filter(p=>(!d||p.type===d)&&(!u||p.name.toLocaleLowerCase().includes(u)))},X=c=>c.split(` `).map(d=>d.trim()).filter(Boolean),ue=(c,d,s)=>!!(c&&X(d).length>0&&!s),F=(c,d,s,u)=>c===d&&s===u,be=()=>{const[c,d]=r.useState([]),[s,u]=r.useState(!0),p=r.useRef(0),_=r.useRef(null),j=r.useCallback(async()=>{var A;const f=++p.current;(A=_.current)==null||A.abort();const i=new AbortController;_.current=i,u(!0);try{const o=await oe({signal:i.signal});if(f!==p.current)return;d(o)}catch(o){f===p.current&&!i.signal.aborted&&console.error("加载卡密库存失败:",o)}finally{f===p.current&&u(!1)}},[]);return r.useEffect(()=>(j(),()=>{var i;p.current+=1,(i=_.current)==null||i.abort()}),[j]),{cards:c,setCards:d,loading:s,loadCards:j}},ge=c=>{const d=c.dataCards,s=c.loadCards,[u,p]=r.useState(!1),[_,j]=r.useState("create"),[f,i]=r.useState(null),[A,o]=r.useState(null),[y,N]=r.useState(!1),[b,l]=r.useState(""),[x,a]=r.useState(""),[m,E]=r.useState(null),[M,R]=r.useState(""),w=r.useRef(0),T=r.useRef(null),P=r.useRef(""),L=r.useMemo(()=>X(x),[x]),n=r.useCallback(()=>{var h;j("create"),i(null),o(null),l((h=d[0])!=null&&h.id?String(d[0].id):""),a(""),E(null),R(""),p(!0)},[d]),t=r.useCallback(()=>{var h;w.current+=1,(h=T.current)==null||h.abort(),N(!1),p(!1)},[]),g=r.useCallback(async()=>{var v;if(!f||y)return;const h=++w.current;(v=T.current)==null||v.abort();const B=new AbortController;T.current=B,N(!0),o(null);try{const I=await ie(f,{signal:B.signal});if(!F(h,w.current,"",""))return;o(I),I.created>0&&await s()}catch(I){if(!F(h,w.current,"",""))return;o({error:(I==null?void 0:I.message)||"上传失败"})}finally{F(h,w.current,"","")&&N(!1)}},[y,f,s]),k=r.useCallback(async()=>{var I;if(!ue(b,x,y))return;const h=b,B=++w.current;P.current=h,(I=T.current)==null||I.abort();const v=new AbortController;T.current=v,N(!0),E(null),R("");try{const O=await de(h,x,{signal:v.signal});if(!F(B,w.current,h,b))return;E({added:O.added}),a(""),await s()}catch(O){if(!F(B,w.current,h,b))return;R((O==null?void 0:O.message)||"追加失败")}finally{F(B,w.current,h,b)&&N(!1)}},[x,b,y,s]),S=r.useCallback(async()=>{await g()},[g]),C=r.useCallback(async()=>{P.current&&b!==P.current||await k()},[b,k]);return{showBatchModal:u,setShowBatchModal:p,batchTab:_,setBatchTab:j,batchFile:f,setBatchFile:i,batchResult:A,batchBusy:y,appendTargetId:b,setAppendTargetId:l,appendContent:x,setAppendContent:a,appendResult:m,appendError:M,appendPreview:L,openBatchModal:n,closeBatchModal:t,handleBatchCreate:g,handleBatchAppend:k,handleRetryBatchCreate:S,handleRetryBatchAppend:C}},q=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),D=(c,d)=>c instanceof Error?c.message:d,ye=({cards:c,loadCards:d})=>{const[s,u]=r.useState(!1),[p,_]=r.useState(!1),[j,f]=r.useState(null),[i,A]=r.useState({}),[o,y]=r.useState(q),[N,b]=r.useState(""),[l,x]=r.useState(""),a=r.useMemo(()=>c.filter(n=>n.type==="data"),[c]),m=r.useMemo(()=>he(c,N,l),[c,l,N]),E=r.useCallback(n=>{var t,g,k,S,C;f(n),A({id:n.id,name:n.name||"",type:n.type||"text",api_url:((t=n.api_config)==null?void 0:t.url)||"",api_method:((g=n.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=n.api_config)==null?void 0:k.timeout)||10,api_headers:((S=n.api_config)==null?void 0:S.headers)||"",api_params:((C=n.api_config)==null?void 0:C.params)||"",text_content:n.text_content||"",data_content:n.data_content||"",image_url:n.image_url||"",delay_seconds:n.delay_seconds||0,description:n.description||"",enabled:n.enabled}),u(!0)},[]),M=r.useCallback(async()=>{var n,t,g,k,S,C,h,B;if(j){if(!((n=i.name)!=null&&n.trim())){alert("请输入卡密名称");return}if(!i.type){alert("请选择卡密类型");return}try{const v={name:i.name.trim(),type:i.type,description:(t=i.description)==null?void 0:t.trim(),delay_seconds:i.delay_seconds||0,enabled:i.enabled??!0};i.type==="api"?v.api_config={url:((g=i.api_url)==null?void 0:g.trim())||"",method:i.api_method||"GET",timeout:i.api_timeout||10,headers:((k=i.api_headers)==null?void 0:k.trim())||void 0,params:((S=i.api_params)==null?void 0:S.trim())||void 0}:i.type==="text"?v.text_content=((C=i.text_content)==null?void 0:C.trim())||"":i.type==="data"?v.data_content=((h=i.data_content)==null?void 0:h.trim())||"":i.type==="image"&&(v.image_url=((B=i.image_url)==null?void 0:B.trim())||""),await J(j.id,v),u(!1),await d()}catch(v){console.error("更新卡密失败:",v),alert(D(v,"更新失败,请重试"))}}},[i,d,j]),R=r.useCallback(async n=>{if(confirm("确认删除该卡密吗?"))try{await ce(n),await d()}catch(t){console.error("删除卡密失败:",t),alert(D(t,"删除失败,请重试"))}},[d]),w=r.useCallback(async()=>{if(!o.name.trim()){alert("请输入卡密名称");return}if(!o.content.trim()){alert(o.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const n={name:o.name.trim(),type:o.type,description:o.description.trim(),enabled:o.enabled,delay_seconds:o.delay_seconds};o.type==="text"&&(n.text_content=o.content.trim()),o.type==="data"&&(n.data_content=o.content.trim()),o.type==="image"&&(n.image_url=o.content.trim()),o.type==="api"&&(n.api_config={url:o.content.trim(),method:o.api_method,timeout:o.api_timeout,headers:o.api_headers.trim()||void 0,params:o.api_params.trim()||void 0}),await xe(n),_(!1),y(q()),await d()}catch(n){console.error("添加卡密失败:",n),alert(D(n,"添加失败,请重试"))}},[o,d]),T=r.useCallback(async n=>{try{await J(n.id,{...n,enabled:!n.enabled}),await d()}catch(t){console.error("切换状态失败:",t)}},[d]),P=r.useCallback(async n=>{try{await navigator.clipboard.writeText(String(n)),alert(`已复制卡密组ID:${n}`)}catch{prompt("复制卡密组ID",String(n))}},[]),L=r.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 diff --git a/internal/webui/static/assets/Chat-VbA-SOcX.js b/internal/webui/static/assets/Chat-B1v5dyJA.js similarity index 99% rename from internal/webui/static/assets/Chat-VbA-SOcX.js rename to internal/webui/static/assets/Chat-B1v5dyJA.js index 23b9193..f5d53b9 100644 --- a/internal/webui/static/assets/Chat-VbA-SOcX.js +++ b/internal/webui/static/assets/Chat-B1v5dyJA.js @@ -1 +1 @@ -import{j as e,c as W0,r as a}from"./react-vendor-C_od1ZSF.js";import{ap as R0,aq as M0,ar as q0,as as G0,at as X0,h as Y0,j as T0}from"./index-CFJ5pUjO.js";import{f as i0,ak as K0,al as $0,M as L0,I as ee,R as te,ad as E0,k as se,am as ie,s as ae,an as ne,ao as re,ah as le}from"./icons-vendor-ThcsWkZG.js";const U0=[["尊嘟假嘟","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"]],ce=m=>m,oe=new Map(U0.map(([m,g])=>[m,g])),pe=m=>m.split(/(\[[^\]]+\])/g).map((g,i)=>{const r=g.startsWith("[")?oe.get(g.slice(1,-1)):void 0;return r?e.jsx("img",{src:r,alt:g,title:g,className:"mx-0.5 inline-block h-7 w-7 align-middle"},i):e.jsx(W0.Fragment,{children:g},i)}),me=(m,g,i)=>{const r=g.trim().toLowerCase();return m.filter(x=>i&&x.unread_count<=0?!1:r?[x.buyer_name,x.buyer_id,x.item_title,x.last_message].some(N=>(N||"").toLowerCase().includes(r)):!0)},ge=(m,g)=>{const i=new Set(m.map(r=>r.message_key));return[...g.filter(r=>!i.has(r.message_key)),...m]},D0=(m,g)=>{const i=m.findIndex(r=>r.message_key===g.message_key);return i<0?[...m,g]:m.map((r,x)=>x===i?g:r)},j=(m,g,i)=>m===g&&!i.aborted,Q=m=>m instanceof Error&&m.message==="请求已取消",de=m=>{if(!m)return"";const g=new Date(m<1e10?m*1e3:m),i=new Date;return g.toDateString()===i.toDateString()?g.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):g.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},xe=m=>new Date(m<1e10?m*1e3:m).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),_e=()=>{const[m,g]=a.useState([]),[i,r]=a.useState(""),[x,N]=a.useState({}),[b,P]=a.useState(""),[E,v]=a.useState([]),[Z,h0]=a.useState(""),[M,u0]=a.useState(!1),[q,a0]=a.useState(""),[b0,T]=a.useState(!0),[L,D]=a.useState(!1),[z,V]=a.useState(!1),[W,n0]=a.useState(!1),[r0,l0]=a.useState(),[G,U]=a.useState({}),[X,Y]=a.useState({}),[K,c0]=a.useState(!1),[o0,f0]=a.useState(!1),[C,A]=a.useState(!1),[j0,w]=a.useState(""),[w0,H]=a.useState("connecting"),[F,$]=a.useState(null),[s,u]=a.useState(null),O=a.useRef(""),e0=a.useRef(""),p0=a.useRef(null),N0=a.useRef({accountID:"",chatID:""}),C0=a.useRef(!0),m0=a.useRef(!1),y0=a.useRef(null),I0=a.useRef(new Set),O0=a.useRef(0),v0=a.useRef(null),J=a.useRef(0),k0=a.useRef(null),t0=a.useRef(0),g0=a.useRef(null),k=a.useRef(0),B=a.useRef(null);a.useEffect(()=>{O.current=i},[i]),a.useEffect(()=>{e0.current=b},[b]);const s0=a.useCallback(async t=>{var n;const l=++O0.current;(n=v0.current)==null||n.abort();const c=new AbortController;v0.current=c;try{const p=await R0(t,void 0,{signal:c.signal},!0);return j(O0.current,l,c.signal)?(N(o=>({...o,[t]:p.sessions})),U(o=>({...o,[t]:p.next_cursor})),Y(o=>({...o,[t]:p.has_more})),p.sessions):[]}catch(p){return j(O0.current,l,c.signal)&&!Q(p)&&w(p instanceof Error?p.message:"同步会话失败"),[]}},[]);a.useEffect(()=>{const t=new AbortController;return(async()=>{var c;T(!0);try{const[n,p]=await Promise.all([Y0({signal:t.signal}),T0({signal:t.signal})]),d=n.map(_=>{var y,S0;return{..._,runtime_state:((y=p[_.id])==null?void 0:y.state)||(_.enabled?"connecting":"disabled"),runtime_connected:((S0=p[_.id])==null?void 0:S0.connected)===!0}}).filter(_=>_.enabled),S=await Promise.all(d.map(async _=>[_.id,await R0(_.id,void 0,{signal:t.signal})]));if(t.signal.aborted)return;g(d),N(Object.fromEntries(S.map(([_,y])=>[_,y.sessions]))),U(Object.fromEntries(S.map(([_,y])=>[_,y.next_cursor]))),Y(Object.fromEntries(S.map(([_,y])=>[_,y.has_more])));const f=window.localStorage.getItem("ydisks.chat.account.v1")||"",I=d.some(_=>_.id===f)?f:((c=d[0])==null?void 0:c.id)||"";r(I)}catch(n){t.signal.aborted||w(n instanceof Error?n.message:"加载聊天数据失败")}finally{t.signal.aborted||T(!1)}})(),(()=>t.abort())},[]),a.useEffect(()=>{let t=!1,l=0,c=null;const n=async()=>{c=new AbortController;try{const p=await T0({signal:c.signal,timeoutMs:1e4});t||g(o=>o.map(d=>{var S,f;return{...d,runtime_state:((S=p[d.id])==null?void 0:S.state)||d.runtime_state,runtime_connected:((f=p[d.id])==null?void 0:f.connected)??d.runtime_connected}}))}catch{}finally{t||(l=window.setTimeout(n,3e3))}};return l=window.setTimeout(n,3e3),(()=>{t=!0,window.clearTimeout(l),c==null||c.abort()})},[]),a.useEffect(()=>{if(!i)return;window.localStorage.setItem("ydisks.chat.account.v1",i);const t=x[i]||[];P(l=>{var c;return t.some(n=>n.chat_id===l)?l:((c=t[0])==null?void 0:c.chat_id)||""})},[i,x]),a.useEffect(()=>{!i||I0.current.has(i)||(I0.current.add(i),s0(i))},[i,s0]),a.useEffect(()=>{var c;if(!i||!b){v([]);return}const t=++J.current;(c=k0.current)==null||c.abort();const l=new AbortController;return k0.current=l,D(!0),Promise.all([M0(i,b,void 0,void 0,{signal:l.signal}),q0(i,b,{signal:l.signal})]).then(([n])=>{j(J.current,t,l.signal)&&(v(n.messages),n0(n.has_more),l0(n.next_cursor),n.session&&N(p=>({...p,[i]:(p[i]||[]).map(o=>{var d;return o.chat_id===((d=n.session)==null?void 0:d.chat_id)?n.session:o})})),N(p=>({...p,[i]:(p[i]||[]).map(o=>o.chat_id===b?{...o,unread_count:0}:o)})))}).catch(n=>{j(J.current,t,l.signal)&&!Q(n)&&w(n instanceof Error?n.message:"加载消息失败")}).finally(()=>{j(J.current,t,l.signal)&&D(!1)}),(()=>l.abort())},[i,b]),a.useEffect(()=>{var t;(t=g0.current)==null||t.abort(),t0.current+=1},[i]),a.useEffect(()=>{var t;(t=B.current)==null||t.abort(),k.current+=1},[i,b]),a.useEffect(()=>(()=>{var t,l,c,n;(t=v0.current)==null||t.abort(),(l=k0.current)==null||l.abort(),(c=g0.current)==null||c.abort(),(n=B.current)==null||n.abort()}),[]);const A0=a.useCallback(async()=>{var p;if(!i||!b||z||!W)return;const t=p0.current,l=(t==null?void 0:t.scrollHeight)||0,c=J.current,n=new AbortController;m0.current=!0,V(!0),w("");try{const o=(p=E[0])==null?void 0:p.id,d=await M0(i,b,r0,o,{signal:n.signal});if(!j(J.current,c,n.signal))return;v(S=>ge(S,d.messages)),n0(d.has_more),l0(d.next_cursor),requestAnimationFrame(()=>{t&&(t.scrollTop+=t.scrollHeight-l)})}catch(o){m0.current=!1,Q(o)||w(o instanceof Error?o.message:"加载历史消息失败")}finally{V(!1)}},[i,b,W,r0,E,z]);a.useEffect(()=>{let t=!1,l=0,c=0,n=null;const p=()=>{if(t)return;H("connecting");const o=window.location.protocol==="https:"?"wss:":"ws:";n=new WebSocket(`${o}//${window.location.host}/api/v1/chat/ws`),n.onopen=()=>{c=0,H("online")},n.onmessage=d=>{try{const f=JSON.parse(d.data).message;if(!f)return;const I=f.account_id;N(_=>{const y=_[I]||[];return y.some(R=>R.chat_id===f.chat_id)?{..._,[I]:y.map(R=>R.chat_id===f.chat_id?{...R,last_message:f.content,last_message_at:f.sent_at,unread_count:f.direction==="incoming"&&(O.current!==I||e0.current!==f.chat_id)?R.unread_count+1:R.unread_count}:R).sort((R,V0)=>V0.last_message_at-R.last_message_at)}:(s0(I),_)}),O.current===I&&e0.current===f.chat_id&&(v(_=>D0(_,f)),f.direction==="incoming"&&q0(I,f.chat_id))}catch{}},n.onclose=()=>{if(t)return;H("offline");const d=Math.min(15e3,1e3*2**Math.min(c++,4));l=window.setTimeout(p,d)},n.onerror=()=>n==null?void 0:n.close()};return p(),(()=>{t=!0,window.clearTimeout(l),n==null||n.close()})},[s0]);const H0=a.useCallback(()=>{const t=p0.current;if(!t)return;const l=t.scrollHeight-t.scrollTop-t.clientHeight;C0.current=l<=48},[]);a.useLayoutEffect(()=>{const t=N0.current.accountID!==i||N0.current.chatID!==b;N0.current={accountID:i,chatID:b},t&&(C0.current=!0);const l=p0.current;if(l){if(m0.current){m0.current=!1;return}(L||C0.current)&&(l.scrollTop=l.scrollHeight)}},[i,b,E,L]);const F0=m.find(t=>t.id===i),d0=x[i]||[],h=d0.find(t=>t.chat_id===b),J0=a.useMemo(()=>me(d0,Z,M),[d0,Z,M]),B0=a.useCallback(t=>(x[t]||[]).reduce((l,c)=>l+c.unread_count,0),[x]),Q0=a.useCallback(async()=>{var n;if(!i||K||!X[i])return;const t=++t0.current;(n=g0.current)==null||n.abort();const l=new AbortController;g0.current=l;const c=i;c0(!0),w("");try{const p=await R0(c,G[c],{signal:l.signal},!0);if(!j(t0.current,t,l.signal))return;N(o=>({...o,[c]:p.sessions})),U(o=>({...o,[c]:p.next_cursor})),Y(o=>({...o,[c]:p.has_more}))}catch(p){j(t0.current,t,l.signal)&&!Q(p)&&w(p instanceof Error?p.message:"加载历史联系人失败")}finally{j(t0.current,t,l.signal)&&c0(!1)}},[i,G,K,X]),x0=a.useCallback(async(t,l)=>{var p;if(!h||!i||C)return;const c=++k.current;(p=B.current)==null||p.abort();const n=new AbortController;B.current=n,A(!0),w("");try{const o=await G0({account_id:i,chat_id:h.chat_id,buyer_id:h.buyer_id,buyer_name:h.buyer_name,item_id:h.item_id,item_title:h.item_title,text:t},{signal:n.signal});if(!j(k.current,c,n.signal))return;a0(""),$(null),v(d=>D0(d,o.message))}catch(o){j(k.current,c,n.signal)&&(l&&$(t),Q(o)||w(o instanceof Error?o.message:"消息发送失败"))}finally{j(k.current,c,n.signal)&&A(!1)}},[i,h,C]),_0=a.useCallback(async(t,l)=>{var p;if(!h||!i||C)return;const c=++k.current;(p=B.current)==null||p.abort();const n=new AbortController;B.current=n,A(!0),w("");try{const o=await X0({account_id:i,chat_id:h.chat_id,buyer_id:h.buyer_id,buyer_name:h.buyer_name,buyer_avatar_url:h.buyer_avatar_url,item_id:h.item_id,item_title:h.item_title,image:t},{signal:n.signal});if(!j(k.current,c,n.signal))return;u(null),v(d=>D0(d,o.message))}catch(o){j(k.current,c,n.signal)&&(l&&u(t),Q(o)||w(o instanceof Error?o.message:"图片发送失败"))}finally{j(k.current,c,n.signal)&&(A(!1),y0.current&&(y0.current.value=""))}},[i,h,C]),P0=a.useCallback(async()=>{const t=q.trim();!t||!h||!i||C||await x0(t,!0)},[i,q,h,x0,C]),Z0=a.useCallback(async t=>{!t||!h||!i||C||await _0(t,!0)},[i,h,_0,C]),z0=a.useCallback(async()=>{F?await x0(F,!1):s&&await _0(s,!1)},[s,F,_0,x0]);return{accounts:m,activeAccountID:i,activeSessions:d0,selectedSession:h,activeAccount:F0,messages:E,search:Z,unreadOnly:M,draft:q,loading:b0,messagesLoading:L,olderLoading:z,hasOlder:W,contactsLoading:K,hasMoreContacts:X[i]===!0,emojiOpen:o0,sending:C,error:j0,liveState:w0,activeChatID:b,filteredSessions:J0,scrollRef:p0,imageInputRef:y0,setActiveAccountID:r,setActiveChatID:P,setSearch:h0,setUnreadOnly:u0,setDraft:a0,setEmojiOpen:f0,reloadSessions:s0,loadMoreContacts:Q0,loadOlderMessages:A0,handleMessageScroll:H0,handleSend:P0,handleImage:Z0,retrySend:z0,retryAvailable:!!(F||s),unreadForAccount:B0,emojiURL:ce,xianyuEmojis:U0,renderXianyuText:pe,formatClock:de,messageTime:xe}},fe=()=>{const{accounts:m,activeAccountID:g,activeChatID:i,activeAccount:r,selectedSession:x,filteredSessions:N,messages:b,search:P,unreadOnly:E,draft:v,loading:Z,messagesLoading:h0,olderLoading:M,hasOlder:u0,contactsLoading:q,hasMoreContacts:a0,emojiOpen:b0,sending:T,error:L,liveState:D,scrollRef:z,imageInputRef:V,setActiveAccountID:W,setActiveChatID:n0,setSearch:r0,setUnreadOnly:l0,setDraft:G,setEmojiOpen:U,reloadSessions:X,loadMoreContacts:Y,loadOlderMessages:K,handleMessageScroll:c0,handleSend:o0,handleImage:f0,retrySend:C,retryAvailable:A,unreadForAccount:j0,emojiURL:w,xianyuEmojis:w0,renderXianyuText:H,formatClock:F,messageTime:$}=_e();return Z?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(i0,{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 ${D==="online"?"bg-emerald-50 text-emerald-700":D==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[D==="online"?e.jsx(K0,{className:"h-3.5 w-3.5"}):e.jsx($0,{className:"h-3.5 w-3.5"}),D==="online"?"实时同步中":D==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:m.map(s=>{const u=s.id===g,O=j0(s.id),e0=s.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":u,onClick:(()=>W(s.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${u?"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 ${e0?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:s.nickname||s.remark||s.id}),O>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:O>99?"99+":O})]},s.id)})})]}),m.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{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(ee,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:P,onChange:(s=>r0(s.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:(()=>l0(s=>!s)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${E?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:E?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void X(g)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(te,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[N.map(s=>e.jsxs("button",{type:"button",onClick:(()=>n0(s.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${s.chat_id===i?"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:s.buyer_avatar_url?e.jsx("img",{src:s.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(E0,{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:s.buyer_name||`用户 ${s.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:F(s.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:s.last_message||"暂无消息"}),s.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:s.unread_count})]}),s.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",s.item_title]})]})]},s.chat_id)),N.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),a0&&!P&&!E&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void Y()),disabled:q,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:[q&&e.jsx(i0,{className:"h-3.5 w-3.5 animate-spin"}),q?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:x?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:x.buyer_name||x.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",x.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(r==null?void 0:r.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(r==null?void 0:r.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:z,onScroll:c0,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:h0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(i0,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[u0&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void K()),disabled:M,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:[M&&e.jsx(i0,{className:"h-3.5 w-3.5 animate-spin"}),M?"正在加载":"加载更早消息"]})}),b.map(s=>{const u=s.direction==="outgoing";return s.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:[H(s.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:$(s.sent_at)})]})},s.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${u?"justify-end":"justify-start"}`,children:[!u&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:x.buyer_avatar_url?e.jsx("img",{src:x.buyer_avatar_url,alt:x.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${u?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:u?(r==null?void 0:r.nickname)||(r==null?void 0:r.remark)||"我":x.buyer_name||s.sender_name||x.buyer_id}),s.message_type==="image"?e.jsx("a",{href:s.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${u?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:s.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):s.message_type==="video"?e.jsx("video",{src:s.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 ${u?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:H(s.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[$(s.sent_at),u&&(s.status==="failed"?e.jsx(se,{className:"h-3 w-3 text-red-500"}):s.status==="sent"?e.jsx(ie,{className:"h-3 w-3 text-sky-500"}):e.jsx(ae,{className:"h-3 w-3"}))]})]}),u&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:r!=null&&r.avatar_url?e.jsx("img",{src:r.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"m-2 h-5 w-5 text-sky-600"})})]},s.message_key)})]})}),L&&e.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:[e.jsx("span",{children:L}),A&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void C()),children:"重试发送"})]}),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:(()=>U(s=>!s)),disabled:T||(r==null?void 0:r.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(ne,{className:"h-5 w-5"})}),b0&&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:w0.map(([s,u])=>e.jsx("button",{type:"button",title:`[${s}]`,onClick:(()=>{G(O=>O+`[${s}]`),U(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:w(u),alt:`[${s}]`,className:"h-8 w-8 object-contain"})},s))})]})]}),e.jsx("input",{ref:V,type:"file",accept:"image/*",className:"hidden",onChange:(s=>{var u;return void f0((u=s.target.files)==null?void 0:u[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var s;return(s=V.current)==null?void 0:s.click()}),disabled:T||(r==null?void 0:r.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(re,{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:v,onChange:(s=>G(s.target.value)),rows:2,maxLength:2e3,onKeyDown:(s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),o0())}),disabled:(r==null?void 0:r.runtime_state)!=="online",placeholder:(r==null?void 0:r.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 o0()),disabled:!v.trim()||T||(r==null?void 0:r.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:T?e.jsx(i0,{className:"h-4 w-4 animate-spin"}):e.jsx(le,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{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:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})};export{fe as default}; +import{j as e,c as W0,r as a}from"./react-vendor-C_od1ZSF.js";import{ap as R0,aq as M0,ar as q0,as as G0,at as X0,h as Y0,j as T0}from"./index-CsLZwESi.js";import{f as i0,ak as K0,al as $0,M as L0,I as ee,R as te,ad as E0,k as se,am as ie,s as ae,an as ne,ao as re,ah as le}from"./icons-vendor-ThcsWkZG.js";const U0=[["尊嘟假嘟","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"]],ce=m=>m,oe=new Map(U0.map(([m,g])=>[m,g])),pe=m=>m.split(/(\[[^\]]+\])/g).map((g,i)=>{const r=g.startsWith("[")?oe.get(g.slice(1,-1)):void 0;return r?e.jsx("img",{src:r,alt:g,title:g,className:"mx-0.5 inline-block h-7 w-7 align-middle"},i):e.jsx(W0.Fragment,{children:g},i)}),me=(m,g,i)=>{const r=g.trim().toLowerCase();return m.filter(x=>i&&x.unread_count<=0?!1:r?[x.buyer_name,x.buyer_id,x.item_title,x.last_message].some(N=>(N||"").toLowerCase().includes(r)):!0)},ge=(m,g)=>{const i=new Set(m.map(r=>r.message_key));return[...g.filter(r=>!i.has(r.message_key)),...m]},D0=(m,g)=>{const i=m.findIndex(r=>r.message_key===g.message_key);return i<0?[...m,g]:m.map((r,x)=>x===i?g:r)},j=(m,g,i)=>m===g&&!i.aborted,Q=m=>m instanceof Error&&m.message==="请求已取消",de=m=>{if(!m)return"";const g=new Date(m<1e10?m*1e3:m),i=new Date;return g.toDateString()===i.toDateString()?g.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):g.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},xe=m=>new Date(m<1e10?m*1e3:m).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),_e=()=>{const[m,g]=a.useState([]),[i,r]=a.useState(""),[x,N]=a.useState({}),[b,P]=a.useState(""),[E,v]=a.useState([]),[Z,h0]=a.useState(""),[M,u0]=a.useState(!1),[q,a0]=a.useState(""),[b0,T]=a.useState(!0),[L,D]=a.useState(!1),[z,V]=a.useState(!1),[W,n0]=a.useState(!1),[r0,l0]=a.useState(),[G,U]=a.useState({}),[X,Y]=a.useState({}),[K,c0]=a.useState(!1),[o0,f0]=a.useState(!1),[C,A]=a.useState(!1),[j0,w]=a.useState(""),[w0,H]=a.useState("connecting"),[F,$]=a.useState(null),[s,u]=a.useState(null),O=a.useRef(""),e0=a.useRef(""),p0=a.useRef(null),N0=a.useRef({accountID:"",chatID:""}),C0=a.useRef(!0),m0=a.useRef(!1),y0=a.useRef(null),I0=a.useRef(new Set),O0=a.useRef(0),v0=a.useRef(null),J=a.useRef(0),k0=a.useRef(null),t0=a.useRef(0),g0=a.useRef(null),k=a.useRef(0),B=a.useRef(null);a.useEffect(()=>{O.current=i},[i]),a.useEffect(()=>{e0.current=b},[b]);const s0=a.useCallback(async t=>{var n;const l=++O0.current;(n=v0.current)==null||n.abort();const c=new AbortController;v0.current=c;try{const p=await R0(t,void 0,{signal:c.signal},!0);return j(O0.current,l,c.signal)?(N(o=>({...o,[t]:p.sessions})),U(o=>({...o,[t]:p.next_cursor})),Y(o=>({...o,[t]:p.has_more})),p.sessions):[]}catch(p){return j(O0.current,l,c.signal)&&!Q(p)&&w(p instanceof Error?p.message:"同步会话失败"),[]}},[]);a.useEffect(()=>{const t=new AbortController;return(async()=>{var c;T(!0);try{const[n,p]=await Promise.all([Y0({signal:t.signal}),T0({signal:t.signal})]),d=n.map(_=>{var y,S0;return{..._,runtime_state:((y=p[_.id])==null?void 0:y.state)||(_.enabled?"connecting":"disabled"),runtime_connected:((S0=p[_.id])==null?void 0:S0.connected)===!0}}).filter(_=>_.enabled),S=await Promise.all(d.map(async _=>[_.id,await R0(_.id,void 0,{signal:t.signal})]));if(t.signal.aborted)return;g(d),N(Object.fromEntries(S.map(([_,y])=>[_,y.sessions]))),U(Object.fromEntries(S.map(([_,y])=>[_,y.next_cursor]))),Y(Object.fromEntries(S.map(([_,y])=>[_,y.has_more])));const f=window.localStorage.getItem("ydisks.chat.account.v1")||"",I=d.some(_=>_.id===f)?f:((c=d[0])==null?void 0:c.id)||"";r(I)}catch(n){t.signal.aborted||w(n instanceof Error?n.message:"加载聊天数据失败")}finally{t.signal.aborted||T(!1)}})(),(()=>t.abort())},[]),a.useEffect(()=>{let t=!1,l=0,c=null;const n=async()=>{c=new AbortController;try{const p=await T0({signal:c.signal,timeoutMs:1e4});t||g(o=>o.map(d=>{var S,f;return{...d,runtime_state:((S=p[d.id])==null?void 0:S.state)||d.runtime_state,runtime_connected:((f=p[d.id])==null?void 0:f.connected)??d.runtime_connected}}))}catch{}finally{t||(l=window.setTimeout(n,3e3))}};return l=window.setTimeout(n,3e3),(()=>{t=!0,window.clearTimeout(l),c==null||c.abort()})},[]),a.useEffect(()=>{if(!i)return;window.localStorage.setItem("ydisks.chat.account.v1",i);const t=x[i]||[];P(l=>{var c;return t.some(n=>n.chat_id===l)?l:((c=t[0])==null?void 0:c.chat_id)||""})},[i,x]),a.useEffect(()=>{!i||I0.current.has(i)||(I0.current.add(i),s0(i))},[i,s0]),a.useEffect(()=>{var c;if(!i||!b){v([]);return}const t=++J.current;(c=k0.current)==null||c.abort();const l=new AbortController;return k0.current=l,D(!0),Promise.all([M0(i,b,void 0,void 0,{signal:l.signal}),q0(i,b,{signal:l.signal})]).then(([n])=>{j(J.current,t,l.signal)&&(v(n.messages),n0(n.has_more),l0(n.next_cursor),n.session&&N(p=>({...p,[i]:(p[i]||[]).map(o=>{var d;return o.chat_id===((d=n.session)==null?void 0:d.chat_id)?n.session:o})})),N(p=>({...p,[i]:(p[i]||[]).map(o=>o.chat_id===b?{...o,unread_count:0}:o)})))}).catch(n=>{j(J.current,t,l.signal)&&!Q(n)&&w(n instanceof Error?n.message:"加载消息失败")}).finally(()=>{j(J.current,t,l.signal)&&D(!1)}),(()=>l.abort())},[i,b]),a.useEffect(()=>{var t;(t=g0.current)==null||t.abort(),t0.current+=1},[i]),a.useEffect(()=>{var t;(t=B.current)==null||t.abort(),k.current+=1},[i,b]),a.useEffect(()=>(()=>{var t,l,c,n;(t=v0.current)==null||t.abort(),(l=k0.current)==null||l.abort(),(c=g0.current)==null||c.abort(),(n=B.current)==null||n.abort()}),[]);const A0=a.useCallback(async()=>{var p;if(!i||!b||z||!W)return;const t=p0.current,l=(t==null?void 0:t.scrollHeight)||0,c=J.current,n=new AbortController;m0.current=!0,V(!0),w("");try{const o=(p=E[0])==null?void 0:p.id,d=await M0(i,b,r0,o,{signal:n.signal});if(!j(J.current,c,n.signal))return;v(S=>ge(S,d.messages)),n0(d.has_more),l0(d.next_cursor),requestAnimationFrame(()=>{t&&(t.scrollTop+=t.scrollHeight-l)})}catch(o){m0.current=!1,Q(o)||w(o instanceof Error?o.message:"加载历史消息失败")}finally{V(!1)}},[i,b,W,r0,E,z]);a.useEffect(()=>{let t=!1,l=0,c=0,n=null;const p=()=>{if(t)return;H("connecting");const o=window.location.protocol==="https:"?"wss:":"ws:";n=new WebSocket(`${o}//${window.location.host}/api/v1/chat/ws`),n.onopen=()=>{c=0,H("online")},n.onmessage=d=>{try{const f=JSON.parse(d.data).message;if(!f)return;const I=f.account_id;N(_=>{const y=_[I]||[];return y.some(R=>R.chat_id===f.chat_id)?{..._,[I]:y.map(R=>R.chat_id===f.chat_id?{...R,last_message:f.content,last_message_at:f.sent_at,unread_count:f.direction==="incoming"&&(O.current!==I||e0.current!==f.chat_id)?R.unread_count+1:R.unread_count}:R).sort((R,V0)=>V0.last_message_at-R.last_message_at)}:(s0(I),_)}),O.current===I&&e0.current===f.chat_id&&(v(_=>D0(_,f)),f.direction==="incoming"&&q0(I,f.chat_id))}catch{}},n.onclose=()=>{if(t)return;H("offline");const d=Math.min(15e3,1e3*2**Math.min(c++,4));l=window.setTimeout(p,d)},n.onerror=()=>n==null?void 0:n.close()};return p(),(()=>{t=!0,window.clearTimeout(l),n==null||n.close()})},[s0]);const H0=a.useCallback(()=>{const t=p0.current;if(!t)return;const l=t.scrollHeight-t.scrollTop-t.clientHeight;C0.current=l<=48},[]);a.useLayoutEffect(()=>{const t=N0.current.accountID!==i||N0.current.chatID!==b;N0.current={accountID:i,chatID:b},t&&(C0.current=!0);const l=p0.current;if(l){if(m0.current){m0.current=!1;return}(L||C0.current)&&(l.scrollTop=l.scrollHeight)}},[i,b,E,L]);const F0=m.find(t=>t.id===i),d0=x[i]||[],h=d0.find(t=>t.chat_id===b),J0=a.useMemo(()=>me(d0,Z,M),[d0,Z,M]),B0=a.useCallback(t=>(x[t]||[]).reduce((l,c)=>l+c.unread_count,0),[x]),Q0=a.useCallback(async()=>{var n;if(!i||K||!X[i])return;const t=++t0.current;(n=g0.current)==null||n.abort();const l=new AbortController;g0.current=l;const c=i;c0(!0),w("");try{const p=await R0(c,G[c],{signal:l.signal},!0);if(!j(t0.current,t,l.signal))return;N(o=>({...o,[c]:p.sessions})),U(o=>({...o,[c]:p.next_cursor})),Y(o=>({...o,[c]:p.has_more}))}catch(p){j(t0.current,t,l.signal)&&!Q(p)&&w(p instanceof Error?p.message:"加载历史联系人失败")}finally{j(t0.current,t,l.signal)&&c0(!1)}},[i,G,K,X]),x0=a.useCallback(async(t,l)=>{var p;if(!h||!i||C)return;const c=++k.current;(p=B.current)==null||p.abort();const n=new AbortController;B.current=n,A(!0),w("");try{const o=await G0({account_id:i,chat_id:h.chat_id,buyer_id:h.buyer_id,buyer_name:h.buyer_name,item_id:h.item_id,item_title:h.item_title,text:t},{signal:n.signal});if(!j(k.current,c,n.signal))return;a0(""),$(null),v(d=>D0(d,o.message))}catch(o){j(k.current,c,n.signal)&&(l&&$(t),Q(o)||w(o instanceof Error?o.message:"消息发送失败"))}finally{j(k.current,c,n.signal)&&A(!1)}},[i,h,C]),_0=a.useCallback(async(t,l)=>{var p;if(!h||!i||C)return;const c=++k.current;(p=B.current)==null||p.abort();const n=new AbortController;B.current=n,A(!0),w("");try{const o=await X0({account_id:i,chat_id:h.chat_id,buyer_id:h.buyer_id,buyer_name:h.buyer_name,buyer_avatar_url:h.buyer_avatar_url,item_id:h.item_id,item_title:h.item_title,image:t},{signal:n.signal});if(!j(k.current,c,n.signal))return;u(null),v(d=>D0(d,o.message))}catch(o){j(k.current,c,n.signal)&&(l&&u(t),Q(o)||w(o instanceof Error?o.message:"图片发送失败"))}finally{j(k.current,c,n.signal)&&(A(!1),y0.current&&(y0.current.value=""))}},[i,h,C]),P0=a.useCallback(async()=>{const t=q.trim();!t||!h||!i||C||await x0(t,!0)},[i,q,h,x0,C]),Z0=a.useCallback(async t=>{!t||!h||!i||C||await _0(t,!0)},[i,h,_0,C]),z0=a.useCallback(async()=>{F?await x0(F,!1):s&&await _0(s,!1)},[s,F,_0,x0]);return{accounts:m,activeAccountID:i,activeSessions:d0,selectedSession:h,activeAccount:F0,messages:E,search:Z,unreadOnly:M,draft:q,loading:b0,messagesLoading:L,olderLoading:z,hasOlder:W,contactsLoading:K,hasMoreContacts:X[i]===!0,emojiOpen:o0,sending:C,error:j0,liveState:w0,activeChatID:b,filteredSessions:J0,scrollRef:p0,imageInputRef:y0,setActiveAccountID:r,setActiveChatID:P,setSearch:h0,setUnreadOnly:u0,setDraft:a0,setEmojiOpen:f0,reloadSessions:s0,loadMoreContacts:Q0,loadOlderMessages:A0,handleMessageScroll:H0,handleSend:P0,handleImage:Z0,retrySend:z0,retryAvailable:!!(F||s),unreadForAccount:B0,emojiURL:ce,xianyuEmojis:U0,renderXianyuText:pe,formatClock:de,messageTime:xe}},fe=()=>{const{accounts:m,activeAccountID:g,activeChatID:i,activeAccount:r,selectedSession:x,filteredSessions:N,messages:b,search:P,unreadOnly:E,draft:v,loading:Z,messagesLoading:h0,olderLoading:M,hasOlder:u0,contactsLoading:q,hasMoreContacts:a0,emojiOpen:b0,sending:T,error:L,liveState:D,scrollRef:z,imageInputRef:V,setActiveAccountID:W,setActiveChatID:n0,setSearch:r0,setUnreadOnly:l0,setDraft:G,setEmojiOpen:U,reloadSessions:X,loadMoreContacts:Y,loadOlderMessages:K,handleMessageScroll:c0,handleSend:o0,handleImage:f0,retrySend:C,retryAvailable:A,unreadForAccount:j0,emojiURL:w,xianyuEmojis:w0,renderXianyuText:H,formatClock:F,messageTime:$}=_e();return Z?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(i0,{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 ${D==="online"?"bg-emerald-50 text-emerald-700":D==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[D==="online"?e.jsx(K0,{className:"h-3.5 w-3.5"}):e.jsx($0,{className:"h-3.5 w-3.5"}),D==="online"?"实时同步中":D==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:m.map(s=>{const u=s.id===g,O=j0(s.id),e0=s.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":u,onClick:(()=>W(s.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${u?"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 ${e0?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:s.nickname||s.remark||s.id}),O>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:O>99?"99+":O})]},s.id)})})]}),m.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{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(ee,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:P,onChange:(s=>r0(s.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:(()=>l0(s=>!s)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${E?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:E?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void X(g)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(te,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[N.map(s=>e.jsxs("button",{type:"button",onClick:(()=>n0(s.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${s.chat_id===i?"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:s.buyer_avatar_url?e.jsx("img",{src:s.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(E0,{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:s.buyer_name||`用户 ${s.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:F(s.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:s.last_message||"暂无消息"}),s.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:s.unread_count})]}),s.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",s.item_title]})]})]},s.chat_id)),N.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),a0&&!P&&!E&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void Y()),disabled:q,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:[q&&e.jsx(i0,{className:"h-3.5 w-3.5 animate-spin"}),q?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:x?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:x.buyer_name||x.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",x.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(r==null?void 0:r.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(r==null?void 0:r.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:z,onScroll:c0,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:h0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(i0,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[u0&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void K()),disabled:M,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:[M&&e.jsx(i0,{className:"h-3.5 w-3.5 animate-spin"}),M?"正在加载":"加载更早消息"]})}),b.map(s=>{const u=s.direction==="outgoing";return s.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:[H(s.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:$(s.sent_at)})]})},s.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${u?"justify-end":"justify-start"}`,children:[!u&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:x.buyer_avatar_url?e.jsx("img",{src:x.buyer_avatar_url,alt:x.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${u?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:u?(r==null?void 0:r.nickname)||(r==null?void 0:r.remark)||"我":x.buyer_name||s.sender_name||x.buyer_id}),s.message_type==="image"?e.jsx("a",{href:s.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${u?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:s.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):s.message_type==="video"?e.jsx("video",{src:s.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 ${u?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:H(s.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[$(s.sent_at),u&&(s.status==="failed"?e.jsx(se,{className:"h-3 w-3 text-red-500"}):s.status==="sent"?e.jsx(ie,{className:"h-3 w-3 text-sky-500"}):e.jsx(ae,{className:"h-3 w-3"}))]})]}),u&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:r!=null&&r.avatar_url?e.jsx("img",{src:r.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"m-2 h-5 w-5 text-sky-600"})})]},s.message_key)})]})}),L&&e.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:[e.jsx("span",{children:L}),A&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void C()),children:"重试发送"})]}),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:(()=>U(s=>!s)),disabled:T||(r==null?void 0:r.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(ne,{className:"h-5 w-5"})}),b0&&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:w0.map(([s,u])=>e.jsx("button",{type:"button",title:`[${s}]`,onClick:(()=>{G(O=>O+`[${s}]`),U(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:w(u),alt:`[${s}]`,className:"h-8 w-8 object-contain"})},s))})]})]}),e.jsx("input",{ref:V,type:"file",accept:"image/*",className:"hidden",onChange:(s=>{var u;return void f0((u=s.target.files)==null?void 0:u[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var s;return(s=V.current)==null?void 0:s.click()}),disabled:T||(r==null?void 0:r.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(re,{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:v,onChange:(s=>G(s.target.value)),rows:2,maxLength:2e3,onKeyDown:(s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),o0())}),disabled:(r==null?void 0:r.runtime_state)!=="online",placeholder:(r==null?void 0:r.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 o0()),disabled:!v.trim()||T||(r==null?void 0:r.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:T?e.jsx(i0,{className:"h-4 w-4 animate-spin"}):e.jsx(le,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{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:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})};export{fe as default}; diff --git a/internal/webui/static/assets/Dashboard-COpr9cLo.js b/internal/webui/static/assets/Dashboard-Ds-nEvf-.js similarity index 99% rename from internal/webui/static/assets/Dashboard-COpr9cLo.js rename to internal/webui/static/assets/Dashboard-Ds-nEvf-.js index eaac4cb..e450091 100644 --- a/internal/webui/static/assets/Dashboard-COpr9cLo.js +++ b/internal/webui/static/assets/Dashboard-Ds-nEvf-.js @@ -1 +1 @@ -import{r as d,j as e}from"./react-vendor-C_od1ZSF.js";import{g as oe,a as ie,b as le,c as ce,d as H,e as de}from"./index-CFJ5pUjO.js";import{f as xe}from"./dateTime-DDi7rqpW.js";import{j as ne,k as me,l as J,D as ue,U as he,P as ge,m as Q,E as be,T as pe}from"./icons-vendor-ThcsWkZG.js";import{R as E,B as fe,X as Z,Y as ee,T as z,a as ye,C as V,A as je,b as ve,c as Ne,P as te,d as se,L as we}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";const _e=s=>{const r={};return s.forEach(a=>{r[a.item_id]=a.item_title||a.item_id}),r},ke=s=>{var r;return((r=s.daily_stats)==null?void 0:r.map(a=>({name:a.date.slice(5),amount:a.amount,orders:a.order_count,avgAmount:a.order_count>0?(a.amount/a.order_count).toFixed(2):0})))||[]},Ce=(s,r)=>(s.item_stats||[]).map(a=>{const n=r[a.item_id]||a.item_id;return{name:n.length>12?`${n.substring(0,12)}...`:n,sales:a.order_count}}).sort((a,n)=>n.sales-a.sales).slice(0,10),Se=(s,r,a)=>{const n=s.revenue_stats.total_orders||0;return(s.item_stats||[]).map(l=>{const o=r[l.item_id]||l.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:l.order_count,percent:n>0?l.order_count/n*100:0}}).sort((l,o)=>o.value-l.value).slice(0,6).map((l,o)=>({...l,color:a[o%a.length]}))},De=(s,r,a)=>{const n=s.revenue_stats.total_amount||0;return(s.item_stats||[]).map(l=>{const o=r[l.item_id]||l.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:l.total_amount,orderCount:l.order_count,percentage:n>0?l.total_amount/n*100:0}}).sort((l,o)=>o.value-l.value).slice(0,5).map((l,o)=>({...l,color:a[o%a.length],percentage:l.percentage.toFixed(1)}))},$e=(s,r)=>{if(!s||!r)return null;const a=s.revenue_stats.total_amount,n=r.revenue_stats.total_amount;if(n===0)return a>0?"+100%":"0%";const l=(a-n)/n*100;return`${l>=0?"+":""}${l.toFixed(1)}%`},Re=s=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[s.range]||"所选范围",Le=s=>Math.max(...s.map(r=>r.sales),1),ae=(s,r,a)=>s===r&&!a.aborted,re=s=>s instanceof Error&&s.message==="请求已取消",q=(s,r)=>s instanceof Error?s.message:r,Ae=s=>{const{range:r,customStartDate:a,customEndDate:n,customRangeVersion:l}=s,[o,S]=d.useState(null),[w,M]=d.useState(null),[F,v]=d.useState({overview:"idle",range:"idle",error:""}),[c,O]=d.useState(0),D=d.useRef(0),P=d.useMemo(()=>({range:r,customStartDate:a,customEndDate:n}),[n,a,r]),$=d.useCallback(()=>O(x=>x+1),[]);d.useEffect(()=>{const x=new AbortController;return v(g=>({...g,overview:"loading",error:""})),Promise.all([oe({signal:x.signal}),ie(void 0,{signal:x.signal})]).then(([g,h])=>{x.signal.aborted||(S({stats:g,items:h,itemNames:_e(h)}),v(u=>({...u,overview:"success"})))}).catch(g=>{x.signal.aborted||re(g)||v(h=>({...h,overview:"error",error:q(g,"概览加载失败")}))}),(()=>x.abort())},[c]),d.useEffect(()=>{let x;try{x=le(r,new Date,a,n)}catch(b){v(k=>({...k,range:"error",error:q(b,"日期范围无效")}));return}const g=ce(x),h=++D.current,u=new AbortController;return v(b=>({...b,range:"loading",error:""})),Promise.all([H({start_date:x.startDate,end_date:x.endDate},{signal:u.signal}),H({start_date:g.startDate,end_date:g.endDate},{signal:u.signal}),de({start_date:x.startDate,end_date:x.endDate},{signal:u.signal})]).then(([b,k,L])=>{ae(D.current,h,u.signal)&&(M({analytics:b,previousAnalytics:k,validOrders:L,dateRange:x}),v(B=>({...B,range:"success"})))}).catch(b=>{!ae(D.current,h,u.signal)||re(b)||v(k=>({...k,range:"error",error:q(b,"经营数据加载失败")}))}),(()=>u.abort())},[l,r,c]);const f=d.useMemo(()=>o&&w?{...o,...w}:null,[o,w]),_=(o==null?void 0:o.itemNames)||{},m=(w==null?void 0:w.analytics)||null,K=d.useMemo(()=>m?ke(m):[],[m]),C=d.useMemo(()=>m?Ce(m,_):[],[m,_]),y=d.useMemo(()=>["rgb(var(--color-brand))","rgb(var(--color-brand-highlight))","rgb(var(--color-success-500))","rgb(var(--color-warning-500))","rgb(var(--color-accent-500))"],[]),N=d.useMemo(()=>m?Se(m,_,y):[],[m,y,_]),R=d.useMemo(()=>m?De(m,_,y):[],[m,y,_]),I=d.useMemo(()=>Le(C),[C]);return{data:f,status:F,chartData:K,productSalesData:C,sourceData:N,categoryData:R,maxProductSales:I,trendPercent:$e(m,(f==null?void 0:f.previousAnalytics)||null),selectedRangeLabel:Re(P),refresh:$}},i=(s,r)=>r===void 0?`rgb(var(--color-${s}))`:`rgb(var(--color-${s}) / ${r})`,Oe=({chartData:s,selectedRangeLabel:r,totalAmount:a})=>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:[r,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:s.length===0||a===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(ne,{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:"所选时间范围内暂无订单记录"})]}):s.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(fe,{data:s,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Z,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(ee,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(n=>`¥${n}`)}),e.jsx(z,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(n=>[`¥${Number(n).toFixed(2)}`,"营收"])}),e.jsx(ye,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:s.map((n,l)=>e.jsx(V,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${l}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(je,{data:s,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:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(Z,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(ee,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(ve,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(z,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Ne,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),j=(s,r)=>`rgb(var(--color-${s}))`,Pe=({status:s})=>{const r={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"},a={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 ${r[s]||r.cancelled}`,children:a[s]||s})},W=({title:s,value:r,icon:a,colorClass:n,trend:l})=>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 ${n} 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 ${n} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(a,{className:`w-6 h-6 ${n.replace("bg-","text-")}`})}),l&&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(pe,{className:"w-3 h-3"})," ",l]})]}),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:r}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:s})]})]}),Ke=()=>{const[s,r]=d.useState("7days"),[a,n]=d.useState(""),[l,o]=d.useState(""),[S,w]=d.useState(""),[M,F]=d.useState(0),v=Ae({range:s,customStartDate:a,customEndDate:l,customRangeVersion:M}),{data:c,status:O,chartData:D,productSalesData:P,sourceData:$,categoryData:f,maxProductSales:_,trendPercent:m,selectedRangeLabel:K,refresh:C}=v,y=(c==null?void 0:c.stats)||null,N=(c==null?void 0:c.analytics)||null;c!=null&&c.previousAnalytics;const R=(c==null?void 0:c.validOrders.orders)||[],I=(c==null?void 0:c.validOrders.total)||0,x=(c==null?void 0:c.validOrders.truncated)||!1,g=O.range==="loading",h=O.error,u=[j("brand"),j("brand-highlight"),j("success-500"),j("warning-500"),j("accent-500")],b=t=>`¥${Number(t||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(h&&(!y||!N))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(me,{className:"w-8 h-8"}),e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:C,children:"重新加载"})]});if(!y||!N)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(J,{className:"w-8 h-8 animate-spin text-brand"})});const k=N.revenue_stats.total_orders||0,L=N.revenue_stats.total_amount||0,B=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let T;try{T=le(s,new Date,a,l)}catch{T={startDate:a,endDate:l}}const A=S.trim().toLowerCase(),G=R.filter(t=>{var p,U,Y,X;return((p=t.order_id)==null?void 0:p.toLowerCase().includes(A))||((U=t.item_id)==null?void 0:U.toLowerCase().includes(A))||((Y=t.item_title)==null?void 0:Y.toLowerCase().includes(A))||((X=t.buyer_id)==null?void 0:X.toLowerCase().includes(A))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[h&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:C,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:[B.map(t=>e.jsx("button",{onClick:(()=>r(t.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${s===t.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:t.label},t.key)),s==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:a,onChange:(t=>n(t.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:l,onChange:(t=>o(t.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:(()=>F(t=>t+1)),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(W,{title:"累计营收 (CNY)",value:`¥${N.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:ue,colorClass:"bg-blue-400",trend:m||void 0}),e.jsx(W,{title:"活跃账号 / 总数",value:`${y.active_cookies} / ${y.total_cookies}`,icon:he,colorClass:"bg-blue-500"}),e.jsx(W,{title:"订单数",value:N.revenue_stats.total_orders.toLocaleString(),icon:ne,colorClass:"bg-blue-500"}),e.jsx(W,{title:"库存卡密余量",value:y.available_card_stock,icon:ge,colorClass:"bg-purple-500"})]}),e.jsx(Oe,{chartData:D,selectedRangeLabel:K,totalAmount:L}),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:P.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:P.map((t,p)=>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 ${p<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:p+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:t.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[t.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,t.sales/_*100)}%`}})})]},`${t.name}-${p}`))})})]}),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":`商品下单占比,共 ${k} 单`,children:$.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(te,{accessibilityLayer:!1,children:[e.jsx(se,{data:$,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:$.map((t,p)=>e.jsx(V,{fill:t.color},`cell-${p}`))}),e.jsx(z,{formatter:(t=>`${Number(t||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(we,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(t=>e.jsx("span",{style:{color:j("neutral-500"),fontWeight:500},children:t}))})]})}),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:k}),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:"参与统计的订单"}),x&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",R.length," / ",I," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:S,onChange:(t=>w(t.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:g?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(J,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):G.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(Q,{className:"w-7 h-7 text-gray-300"})}),A?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:["当前共有 ",R.length," 单参与统计,但没有订单号、商品、买家匹配“",S,"”。"]})]}):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:["日期范围:",T.startDate," 至 ",T.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",N.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:G.map(t=>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(Q,{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:t.item_title||t.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:t.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",t.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:t.buyer_id}),t.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:xe(t.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",t.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(Pe,{status:t.status||t.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=${t.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(be,{className:"w-4 h-4"})})})]},t.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)"}),f.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":`商品金额分析,总金额 ${b(L)}`,children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(te,{accessibilityLayer:!1,children:[e.jsx(se,{data:f,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:f.map((t,p)=>e.jsx(V,{fill:t.color||u[p%u.length]},`cell-${p}`))}),e.jsx(z,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(t=>`¥${Number(t||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:b(L)}),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:f.map(t=>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:t.color||u[f.indexOf(t)%u.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:t.name,children:t.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:["¥",t.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[t.percentage,"%"]})]})]},t.name))})]})]})]})]})};export{Pe as StatusBadge,Ke as default}; +import{r as d,j as e}from"./react-vendor-C_od1ZSF.js";import{g as oe,a as ie,b as le,c as ce,d as H,e as de}from"./index-CsLZwESi.js";import{f as xe}from"./dateTime-DDi7rqpW.js";import{j as ne,k as me,l as J,D as ue,U as he,P as ge,m as Q,E as be,T as pe}from"./icons-vendor-ThcsWkZG.js";import{R as E,B as fe,X as Z,Y as ee,T as z,a as ye,C as V,A as je,b as ve,c as Ne,P as te,d as se,L as we}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";const _e=s=>{const r={};return s.forEach(a=>{r[a.item_id]=a.item_title||a.item_id}),r},ke=s=>{var r;return((r=s.daily_stats)==null?void 0:r.map(a=>({name:a.date.slice(5),amount:a.amount,orders:a.order_count,avgAmount:a.order_count>0?(a.amount/a.order_count).toFixed(2):0})))||[]},Ce=(s,r)=>(s.item_stats||[]).map(a=>{const n=r[a.item_id]||a.item_id;return{name:n.length>12?`${n.substring(0,12)}...`:n,sales:a.order_count}}).sort((a,n)=>n.sales-a.sales).slice(0,10),Se=(s,r,a)=>{const n=s.revenue_stats.total_orders||0;return(s.item_stats||[]).map(l=>{const o=r[l.item_id]||l.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:l.order_count,percent:n>0?l.order_count/n*100:0}}).sort((l,o)=>o.value-l.value).slice(0,6).map((l,o)=>({...l,color:a[o%a.length]}))},De=(s,r,a)=>{const n=s.revenue_stats.total_amount||0;return(s.item_stats||[]).map(l=>{const o=r[l.item_id]||l.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:l.total_amount,orderCount:l.order_count,percentage:n>0?l.total_amount/n*100:0}}).sort((l,o)=>o.value-l.value).slice(0,5).map((l,o)=>({...l,color:a[o%a.length],percentage:l.percentage.toFixed(1)}))},$e=(s,r)=>{if(!s||!r)return null;const a=s.revenue_stats.total_amount,n=r.revenue_stats.total_amount;if(n===0)return a>0?"+100%":"0%";const l=(a-n)/n*100;return`${l>=0?"+":""}${l.toFixed(1)}%`},Re=s=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[s.range]||"所选范围",Le=s=>Math.max(...s.map(r=>r.sales),1),ae=(s,r,a)=>s===r&&!a.aborted,re=s=>s instanceof Error&&s.message==="请求已取消",q=(s,r)=>s instanceof Error?s.message:r,Ae=s=>{const{range:r,customStartDate:a,customEndDate:n,customRangeVersion:l}=s,[o,S]=d.useState(null),[w,M]=d.useState(null),[F,v]=d.useState({overview:"idle",range:"idle",error:""}),[c,O]=d.useState(0),D=d.useRef(0),P=d.useMemo(()=>({range:r,customStartDate:a,customEndDate:n}),[n,a,r]),$=d.useCallback(()=>O(x=>x+1),[]);d.useEffect(()=>{const x=new AbortController;return v(g=>({...g,overview:"loading",error:""})),Promise.all([oe({signal:x.signal}),ie(void 0,{signal:x.signal})]).then(([g,h])=>{x.signal.aborted||(S({stats:g,items:h,itemNames:_e(h)}),v(u=>({...u,overview:"success"})))}).catch(g=>{x.signal.aborted||re(g)||v(h=>({...h,overview:"error",error:q(g,"概览加载失败")}))}),(()=>x.abort())},[c]),d.useEffect(()=>{let x;try{x=le(r,new Date,a,n)}catch(b){v(k=>({...k,range:"error",error:q(b,"日期范围无效")}));return}const g=ce(x),h=++D.current,u=new AbortController;return v(b=>({...b,range:"loading",error:""})),Promise.all([H({start_date:x.startDate,end_date:x.endDate},{signal:u.signal}),H({start_date:g.startDate,end_date:g.endDate},{signal:u.signal}),de({start_date:x.startDate,end_date:x.endDate},{signal:u.signal})]).then(([b,k,L])=>{ae(D.current,h,u.signal)&&(M({analytics:b,previousAnalytics:k,validOrders:L,dateRange:x}),v(B=>({...B,range:"success"})))}).catch(b=>{!ae(D.current,h,u.signal)||re(b)||v(k=>({...k,range:"error",error:q(b,"经营数据加载失败")}))}),(()=>u.abort())},[l,r,c]);const f=d.useMemo(()=>o&&w?{...o,...w}:null,[o,w]),_=(o==null?void 0:o.itemNames)||{},m=(w==null?void 0:w.analytics)||null,K=d.useMemo(()=>m?ke(m):[],[m]),C=d.useMemo(()=>m?Ce(m,_):[],[m,_]),y=d.useMemo(()=>["rgb(var(--color-brand))","rgb(var(--color-brand-highlight))","rgb(var(--color-success-500))","rgb(var(--color-warning-500))","rgb(var(--color-accent-500))"],[]),N=d.useMemo(()=>m?Se(m,_,y):[],[m,y,_]),R=d.useMemo(()=>m?De(m,_,y):[],[m,y,_]),I=d.useMemo(()=>Le(C),[C]);return{data:f,status:F,chartData:K,productSalesData:C,sourceData:N,categoryData:R,maxProductSales:I,trendPercent:$e(m,(f==null?void 0:f.previousAnalytics)||null),selectedRangeLabel:Re(P),refresh:$}},i=(s,r)=>r===void 0?`rgb(var(--color-${s}))`:`rgb(var(--color-${s}) / ${r})`,Oe=({chartData:s,selectedRangeLabel:r,totalAmount:a})=>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:[r,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:s.length===0||a===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(ne,{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:"所选时间范围内暂无订单记录"})]}):s.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(fe,{data:s,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Z,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(ee,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(n=>`¥${n}`)}),e.jsx(z,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(n=>[`¥${Number(n).toFixed(2)}`,"营收"])}),e.jsx(ye,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:s.map((n,l)=>e.jsx(V,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${l}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(je,{data:s,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:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(Z,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(ee,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(ve,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(z,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Ne,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),j=(s,r)=>`rgb(var(--color-${s}))`,Pe=({status:s})=>{const r={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"},a={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 ${r[s]||r.cancelled}`,children:a[s]||s})},W=({title:s,value:r,icon:a,colorClass:n,trend:l})=>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 ${n} 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 ${n} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(a,{className:`w-6 h-6 ${n.replace("bg-","text-")}`})}),l&&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(pe,{className:"w-3 h-3"})," ",l]})]}),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:r}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:s})]})]}),Ke=()=>{const[s,r]=d.useState("7days"),[a,n]=d.useState(""),[l,o]=d.useState(""),[S,w]=d.useState(""),[M,F]=d.useState(0),v=Ae({range:s,customStartDate:a,customEndDate:l,customRangeVersion:M}),{data:c,status:O,chartData:D,productSalesData:P,sourceData:$,categoryData:f,maxProductSales:_,trendPercent:m,selectedRangeLabel:K,refresh:C}=v,y=(c==null?void 0:c.stats)||null,N=(c==null?void 0:c.analytics)||null;c!=null&&c.previousAnalytics;const R=(c==null?void 0:c.validOrders.orders)||[],I=(c==null?void 0:c.validOrders.total)||0,x=(c==null?void 0:c.validOrders.truncated)||!1,g=O.range==="loading",h=O.error,u=[j("brand"),j("brand-highlight"),j("success-500"),j("warning-500"),j("accent-500")],b=t=>`¥${Number(t||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(h&&(!y||!N))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(me,{className:"w-8 h-8"}),e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:C,children:"重新加载"})]});if(!y||!N)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(J,{className:"w-8 h-8 animate-spin text-brand"})});const k=N.revenue_stats.total_orders||0,L=N.revenue_stats.total_amount||0,B=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let T;try{T=le(s,new Date,a,l)}catch{T={startDate:a,endDate:l}}const A=S.trim().toLowerCase(),G=R.filter(t=>{var p,U,Y,X;return((p=t.order_id)==null?void 0:p.toLowerCase().includes(A))||((U=t.item_id)==null?void 0:U.toLowerCase().includes(A))||((Y=t.item_title)==null?void 0:Y.toLowerCase().includes(A))||((X=t.buyer_id)==null?void 0:X.toLowerCase().includes(A))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[h&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:C,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:[B.map(t=>e.jsx("button",{onClick:(()=>r(t.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${s===t.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:t.label},t.key)),s==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:a,onChange:(t=>n(t.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:l,onChange:(t=>o(t.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:(()=>F(t=>t+1)),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(W,{title:"累计营收 (CNY)",value:`¥${N.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:ue,colorClass:"bg-blue-400",trend:m||void 0}),e.jsx(W,{title:"活跃账号 / 总数",value:`${y.active_cookies} / ${y.total_cookies}`,icon:he,colorClass:"bg-blue-500"}),e.jsx(W,{title:"订单数",value:N.revenue_stats.total_orders.toLocaleString(),icon:ne,colorClass:"bg-blue-500"}),e.jsx(W,{title:"库存卡密余量",value:y.available_card_stock,icon:ge,colorClass:"bg-purple-500"})]}),e.jsx(Oe,{chartData:D,selectedRangeLabel:K,totalAmount:L}),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:P.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:P.map((t,p)=>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 ${p<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:p+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:t.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[t.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,t.sales/_*100)}%`}})})]},`${t.name}-${p}`))})})]}),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":`商品下单占比,共 ${k} 单`,children:$.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(te,{accessibilityLayer:!1,children:[e.jsx(se,{data:$,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:$.map((t,p)=>e.jsx(V,{fill:t.color},`cell-${p}`))}),e.jsx(z,{formatter:(t=>`${Number(t||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(we,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(t=>e.jsx("span",{style:{color:j("neutral-500"),fontWeight:500},children:t}))})]})}),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:k}),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:"参与统计的订单"}),x&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",R.length," / ",I," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:S,onChange:(t=>w(t.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:g?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(J,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):G.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(Q,{className:"w-7 h-7 text-gray-300"})}),A?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:["当前共有 ",R.length," 单参与统计,但没有订单号、商品、买家匹配“",S,"”。"]})]}):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:["日期范围:",T.startDate," 至 ",T.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",N.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:G.map(t=>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(Q,{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:t.item_title||t.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:t.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",t.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:t.buyer_id}),t.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:xe(t.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",t.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(Pe,{status:t.status||t.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=${t.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(be,{className:"w-4 h-4"})})})]},t.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)"}),f.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":`商品金额分析,总金额 ${b(L)}`,children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(te,{accessibilityLayer:!1,children:[e.jsx(se,{data:f,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:f.map((t,p)=>e.jsx(V,{fill:t.color||u[p%u.length]},`cell-${p}`))}),e.jsx(z,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(t=>`¥${Number(t||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:b(L)}),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:f.map(t=>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:t.color||u[f.indexOf(t)%u.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:t.name,children:t.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:["¥",t.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[t.percentage,"%"]})]})]},t.name))})]})]})]})]})};export{Pe as StatusBadge,Ke as default}; diff --git a/internal/webui/static/assets/ItemList-DE9qcEo5.js b/internal/webui/static/assets/ItemList-BfR3GASL.js similarity index 99% rename from internal/webui/static/assets/ItemList-DE9qcEo5.js rename to internal/webui/static/assets/ItemList-BfR3GASL.js index 898f355..9b8768c 100644 --- a/internal/webui/static/assets/ItemList-DE9qcEo5.js +++ b/internal/webui/static/assets/ItemList-BfR3GASL.js @@ -1,2 +1,2 @@ -import{r as l,j as e,b as ne}from"./react-vendor-C_od1ZSF.js";import{Q as Fe,R as W,S as nt,T as ct,U as dt,V as ot,W as xt,X as mt,a as _e,Y as ke,h as ht,Z as ut,_ as pt,$ as gt,a0 as bt,a1 as yt}from"./index-CFJ5pUjO.js";import{a3 as ft,i as Ce,R as me,N as Ie,a4 as he,a5 as ce,V as jt,F as Nt,B as vt,a6 as Se,a7 as wt,a8 as _t,A as kt,S as Ct,X as H,r as It,a9 as Be,I as Pe}from"./icons-vendor-ThcsWkZG.js";const Ae="ydisks-amap-js-api",St="c9b68d4ce9a2a97f22a4a439404488ca";let Q=null;const Bt=()=>St,Pt=()=>window.AMap?Promise.resolve(window.AMap):Q||(Q=new Promise((a,n)=>{const h=document.getElementById(Ae),o=h||document.createElement("script"),x=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(B)},g=()=>{window.AMap?(x(),a(window.AMap)):(x(),n(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},B=window.setTimeout(()=>{x(),n(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=g,o.id=Ae,o.async=!0,o.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Bt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,o.onerror=()=>{x(),n(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},h||document.head.appendChild(o)}).catch(a=>{throw Q=null,a}),Q),de=a=>Number.isFinite(a)&&a!==0,At=a=>{var x,g;const n=Number((x=a.location)==null?void 0:x.lng),h=Number((g=a.location)==null?void 0:g.lat),o={area:String(a.adname||"").trim(),city:String(a.cityname||"").trim(),division_id:String(a.adcode||"").trim(),longitude:n,latitude:h,poi_id:String(a.id||"").trim(),poi_name:String(a.name||"").trim(),province:String(a.pname||"").trim()};return!o.division_id||!o.province||!o.city||!o.poi_id||!o.poi_name||!de(n)||!de(h)||n<-180||n>180||h<-90||h>90?null:o},Lt=async(a,n)=>{if(!de(a)||!de(n)||a<-180||a>180||n<-90||n>90)throw new Error("经纬度无效");const h=await Pt();return new Promise((o,x)=>{new h.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[a,n],1e3,(B,u)=>{var k;if(B!=="complete"){if(B==="no_data"){o([]);return}x(new Error("高德地图附近地址查询失败,请稍后重试"));return}const D=(((k=u==null?void 0:u.poiList)==null?void 0:k.pois)||[]).map(At).filter(z=>z!==null);o(D)})})},Rt=a=>a.find(n=>n.status==="running"||n.status==="canceling"),ue=a=>a==="running"||a==="canceling",Ft=a=>!!(a!=null&&a.preview_id&&Number(a.valid||0)>0),Mt=a=>!!(a!=null&&a.id&&Number(a.retryable||0)>0&&!ue(a.status)),Et=(a,n)=>a===n,Le=a=>{switch(a){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 a||"-"}},Re=a=>{switch(a){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"}},$t=a=>{const[n,h]=l.useState(!1),[o,x]=l.useState("upload"),[g,B]=l.useState(null),[u,D]=l.useState(null),[k,z]=l.useState(""),[ee,Y]=l.useState(!1),[T,K]=l.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[f,R]=l.useState(null),[d,w]=l.useState(null),[C,F]=l.useState(null),[O,Z]=l.useState([]),[M,G]=l.useState(null),[te,b]=l.useState(!1),S=l.useRef(!1),J=l.useRef(0),j=l.useCallback(async()=>{x("upload"),R(null),w(null),B(null),D(null),z(""),K({catId:"",catName:"",channelCatId:"",tbCatId:""}),Z([]),G(null),h(!0),b(!0);try{const i=await Fe(20),m=Rt(i);if(m!=null&&m.id){const I=await W(m.id);F(I),w(I),x(["running","canceling"].includes(I.status)?"running":"done")}}catch(i){console.error("恢复最近批量铺货任务失败:",i)}finally{b(!1)}},[]),U=l.useCallback(async()=>{const i=k.trim();if(!a.selectedAccount){alert("请先选择默认发布账号");return}if(!i){alert("请输入类目关键词");return}Y(!0);try{const I=(await nt(a.selectedAccount,i)).category;K({catId:I.cat_id,catName:I.cat_name,channelCatId:I.channel_cat_id,tbCatId:I.tb_cat_id||""})}catch(m){console.error("获取推荐类目失败:",m),alert((m==null?void 0:m.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{Y(!1)}},[k,a.selectedAccount]),p=l.useCallback(async()=>{if(C!=null&&C.id){b(!0),h(!0);try{const i=await W(C.id);w(i),x(["running","canceling"].includes(i.status)?"running":"done")}catch(i){console.error("加载最近批量铺货结果失败:",i)}finally{b(!1)}}},[C==null?void 0:C.id]),P=l.useCallback(async()=>{if(!g){alert("请先上传商品表格");return}if(!a.selectedAccount){alert("请先选择默认发布账号");return}b(!0);try{const i=await ct({file:g,imagesZip:u,defaultCookieId:a.selectedAccount,fallbackCategory:T,location:M||void 0});R(i),w(null),x("preview")}catch(i){console.error("批量铺货预检失败:",i),alert((i==null?void 0:i.message)||"预检失败,请检查表格和图片 zip")}finally{b(!1)}},[T,g,u,M,a.selectedAccount]),r=l.useCallback(async()=>{if(f!=null&&f.preview_id){if(!Ft(f)){alert("没有可发布的商品行");return}b(!0);try{const i=await dt(f.preview_id),m=await W(i.batch_id||f.preview_id);w(m),F(m),x(m.status==="running"?"running":"done")}catch(i){console.error("启动批量铺货失败:",i),alert((i==null?void 0:i.message)||"启动发布任务失败")}finally{b(!1)}}},[f]),_=l.useCallback(async()=>{if(d!=null&&d.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){b(!0);try{const i=await ot(d.id),m=await W(d.id);w(m),x((i==null?void 0:i.status)==="canceling"||m.status==="canceling"?"running":"done")}catch(i){alert((i==null?void 0:i.message)||"取消失败")}finally{b(!1)}}},[d==null?void 0:d.id]),V=l.useCallback(async()=>{const i=f==null?void 0:f.preview_id;if(i&&o==="preview")try{await xt(i)}catch(m){console.error("清理批量铺货预检失败:",m)}R(null),x("upload")},[o,f==null?void 0:f.preview_id]),se=l.useCallback(async()=>{await V(),h(!1)},[V]),E=l.useCallback(async()=>{if(!(!(d!=null&&d.id)||!Mt(d))){b(!0);try{await mt(d.id),w(await W(d.id)),x("running")}catch(i){alert((i==null?void 0:i.message)||"重试失败")}finally{b(!1)}}},[d]);return l.useEffect(()=>{if(!n||!(d!=null&&d.id)||!ue(d.status))return;const i=++J.current,m=async()=>{if(!S.current){S.current=!0;try{const N=await W(d.id);if(!Et(i,J.current))return;w(N),F(N),ue(N.status)||(x("done"),await Promise.all([a.loadItems(),a.loadShippingRules()]))}catch(N){console.error("刷新批量铺货进度失败:",N)}finally{S.current=!1}}},I=window.setInterval(()=>void m(),3e3);return(()=>{window.clearInterval(I),J.current+=1})},[d==null?void 0:d.id,d==null?void 0:d.status,a.loadItems,a.loadShippingRules,n]),{showBatchModal:n,setShowBatchModal:h,batchLoading:te,batchPhase:o,setBatchPhase:x,batchFile:g,setBatchFile:B,batchImagesZip:u,setBatchImagesZip:D,batchCategoryKeyword:k,setBatchCategoryKeyword:z,batchCategoryLoading:ee,batchFallbackCategory:T,setBatchFallbackCategory:K,batchPreview:f,setBatchPreview:R,batchDetail:d,setBatchDetail:w,recentBatch:C,setRecentBatch:F,batchLocations:O,batchLocation:M,setBatchLocations:Z,setBatchLocation:G,openBatchModal:j,handleRecommendBatchCategory:U,openRecentBatchResult:p,handlePreviewBatch:P,handleStartBatch:r,handleCancelBatch:_,abandonBatchPreview:V,closeBatchModal:se,handleRetryBatchFailed:E}},Dt=({phase:a})=>{const n=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:n.map(([h,o])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${a===h?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:o},h))})},Ut=a=>{const n=String(a||"").trim();return n?/^[¥¥]/.test(n)?n:`¥${n}`:"-"},Kt=({onConfigureDelivery:a})=>{const[n,h]=l.useState([]),[o,x]=l.useState([]),[g,B]=l.useState([]),[u,D]=l.useState(""),[k,z]=l.useState(""),[ee,Y]=l.useState(!1),[T,K]=l.useState(!1),[f,R]=l.useState(!1),[d,w]=l.useState(!1),[C,F]=l.useState(!1),[O,Z]=l.useState(!1),[M,G]=l.useState([]),[te,b]=l.useState(null),[S,J]=l.useState(null),[j,U]=l.useState({}),[p,P]=l.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[r,_]=l.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[V,se]=l.useState([]),E=l.useCallback(async()=>{const t=await _e();h(t)},[]),ae=l.useCallback(async()=>{x(await ke())},[]),i=$t({selectedAccount:u,loadItems:E,loadShippingRules:ae}),{showBatchModal:m,setShowBatchModal:I,batchLoading:N,batchPhase:A,batchFile:oe,setBatchFile:Me,batchImagesZip:pe,setBatchImagesZip:Ee,batchCategoryKeyword:ge,setBatchCategoryKeyword:$e,batchCategoryLoading:be,batchFallbackCategory:le,setBatchFallbackCategory:De,batchPreview:$,batchDetail:v,recentBatch:ie,setRecentBatch:Ue,batchLocations:re,batchLocation:qe,setBatchLocations:ye,setBatchLocation:xe,openBatchModal:ze,handleRecommendBatchCategory:fe,openRecentBatchResult:Te,handlePreviewBatch:Ke,handleStartBatch:Oe,handleCancelBatch:Ze,abandonBatchPreview:Ge,closeBatchModal:Je,handleRetryBatchFailed:Ve}=i;l.useEffect(()=>{if(!C||r.images.length===0){se([]);return}const t=r.images.map((s,c)=>({key:s.name+c,url:URL.createObjectURL(s)}));return se(t),(()=>{t.forEach(s=>URL.revokeObjectURL(s.url))})},[C,r.images]),l.useEffect(()=>{Promise.all([ht(),_e(),ke(),Fe(20)]).then(([t,s,c,y])=>{B(t),h(s),x(c);const q=y.find(L=>["running","canceling"].includes(L.status))||y.find(L=>L.status!=="preview");Ue(q||null)}).catch(t=>console.error("加载商品配置失败:",t))},[]);const We=async()=>{if(!u)return alert("请先选择账号");Y(!0);try{const t=await ut(u);await E(),alert((t==null?void 0:t.message)||"商品同步完成")}catch(t){console.error("同步商品失败:",t),alert((t==null?void 0:t.message)||"同步失败,请重试")}finally{Y(!1)}},Ye=t=>{J(t),U({...t}),R(!0)},Xe=async()=>{if(S)try{await gt(S.cookie_id,S.item_id,{item_title:j.item_title||"",item_description:j.item_description||"",item_category:j.item_category||"",item_price:j.item_price||"",item_detail:j.item_detail||S.item_detail||""}),await E(),await ae(),R(!1),J(null)}catch(t){console.error("更新商品失败:",t),alert("更新失败,请重试")}},He=async t=>{if(confirm(`确认删除商品"${t.item_title}"吗?`))try{await pt(t.cookie_id,t.item_id),h(s=>s.filter(c=>!(c.cookie_id===t.cookie_id&&c.item_id===t.item_id)))}catch(s){console.error("删除商品失败:",s),alert("删除失败,请重试")}},Qe=async()=>{try{if(!p.cookie_id||!p.item_id){alert("请选择账号并填写商品ID");return}await bt(p.cookie_id,{item_id:p.item_id,item_title:p.item_title,item_price:p.item_price,item_detail:p.item_image?JSON.stringify({item_image:p.item_image}):""}),await E(),w(!1),P({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(t){console.error("添加商品失败:",t),alert("添加失败,请重试")}},et=async()=>{if(!r.cookie_id)return alert("请选择发布账号");if(!r.title.trim())return alert("请填写商品标题");if(!r.price.trim())return alert("请填写商品价格");if(!r.quantity||Number(r.quantity)<=0)return alert("库存数量必须大于 0");if(r.images.length===0)return alert("至少上传 1 张商品图片");if(r.postage_mode==="fixed"&&!r.postage.trim())return alert("请填写一口价邮费");K(!0);try{const t=await yt({...r,location:te||void 0});if(await E(),F(!1),_({cookie_id:u||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),G([]),b(null),t!=null&&t.item_id){const s={id:t.item_id,cookie_id:r.cookie_id,item_id:t.item_id,item_title:t.item_title||r.title,item_price:t.item_price||r.price,item_image:t.item_image};a(s),alert("商品发布成功,ID: "+t.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(t){console.error("发布商品失败:",t);const s=t==null?void 0:t.payload;if((s==null?void 0:s.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((t==null?void 0:t.message)||"发布失败,请重试")}finally{K(!1)}},tt=()=>{const c=[["账号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(it=>it.map(rt=>`"${String(rt).replace(/"/g,'""')}"`).join(",")).join(` +import{r as l,j as e,b as ne}from"./react-vendor-C_od1ZSF.js";import{Q as Fe,R as W,S as nt,T as ct,U as dt,V as ot,W as xt,X as mt,a as _e,Y as ke,h as ht,Z as ut,_ as pt,$ as gt,a0 as bt,a1 as yt}from"./index-CsLZwESi.js";import{a3 as ft,i as Ce,R as me,N as Ie,a4 as he,a5 as ce,V as jt,F as Nt,B as vt,a6 as Se,a7 as wt,a8 as _t,A as kt,S as Ct,X as H,r as It,a9 as Be,I as Pe}from"./icons-vendor-ThcsWkZG.js";const Ae="ydisks-amap-js-api",St="c9b68d4ce9a2a97f22a4a439404488ca";let Q=null;const Bt=()=>St,Pt=()=>window.AMap?Promise.resolve(window.AMap):Q||(Q=new Promise((a,n)=>{const h=document.getElementById(Ae),o=h||document.createElement("script"),x=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(B)},g=()=>{window.AMap?(x(),a(window.AMap)):(x(),n(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},B=window.setTimeout(()=>{x(),n(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=g,o.id=Ae,o.async=!0,o.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Bt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,o.onerror=()=>{x(),n(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},h||document.head.appendChild(o)}).catch(a=>{throw Q=null,a}),Q),de=a=>Number.isFinite(a)&&a!==0,At=a=>{var x,g;const n=Number((x=a.location)==null?void 0:x.lng),h=Number((g=a.location)==null?void 0:g.lat),o={area:String(a.adname||"").trim(),city:String(a.cityname||"").trim(),division_id:String(a.adcode||"").trim(),longitude:n,latitude:h,poi_id:String(a.id||"").trim(),poi_name:String(a.name||"").trim(),province:String(a.pname||"").trim()};return!o.division_id||!o.province||!o.city||!o.poi_id||!o.poi_name||!de(n)||!de(h)||n<-180||n>180||h<-90||h>90?null:o},Lt=async(a,n)=>{if(!de(a)||!de(n)||a<-180||a>180||n<-90||n>90)throw new Error("经纬度无效");const h=await Pt();return new Promise((o,x)=>{new h.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[a,n],1e3,(B,u)=>{var k;if(B!=="complete"){if(B==="no_data"){o([]);return}x(new Error("高德地图附近地址查询失败,请稍后重试"));return}const D=(((k=u==null?void 0:u.poiList)==null?void 0:k.pois)||[]).map(At).filter(z=>z!==null);o(D)})})},Rt=a=>a.find(n=>n.status==="running"||n.status==="canceling"),ue=a=>a==="running"||a==="canceling",Ft=a=>!!(a!=null&&a.preview_id&&Number(a.valid||0)>0),Mt=a=>!!(a!=null&&a.id&&Number(a.retryable||0)>0&&!ue(a.status)),Et=(a,n)=>a===n,Le=a=>{switch(a){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 a||"-"}},Re=a=>{switch(a){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"}},$t=a=>{const[n,h]=l.useState(!1),[o,x]=l.useState("upload"),[g,B]=l.useState(null),[u,D]=l.useState(null),[k,z]=l.useState(""),[ee,Y]=l.useState(!1),[T,K]=l.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[f,R]=l.useState(null),[d,w]=l.useState(null),[C,F]=l.useState(null),[O,Z]=l.useState([]),[M,G]=l.useState(null),[te,b]=l.useState(!1),S=l.useRef(!1),J=l.useRef(0),j=l.useCallback(async()=>{x("upload"),R(null),w(null),B(null),D(null),z(""),K({catId:"",catName:"",channelCatId:"",tbCatId:""}),Z([]),G(null),h(!0),b(!0);try{const i=await Fe(20),m=Rt(i);if(m!=null&&m.id){const I=await W(m.id);F(I),w(I),x(["running","canceling"].includes(I.status)?"running":"done")}}catch(i){console.error("恢复最近批量铺货任务失败:",i)}finally{b(!1)}},[]),U=l.useCallback(async()=>{const i=k.trim();if(!a.selectedAccount){alert("请先选择默认发布账号");return}if(!i){alert("请输入类目关键词");return}Y(!0);try{const I=(await nt(a.selectedAccount,i)).category;K({catId:I.cat_id,catName:I.cat_name,channelCatId:I.channel_cat_id,tbCatId:I.tb_cat_id||""})}catch(m){console.error("获取推荐类目失败:",m),alert((m==null?void 0:m.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{Y(!1)}},[k,a.selectedAccount]),p=l.useCallback(async()=>{if(C!=null&&C.id){b(!0),h(!0);try{const i=await W(C.id);w(i),x(["running","canceling"].includes(i.status)?"running":"done")}catch(i){console.error("加载最近批量铺货结果失败:",i)}finally{b(!1)}}},[C==null?void 0:C.id]),P=l.useCallback(async()=>{if(!g){alert("请先上传商品表格");return}if(!a.selectedAccount){alert("请先选择默认发布账号");return}b(!0);try{const i=await ct({file:g,imagesZip:u,defaultCookieId:a.selectedAccount,fallbackCategory:T,location:M||void 0});R(i),w(null),x("preview")}catch(i){console.error("批量铺货预检失败:",i),alert((i==null?void 0:i.message)||"预检失败,请检查表格和图片 zip")}finally{b(!1)}},[T,g,u,M,a.selectedAccount]),r=l.useCallback(async()=>{if(f!=null&&f.preview_id){if(!Ft(f)){alert("没有可发布的商品行");return}b(!0);try{const i=await dt(f.preview_id),m=await W(i.batch_id||f.preview_id);w(m),F(m),x(m.status==="running"?"running":"done")}catch(i){console.error("启动批量铺货失败:",i),alert((i==null?void 0:i.message)||"启动发布任务失败")}finally{b(!1)}}},[f]),_=l.useCallback(async()=>{if(d!=null&&d.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){b(!0);try{const i=await ot(d.id),m=await W(d.id);w(m),x((i==null?void 0:i.status)==="canceling"||m.status==="canceling"?"running":"done")}catch(i){alert((i==null?void 0:i.message)||"取消失败")}finally{b(!1)}}},[d==null?void 0:d.id]),V=l.useCallback(async()=>{const i=f==null?void 0:f.preview_id;if(i&&o==="preview")try{await xt(i)}catch(m){console.error("清理批量铺货预检失败:",m)}R(null),x("upload")},[o,f==null?void 0:f.preview_id]),se=l.useCallback(async()=>{await V(),h(!1)},[V]),E=l.useCallback(async()=>{if(!(!(d!=null&&d.id)||!Mt(d))){b(!0);try{await mt(d.id),w(await W(d.id)),x("running")}catch(i){alert((i==null?void 0:i.message)||"重试失败")}finally{b(!1)}}},[d]);return l.useEffect(()=>{if(!n||!(d!=null&&d.id)||!ue(d.status))return;const i=++J.current,m=async()=>{if(!S.current){S.current=!0;try{const N=await W(d.id);if(!Et(i,J.current))return;w(N),F(N),ue(N.status)||(x("done"),await Promise.all([a.loadItems(),a.loadShippingRules()]))}catch(N){console.error("刷新批量铺货进度失败:",N)}finally{S.current=!1}}},I=window.setInterval(()=>void m(),3e3);return(()=>{window.clearInterval(I),J.current+=1})},[d==null?void 0:d.id,d==null?void 0:d.status,a.loadItems,a.loadShippingRules,n]),{showBatchModal:n,setShowBatchModal:h,batchLoading:te,batchPhase:o,setBatchPhase:x,batchFile:g,setBatchFile:B,batchImagesZip:u,setBatchImagesZip:D,batchCategoryKeyword:k,setBatchCategoryKeyword:z,batchCategoryLoading:ee,batchFallbackCategory:T,setBatchFallbackCategory:K,batchPreview:f,setBatchPreview:R,batchDetail:d,setBatchDetail:w,recentBatch:C,setRecentBatch:F,batchLocations:O,batchLocation:M,setBatchLocations:Z,setBatchLocation:G,openBatchModal:j,handleRecommendBatchCategory:U,openRecentBatchResult:p,handlePreviewBatch:P,handleStartBatch:r,handleCancelBatch:_,abandonBatchPreview:V,closeBatchModal:se,handleRetryBatchFailed:E}},Dt=({phase:a})=>{const n=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:n.map(([h,o])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${a===h?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:o},h))})},Ut=a=>{const n=String(a||"").trim();return n?/^[¥¥]/.test(n)?n:`¥${n}`:"-"},Kt=({onConfigureDelivery:a})=>{const[n,h]=l.useState([]),[o,x]=l.useState([]),[g,B]=l.useState([]),[u,D]=l.useState(""),[k,z]=l.useState(""),[ee,Y]=l.useState(!1),[T,K]=l.useState(!1),[f,R]=l.useState(!1),[d,w]=l.useState(!1),[C,F]=l.useState(!1),[O,Z]=l.useState(!1),[M,G]=l.useState([]),[te,b]=l.useState(null),[S,J]=l.useState(null),[j,U]=l.useState({}),[p,P]=l.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[r,_]=l.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[V,se]=l.useState([]),E=l.useCallback(async()=>{const t=await _e();h(t)},[]),ae=l.useCallback(async()=>{x(await ke())},[]),i=$t({selectedAccount:u,loadItems:E,loadShippingRules:ae}),{showBatchModal:m,setShowBatchModal:I,batchLoading:N,batchPhase:A,batchFile:oe,setBatchFile:Me,batchImagesZip:pe,setBatchImagesZip:Ee,batchCategoryKeyword:ge,setBatchCategoryKeyword:$e,batchCategoryLoading:be,batchFallbackCategory:le,setBatchFallbackCategory:De,batchPreview:$,batchDetail:v,recentBatch:ie,setRecentBatch:Ue,batchLocations:re,batchLocation:qe,setBatchLocations:ye,setBatchLocation:xe,openBatchModal:ze,handleRecommendBatchCategory:fe,openRecentBatchResult:Te,handlePreviewBatch:Ke,handleStartBatch:Oe,handleCancelBatch:Ze,abandonBatchPreview:Ge,closeBatchModal:Je,handleRetryBatchFailed:Ve}=i;l.useEffect(()=>{if(!C||r.images.length===0){se([]);return}const t=r.images.map((s,c)=>({key:s.name+c,url:URL.createObjectURL(s)}));return se(t),(()=>{t.forEach(s=>URL.revokeObjectURL(s.url))})},[C,r.images]),l.useEffect(()=>{Promise.all([ht(),_e(),ke(),Fe(20)]).then(([t,s,c,y])=>{B(t),h(s),x(c);const q=y.find(L=>["running","canceling"].includes(L.status))||y.find(L=>L.status!=="preview");Ue(q||null)}).catch(t=>console.error("加载商品配置失败:",t))},[]);const We=async()=>{if(!u)return alert("请先选择账号");Y(!0);try{const t=await ut(u);await E(),alert((t==null?void 0:t.message)||"商品同步完成")}catch(t){console.error("同步商品失败:",t),alert((t==null?void 0:t.message)||"同步失败,请重试")}finally{Y(!1)}},Ye=t=>{J(t),U({...t}),R(!0)},Xe=async()=>{if(S)try{await gt(S.cookie_id,S.item_id,{item_title:j.item_title||"",item_description:j.item_description||"",item_category:j.item_category||"",item_price:j.item_price||"",item_detail:j.item_detail||S.item_detail||""}),await E(),await ae(),R(!1),J(null)}catch(t){console.error("更新商品失败:",t),alert("更新失败,请重试")}},He=async t=>{if(confirm(`确认删除商品"${t.item_title}"吗?`))try{await pt(t.cookie_id,t.item_id),h(s=>s.filter(c=>!(c.cookie_id===t.cookie_id&&c.item_id===t.item_id)))}catch(s){console.error("删除商品失败:",s),alert("删除失败,请重试")}},Qe=async()=>{try{if(!p.cookie_id||!p.item_id){alert("请选择账号并填写商品ID");return}await bt(p.cookie_id,{item_id:p.item_id,item_title:p.item_title,item_price:p.item_price,item_detail:p.item_image?JSON.stringify({item_image:p.item_image}):""}),await E(),w(!1),P({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(t){console.error("添加商品失败:",t),alert("添加失败,请重试")}},et=async()=>{if(!r.cookie_id)return alert("请选择发布账号");if(!r.title.trim())return alert("请填写商品标题");if(!r.price.trim())return alert("请填写商品价格");if(!r.quantity||Number(r.quantity)<=0)return alert("库存数量必须大于 0");if(r.images.length===0)return alert("至少上传 1 张商品图片");if(r.postage_mode==="fixed"&&!r.postage.trim())return alert("请填写一口价邮费");K(!0);try{const t=await yt({...r,location:te||void 0});if(await E(),F(!1),_({cookie_id:u||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),G([]),b(null),t!=null&&t.item_id){const s={id:t.item_id,cookie_id:r.cookie_id,item_id:t.item_id,item_title:t.item_title||r.title,item_price:t.item_price||r.price,item_image:t.item_image};a(s),alert("商品发布成功,ID: "+t.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(t){console.error("发布商品失败:",t);const s=t==null?void 0:t.payload;if((s==null?void 0:s.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((t==null?void 0:t.message)||"发布失败,请重试")}finally{K(!1)}},tt=()=>{const c=[["账号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(it=>it.map(rt=>`"${String(rt).replace(/"/g,'""')}"`).join(",")).join(` `),y=new Blob(["\uFEFF"+c],{type:"text/csv;charset=utf-8"}),q=URL.createObjectURL(y),L=document.createElement("a");L.href=q,L.download="批量铺货模板.csv",document.body.appendChild(L),L.click(),L.remove(),URL.revokeObjectURL(q)},st=()=>{P(t=>({...t,cookie_id:u||t.cookie_id})),w(!0)},at=()=>{_(t=>({...t,cookie_id:u||t.cookie_id})),F(!0)},je=async t=>{if(!(t?u:r.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");Z(!0),navigator.geolocation.getCurrentPosition(async c=>{try{const y=await Lt(c.coords.longitude,c.coords.latitude);if(!y.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");t?(ye(y),xe(y[0])):(G(y),b(y[0]))}catch(y){alert((y==null?void 0:y.message)||"获取发货地失败")}finally{Z(!1)}},c=>{Z(!1),alert(c.code===c.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},lt=t=>o.filter(s=>s.cookie_id===t.cookie_id&&s.item_id===t.item_id).length>0?o.filter(s=>s.cookie_id===t.cookie_id&&s.item_id===t.item_id):o.filter(s=>s.cookie_id===t.cookie_id&&!s.item_id),Ne=l.useMemo(()=>new Map(g.map(t=>[t.id,t])),[g]),ve=l.useMemo(()=>k?n.filter(t=>t.cookie_id===k):n,[k,n]),X=t=>{const s=Ne.get(t),c=(s==null?void 0:s.remark)||(s==null?void 0:s.nickname);return c?`${c} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},we=t=>{const s=Ne.get(t);return(s==null?void 0:s.remark)||(s==null?void 0:s.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(ft,{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:k,onChange:(t=>z(t.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(t=>e.jsx("option",{value:t.id,children:X(t.id)},t.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(Ce,{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:u,onChange:(t=>D(t.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:X(t.id)},t.id))]})]})]}),e.jsxs("button",{onClick:We,disabled:ee||!u,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(me,{className:`w-4 h-4 ${ee?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:st,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(Ie,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:at,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(he,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void ze()),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(ce,{className:"w-4 h-4"}),ie&&["running","canceling"].includes(ie.status)?"继续批量任务":"批量铺货"]}),ie&&!["running","canceling"].includes(ie.status)&&e.jsx("button",{onClick:(()=>void Te()),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:[ve.map(t=>{const s=lt(t),c=s.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:(()=>Ye(t)),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(jt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:(()=>He(t)),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(Nt,{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:[t.item_image?e.jsx("img",{src:t.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(vt,{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:Ut(t.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:t.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:we(t.cookie_id),children:[e.jsx(Ce,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:we(t.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: ",t.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${c?"text-emerald-600":"text-amber-600"}`,children:[c?e.jsx(Se,{className:"w-3 h-3"}):e.jsx(wt,{className:"w-3 h-3"}),c?`${s.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:(()=>a(t)),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${c?"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(_t,{className:"w-3.5 h-3.5"}),c?"查看发货规则":"关联发货规则"]}),e.jsx(kt,{className:"w-3.5 h-3.5"})]})})]},`${t.cookie_id}-${t.item_id}`)}),ve.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(Ct,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),k?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),f&&S&&ne.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: ",S.item_id]})]}),e.jsx("button",{onClick:(()=>R(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(H,{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:j.item_title||"",onChange:(t=>U({...j,item_title:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:j.item_price||"",onChange:(t=>U({...j,item_price:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:j.item_category||"",onChange:(t=>U({...j,item_category:t.target.value}))}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:j.item_description||"",onChange:(t=>U({...j,item_description:t.target.value}))})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:Xe,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(It,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),d&&ne.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:(()=>w(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(H,{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:p.cookie_id,onChange:(t=>P({...p,cookie_id:t.target.value})),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:X(t.id)},t.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:p.item_id,onChange:(t=>P({...p,item_id:t.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:p.item_price,onChange:(t=>P({...p,item_price:t.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:p.item_title,onChange:(t=>P({...p,item_title:t.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:p.item_image,onChange:(t=>P({...p,item_image:t.target.value}))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:Qe,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(Ie,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),C&&ne.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:(()=>F(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(H,{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:r.cookie_id,onChange:(t=>{_({...r,cookie_id:t.target.value}),G([]),b(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:X(t.id)},t.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:r.title,onChange:(t=>_({...r,title:t.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:r.quantity,onChange:(t=>_({...r,quantity:t.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:r.description,onChange:(t=>_({...r,description:t.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:r.price,onChange:(t=>_({...r,price:t.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:r.original_price,onChange:(t=>_({...r,original_price:t.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:r.postage_mode,onChange:(t=>_({...r,postage_mode:t.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:"无需邮寄"})]})]})]}),r.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:r.postage,onChange:(t=>_({...r,postage:t.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:O||!r.cookie_id,onClick:(()=>void je(!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(Be,{className:"h-4 w-4"}),O?"定位中...":"获取当前位置"]})]}),M.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,M.indexOf(te))),onChange:(t=>b(M[Number(t.target.value)]||null)),children:M.map((t,s)=>e.jsx("option",{value:String(s),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${s}`))})]}),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(ce,{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:r.images.length?"已选择 "+r.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:(t=>_({...r,images:Array.from(t.target.files||[]).slice(0,9)}))})]}),V.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:V.map(t=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:t.url,alt:"",className:"w-full h-full object-cover"})},t.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:T,onClick:et,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(he,{className:"w-4 h-4"}),T?"正在发布...":"发布到闲鱼"]})})]})}),document.body),m&&ne.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 Je()),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(H,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx(Dt,{phase:A}),A==="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:tt,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:u,onChange:(t=>{D(t.target.value),ye([]),xe(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:X(t.id)},t.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(Pe,{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:ge,onChange:(t=>$e(t.target.value)),onKeyDown:(t=>{t.key==="Enter"&&(t.preventDefault(),fe())})})]}),e.jsxs("button",{type:"button",disabled:!u||!ge.trim()||be,onClick:(()=>void fe()),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(Pe,{className:"h-4 w-4"}),be?"匹配中...":"获取类目"]})]}),le.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(Se,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:le.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",le.catId," · 频道 ",le.channelCatId]})]}),e.jsx("button",{type:"button",title:"清除默认类目",onClick:(()=>De({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(H,{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:O||!u,onClick:(()=>void je(!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(Be,{className:"h-4 w-4"}),O?"定位中...":"获取当前位置"]})]}),re.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,re.indexOf(qe))),onChange:(t=>xe(re[Number(t.target.value)]||null)),children:re.map((t,s)=>e.jsx("option",{value:String(s),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${s}`))})]}),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(ce,{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:oe?oe.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:(t=>{var s;return Me(((s=t.target.files)==null?void 0:s[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(ce,{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:pe?pe.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:(t=>{var s;return Ee(((s=t.target.files)==null?void 0:s[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(([t,s,c])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:t}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${s==="每个商品都要填"?"text-red-600":s==="可以留空"?"text-gray-500":"text-amber-700"}`,children:s}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:c})]},t))})]})})]})]}),A==="preview"&&$&&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:$.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:$.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:$.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:$.rows.map(t=>{var s,c,y,q;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.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 ${t.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:t.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:t.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",t.price||"-"," / ",t.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:((s=t.category)==null?void 0:s.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((c=t.category)==null?void 0:c.cat_id)||"失败后使用电子资料"})]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((y=t.images)==null?void 0:y.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((q=t.errors)==null?void 0:q.join(";"))||"-"})]},t.row_no)})})]})})]}),(A==="running"||A==="done")&&v&&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 ${Re(v.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:Le(v.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:v.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"成功"}),e.jsx("div",{className:"text-xl font-extrabold text-emerald-700 mt-1",children:v.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:v.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:v.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:v.rows.map(t=>{var s,c;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.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 ${Re(t.status)}`,children:Le(t.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:t.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:((s=t.category)==null?void 0:s.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((c=t.category)==null?void 0:c.cat_id)||"失败后使用电子资料"})]}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:t.item_url?e.jsx("a",{href:t.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:t.item_id}):t.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:t.error_message||"-"})]},t.id)})})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[A==="upload"&&e.jsxs("button",{disabled:N||!oe||!u,onClick:Ke,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(me,{className:`w-4 h-4 ${N?"animate-spin":""}`}),N?"正在预检...":"开始预检"]}),A==="preview"&&$&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:N,onClick:(()=>void Ge()),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:N||$.valid<=0,onClick:Oe,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(he,{className:"w-4 h-4"}),N?"启动中...":`确认发布 ${$.valid} 个商品`]})]}),(A==="running"||A==="done")&&v&&e.jsxs("div",{className:"flex gap-3 w-full",children:[v.status==="running"?e.jsx("button",{disabled:N,onClick:Ze,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):v.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(`/api/v1/items/publish-batches/${v.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:"下载结果"}),v.retryable>0&&!["running","canceling"].includes(v.status)&&e.jsxs("button",{disabled:N,onClick:Ve,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(me,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(v.status)&&e.jsx("button",{onClick:(()=>{I(!1),E(),ae()}),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)]})};export{Kt as default}; diff --git a/internal/webui/static/assets/Notifications-BlIacKXE.js b/internal/webui/static/assets/Notifications-Cu3hjXgW.js similarity index 99% rename from internal/webui/static/assets/Notifications-BlIacKXE.js rename to internal/webui/static/assets/Notifications-Cu3hjXgW.js index ce9232c..fe2b9f3 100644 --- a/internal/webui/static/assets/Notifications-BlIacKXE.js +++ b/internal/webui/static/assets/Notifications-Cu3hjXgW.js @@ -1 +1 @@ -import{j as e,b as be,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as fe,x as G,a as W,f as I,y as ye,F as je,s as J,X as te,u as ae,v as le,r as Ne,R as _e,N as ve}from"./icons-vendor-ThcsWkZG.js";import{n as we,a3 as ke,al as Y,am as Ce,an as Se,ao as Te,a5 as Pe}from"./index-CFJ5pUjO.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],Q=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},re=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?Q(s.use_custom_smtp,!1):a}},ne=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=Q(a.smtp_use_tls,!0),a.smtp_use_ssl=Q(a.smtp_use_ssl,!1),a},oe=s=>{const t=re(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},$={bark:{label:"Bark",icon:W,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:G,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:G,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:G,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:fe,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:se,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:ee,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},ce=[{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:"后台任务或系统级异常"}],Z=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Ee=s=>!s||s.length===0?"全部事件":s.map(t=>{var a;return((a=ce.find(n=>n.value===t))==null?void 0:a.label)||t}).join("、"),Me=(s,t)=>{const a=s.type==="email"?re({...s.config||{}}):null,n=a?a.use_custom_smtp===!0?ne(a,t):a:{...s.config||{}};return{name:s.name,type:s.type,enabled:s.enabled,config:n,event_types:s.event_types||[]}},qe=s=>{const a=$[s.type].fields.find(n=>n.required&&!String(s.config[n.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!s.name.trim())return"请填写渠道名称";if(s.type==="email"){const n=oe(s.config);if(n.use_custom_smtp){const w=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([g])=>!String(n[g]||"").trim());if(w)return`请填写 ${w[1]}`}}return""},Re=s=>({name:s.name.trim(),type:s.type,config:s.type==="email"?oe(s.config):s.config,event_types:s.event_types,enabled:s.enabled}),h=(s,t)=>s===t,A=(s,t)=>s instanceof Error&&s.message?s.message:t,Le=({channels:s,testingId:t,onEdit:a,onDelete:n,onToggleEnabled:b,onTest:w})=>{const g=r=>s.find(o=>o.id===r.currentTarget.dataset.channelId)||null,N=r=>{const o=g(r);o&&b(o)},C=r=>{const o=g(r);o&&w(o)},E=r=>{const o=g(r);o&&a(o)},j=r=>{const o=g(r);o&&n(o)},M=r=>{const o=$[r.type]||$.webhook,P=o.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(P,{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:r.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:o.label}),!r.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:o.fields.map(x=>{var k;return(k=r.config)==null?void 0:k[x.key]}).filter(Boolean).map((x,k)=>e.jsx("span",{className:"mr-3",children:String(x).length>40?`${String(x).slice(0,40)}…`:String(x)},k))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Ee(r.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":r.id,onClick:N,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${r.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:r.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":r.id,onClick:C,disabled:t===r.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:[t===r.id?e.jsx(I,{className:"w-3 h-3 animate-spin"}):e.jsx(se,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":r.id,onClick:E,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(ye,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":r.id,onClick:j,className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(je,{className:"w-4 h-4"})})]})]},r.id)};return s.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(W,{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:s.map(M)})},Be=({selectedEvents:s,onToggleEvent:t})=>{const a=n=>{const b=n.currentTarget.dataset.event;b&&t(b)};return 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:ce.map(n=>{const b=s.includes(n.value);return e.jsxs("button",{type:"button","data-event":n.value,onClick:a,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(J,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${b?"text-brand":"text-gray-800"}`,children:n.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:n.description})]},n.value)})})]})},$e=({showModal:s,editing:t,form:a,setForm:n,smtp:b,showChannelSmtpPassword:w,setShowChannelSmtpPassword:g,saving:N,onClose:C,onSave:E})=>{const j=$[a.type],M=l=>n(m=>({...m,name:l.target.value})),r=l=>{const m=l.currentTarget.dataset.type;m&&n(_=>({..._,type:m,config:{}}))},o=l=>{const m=l.currentTarget.dataset.field;m&&n(_=>({..._,config:{..._.config,[m]:l.target.value}}))},P=()=>n(l=>({...l,config:l.config.use_custom_smtp===!0?{...l.config,use_custom_smtp:!1}:ne(l.config,b)})),x=l=>n(m=>({...m,config:{...m.config,smtp_use_tls:l.target.checked,smtp_use_ssl:l.target.checked?!1:m.config.smtp_use_ssl}})),k=l=>n(m=>({...m,config:{...m.config,smtp_use_ssl:l.target.checked,smtp_use_tls:l.target.checked?!1:m.config.smtp_use_tls}})),U=l=>n(m=>({...m,event_types:m.event_types.includes(l)?m.event_types.filter(_=>_!==l):[...m.event_types,l]})),D=()=>n(l=>({...l,enabled:!l.enabled})),X=()=>g(l=>!l),z=(l,m)=>e.jsx("li",{children:l},m);return s?be.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:t?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:C,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(te,{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:a.name,onChange:M,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($).map(l=>{const m=$[l],_=m.icon,q=a.type===l;return e.jsxs("button",{"data-type":l,type:"button",onClick:r,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(_,{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:m.label})]},l)})})]}),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(W,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",j.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:j.guide.steps.map(z)}),j.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:j.guide.urlFormat})]}),j.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",j.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:j.fields.map(l=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[l.label,l.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":l.key,type:l.type==="password"?"password":l.type==="number"?"number":"text",value:String(a.config[l.key]||""),onChange:o,placeholder:l.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),l.help&&e.jsx("p",{className:"text-xs text-gray-500",children:l.help})]},l.key))}),a.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:a.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:P,className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${a.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 ${a.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),a.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",{"data-field":"smtp_server",type:"text",value:String(a.config.smtp_server||""),onChange:o,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",{"data-field":"smtp_port",type:"number",value:String(a.config.smtp_port||587),onChange:o,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",{"data-field":"smtp_user",type:"email",value:String(a.config.smtp_user||""),onChange:o,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",{"data-field":"smtp_password",type:w?"text":"password",value:String(a.config.smtp_password||""),onChange:o,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:X,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:w?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(le,{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",{"data-field":"smtp_from_name",type:"text",value:String(a.config.smtp_from_name||""),onChange:o,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",{"data-field":"smtp_from_address",type:"email",value:String(a.config.smtp_from_address||""),onChange:o,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:a.config.smtp_use_tls!==!1,onChange:x}),"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:a.config.smtp_use_ssl===!0,onChange:k}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Be,{selectedEvents:a.event_types,onToggleEvent:U}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:D,className:`relative w-11 h-6 rounded-full transition-colors ${a.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 ${a.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:C,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:E,disabled:N,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[N?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(J,{className:"w-4 h-4"}),N?"保存中...":"保存"]})]})]})}),document.body):null},Fe=({smtp:s,setSmtp:t,smtpSaving:a,showPassword:n,setShowPassword:b,onSave:w})=>{const g=r=>{const o=r.currentTarget.dataset.field;o&&t(P=>({...P,[o]:r.target.value}))},N=r=>{t(o=>({...o,smtp_port:parseInt(r.target.value,10)||587}))},C=r=>{t(o=>({...o,smtp_use_tls:r.target.checked,smtp_use_ssl:r.target.checked?!1:o.smtp_use_ssl}))},E=r=>{t(o=>({...o,smtp_use_ssl:r.target.checked,smtp_use_tls:r.target.checked?!1:o.smtp_use_tls}))},j=r=>{t(o=>({...o,smtp_password:r.target.value}))},M=()=>b(r=>!r);return 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(ee,{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",{"data-field":"smtp_server",type:"text",value:s.smtp_server||"",onChange:g,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:s.smtp_port||587,onChange:N,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",{"data-field":"smtp_user",type:"email",value:s.smtp_user||"",onChange:g,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:n?"text":"password",value:s.smtp_password||"",onChange:j,placeholder:s.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:M,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:n?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(le,{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",{"data-field":"smtp_from_name",type:"text",value:s.smtp_from_name||"",onChange:g,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",{"data-field":"smtp_from_address",type:"email",value:s.smtp_from_address||s.smtp_user||"",onChange:g,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_tls!==!1,onChange:C}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_ssl===!0,onChange:E}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:w,disabled:a,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(Ne,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},Ae=s=>{const[t,a]=d.useState([]),[n,b]=d.useState(!0),[w,g]=d.useState(!1),[N,C]=d.useState(null),[E,j]=d.useState(!1),[M,r]=d.useState(""),[o,P]=d.useState(null),[x,k]=d.useState({}),[U,D]=d.useState(!1),[X,z]=d.useState(!1),[l,m]=d.useState(!1),[_,q]=d.useState(Z),F=d.useRef(0),K=d.useRef(null),S=d.useRef(0),L=d.useRef(null),f=d.useRef(0),T=d.useRef(null),B=d.useRef(null),y=d.useCallback((c,i)=>{P({type:c,text:i}),B.current!==null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{B.current=null,P(null)},3e3)},[]),R=d.useCallback(async()=>{var p;const c=++F.current;(p=K.current)==null||p.abort();const i=new AbortController;K.current=i,b(!0);try{const u=await we({signal:i.signal});if(!h(c,F.current))return;a(u.data||[])}catch(u){h(c,F.current)&&!i.signal.aborted&&console.error("加载通知渠道失败",u)}finally{h(c,F.current)&&b(!1)}},[]),V=d.useCallback(async()=>{var p;const c=++S.current;(p=L.current)==null||p.abort();const i=new AbortController;L.current=i;try{const u=await ke({signal:i.signal});h(c,S.current)&&k(u||{})}catch(u){h(c,S.current)&&!i.signal.aborted&&console.error("加载 SMTP 配置失败",u)}},[]);d.useEffect(()=>{var c;return R(),s?V():(S.current+=1,(c=L.current)==null||c.abort(),k({})),(()=>{var i,p;F.current+=1,(i=K.current)==null||i.abort(),S.current+=1,(p=L.current)==null||p.abort()})},[s,R,V]),d.useEffect(()=>(()=>{B.current!==null&&window.clearTimeout(B.current)}),[]);const ie=d.useCallback(()=>{C(null),q(Z()),m(!1),g(!0)},[]),de=d.useCallback(c=>{C(c),q(Me(c,x)),m(!1),g(!0)},[x]),me=d.useCallback(()=>{var c;f.current+=1,(c=T.current)==null||c.abort(),j(!1),g(!1)},[]),pe=d.useCallback(async()=>{var u;const c=qe(_);if(c){y("error",c);return}const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p,j(!0);try{const v=Re(_);if(N?await Y(N.id,v,{signal:p.signal}):await Ce(v,{signal:p.signal}),!h(i,f.current)||(g(!1),await R(),!h(i,f.current)))return;y("success",N?"已更新":"已创建")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"保存失败"))}finally{h(i,f.current)&&j(!1)}},[N,_,R,y]),ue=d.useCallback(async c=>{var u;if(!confirm(`确认删除渠道「${c.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{if(await Se(c.id,{signal:p.signal}),!h(i,f.current)||(await R(),!h(i,f.current)))return;y("success","已删除")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"删除失败"))}},[R,y]),xe=d.useCallback(async c=>{var u;const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{if(await Y(c.id,{enabled:!c.enabled},{signal:p.signal}),!h(i,f.current))return;a(v=>v.map(O=>O.id===c.id?{...O,enabled:!O.enabled}:O))}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"切换失败"))}},[y]),he=d.useCallback(async c=>{var u;r(c.id);const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{await Te(c.id,{signal:p.signal}),h(i,f.current)&&y("success","测试通知已发送,请检查对应渠道")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"发送失败"))}finally{h(i,f.current)&&r("")}},[y]),ge=d.useCallback(async()=>{var p;const c=++S.current;(p=L.current)==null||p.abort();const i=new AbortController;L.current=i,D(!0);try{const u={smtp_server:x.smtp_server||"",smtp_port:x.smtp_port||587,smtp_user:x.smtp_user||"",smtp_from_name:x.smtp_from_name||"",smtp_from_address:x.smtp_from_address||x.smtp_user||"",smtp_use_tls:x.smtp_use_tls!==!1,smtp_use_ssl:x.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(x,"smtp_password")&&(u.smtp_password=x.smtp_password),await Pe(u,{signal:i.signal}),h(c,S.current)&&y("success","SMTP 配置已保存")}catch(u){h(c,S.current)&&!i.signal.aborted&&y("error",A(u,"保存失败"))}finally{h(c,S.current)&&D(!1)}},[y,x]);return{channels:t,loading:n,showModal:w,editing:N,saving:E,testingId:M,toast:o,smtp:x,smtpSaving:U,showSmtpPassword:X,showChannelSmtpPassword:l,form:_,setForm:q,setSmtp:k,setShowSmtpPassword:z,setShowChannelSmtpPassword:m,loadChannels:R,openCreate:ie,openEdit:de,closeModal:me,showToast:y,handleSave:pe,handleDelete:ue,handleToggleEnabled:xe,handleTest:he,handleSaveSmtp:ge}},Ie=({isAdmin:s=!1})=>{const t=Ae(s);return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:t.loadChannels,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(_e,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:t.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(ve,{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(W,{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:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),t.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(I,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(Le,{channels:t.channels,testingId:t.testingId,onEdit:t.openEdit,onDelete:t.handleDelete,onToggleEnabled:t.handleToggleEnabled,onTest:t.handleTest}),s&&e.jsx(Fe,{smtp:t.smtp,setSmtp:t.setSmtp,smtpSaving:t.smtpSaving,showPassword:t.showSmtpPassword,setShowPassword:t.setShowSmtpPassword,onSave:t.handleSaveSmtp}),e.jsx($e,{showModal:t.showModal,editing:t.editing,form:t.form,setForm:t.setForm,smtp:t.smtp,showChannelSmtpPassword:t.showChannelSmtpPassword,setShowChannelSmtpPassword:t.setShowChannelSmtpPassword,saving:t.saving,onClose:t.closeModal,onSave:t.handleSave}),t.toast&&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 ${t.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[t.toast.type==="success"?e.jsx(J,{className:"w-4 h-4"}):e.jsx(te,{className:"w-4 h-4"}),t.toast.text]})]})};export{Ie as default}; +import{j as e,b as be,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as fe,x as G,a as W,f as I,y as ye,F as je,s as J,X as te,u as ae,v as le,r as Ne,R as _e,N as ve}from"./icons-vendor-ThcsWkZG.js";import{n as we,a3 as ke,al as Y,am as Ce,an as Se,ao as Te,a5 as Pe}from"./index-CsLZwESi.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],Q=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},re=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?Q(s.use_custom_smtp,!1):a}},ne=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=Q(a.smtp_use_tls,!0),a.smtp_use_ssl=Q(a.smtp_use_ssl,!1),a},oe=s=>{const t=re(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},$={bark:{label:"Bark",icon:W,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:G,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:G,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:G,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:fe,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:se,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:ee,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},ce=[{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:"后台任务或系统级异常"}],Z=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Ee=s=>!s||s.length===0?"全部事件":s.map(t=>{var a;return((a=ce.find(n=>n.value===t))==null?void 0:a.label)||t}).join("、"),Me=(s,t)=>{const a=s.type==="email"?re({...s.config||{}}):null,n=a?a.use_custom_smtp===!0?ne(a,t):a:{...s.config||{}};return{name:s.name,type:s.type,enabled:s.enabled,config:n,event_types:s.event_types||[]}},qe=s=>{const a=$[s.type].fields.find(n=>n.required&&!String(s.config[n.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!s.name.trim())return"请填写渠道名称";if(s.type==="email"){const n=oe(s.config);if(n.use_custom_smtp){const w=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([g])=>!String(n[g]||"").trim());if(w)return`请填写 ${w[1]}`}}return""},Re=s=>({name:s.name.trim(),type:s.type,config:s.type==="email"?oe(s.config):s.config,event_types:s.event_types,enabled:s.enabled}),h=(s,t)=>s===t,A=(s,t)=>s instanceof Error&&s.message?s.message:t,Le=({channels:s,testingId:t,onEdit:a,onDelete:n,onToggleEnabled:b,onTest:w})=>{const g=r=>s.find(o=>o.id===r.currentTarget.dataset.channelId)||null,N=r=>{const o=g(r);o&&b(o)},C=r=>{const o=g(r);o&&w(o)},E=r=>{const o=g(r);o&&a(o)},j=r=>{const o=g(r);o&&n(o)},M=r=>{const o=$[r.type]||$.webhook,P=o.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(P,{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:r.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:o.label}),!r.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:o.fields.map(x=>{var k;return(k=r.config)==null?void 0:k[x.key]}).filter(Boolean).map((x,k)=>e.jsx("span",{className:"mr-3",children:String(x).length>40?`${String(x).slice(0,40)}…`:String(x)},k))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Ee(r.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":r.id,onClick:N,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${r.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:r.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":r.id,onClick:C,disabled:t===r.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:[t===r.id?e.jsx(I,{className:"w-3 h-3 animate-spin"}):e.jsx(se,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":r.id,onClick:E,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(ye,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":r.id,onClick:j,className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(je,{className:"w-4 h-4"})})]})]},r.id)};return s.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(W,{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:s.map(M)})},Be=({selectedEvents:s,onToggleEvent:t})=>{const a=n=>{const b=n.currentTarget.dataset.event;b&&t(b)};return 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:ce.map(n=>{const b=s.includes(n.value);return e.jsxs("button",{type:"button","data-event":n.value,onClick:a,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(J,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${b?"text-brand":"text-gray-800"}`,children:n.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:n.description})]},n.value)})})]})},$e=({showModal:s,editing:t,form:a,setForm:n,smtp:b,showChannelSmtpPassword:w,setShowChannelSmtpPassword:g,saving:N,onClose:C,onSave:E})=>{const j=$[a.type],M=l=>n(m=>({...m,name:l.target.value})),r=l=>{const m=l.currentTarget.dataset.type;m&&n(_=>({..._,type:m,config:{}}))},o=l=>{const m=l.currentTarget.dataset.field;m&&n(_=>({..._,config:{..._.config,[m]:l.target.value}}))},P=()=>n(l=>({...l,config:l.config.use_custom_smtp===!0?{...l.config,use_custom_smtp:!1}:ne(l.config,b)})),x=l=>n(m=>({...m,config:{...m.config,smtp_use_tls:l.target.checked,smtp_use_ssl:l.target.checked?!1:m.config.smtp_use_ssl}})),k=l=>n(m=>({...m,config:{...m.config,smtp_use_ssl:l.target.checked,smtp_use_tls:l.target.checked?!1:m.config.smtp_use_tls}})),U=l=>n(m=>({...m,event_types:m.event_types.includes(l)?m.event_types.filter(_=>_!==l):[...m.event_types,l]})),D=()=>n(l=>({...l,enabled:!l.enabled})),X=()=>g(l=>!l),z=(l,m)=>e.jsx("li",{children:l},m);return s?be.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:t?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:C,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(te,{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:a.name,onChange:M,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($).map(l=>{const m=$[l],_=m.icon,q=a.type===l;return e.jsxs("button",{"data-type":l,type:"button",onClick:r,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(_,{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:m.label})]},l)})})]}),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(W,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",j.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:j.guide.steps.map(z)}),j.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:j.guide.urlFormat})]}),j.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",j.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:j.fields.map(l=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[l.label,l.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":l.key,type:l.type==="password"?"password":l.type==="number"?"number":"text",value:String(a.config[l.key]||""),onChange:o,placeholder:l.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),l.help&&e.jsx("p",{className:"text-xs text-gray-500",children:l.help})]},l.key))}),a.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:a.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:P,className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${a.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 ${a.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),a.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",{"data-field":"smtp_server",type:"text",value:String(a.config.smtp_server||""),onChange:o,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",{"data-field":"smtp_port",type:"number",value:String(a.config.smtp_port||587),onChange:o,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",{"data-field":"smtp_user",type:"email",value:String(a.config.smtp_user||""),onChange:o,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",{"data-field":"smtp_password",type:w?"text":"password",value:String(a.config.smtp_password||""),onChange:o,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:X,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:w?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(le,{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",{"data-field":"smtp_from_name",type:"text",value:String(a.config.smtp_from_name||""),onChange:o,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",{"data-field":"smtp_from_address",type:"email",value:String(a.config.smtp_from_address||""),onChange:o,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:a.config.smtp_use_tls!==!1,onChange:x}),"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:a.config.smtp_use_ssl===!0,onChange:k}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Be,{selectedEvents:a.event_types,onToggleEvent:U}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:D,className:`relative w-11 h-6 rounded-full transition-colors ${a.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 ${a.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:C,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:E,disabled:N,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[N?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(J,{className:"w-4 h-4"}),N?"保存中...":"保存"]})]})]})}),document.body):null},Fe=({smtp:s,setSmtp:t,smtpSaving:a,showPassword:n,setShowPassword:b,onSave:w})=>{const g=r=>{const o=r.currentTarget.dataset.field;o&&t(P=>({...P,[o]:r.target.value}))},N=r=>{t(o=>({...o,smtp_port:parseInt(r.target.value,10)||587}))},C=r=>{t(o=>({...o,smtp_use_tls:r.target.checked,smtp_use_ssl:r.target.checked?!1:o.smtp_use_ssl}))},E=r=>{t(o=>({...o,smtp_use_ssl:r.target.checked,smtp_use_tls:r.target.checked?!1:o.smtp_use_tls}))},j=r=>{t(o=>({...o,smtp_password:r.target.value}))},M=()=>b(r=>!r);return 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(ee,{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",{"data-field":"smtp_server",type:"text",value:s.smtp_server||"",onChange:g,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:s.smtp_port||587,onChange:N,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",{"data-field":"smtp_user",type:"email",value:s.smtp_user||"",onChange:g,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:n?"text":"password",value:s.smtp_password||"",onChange:j,placeholder:s.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:M,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:n?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(le,{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",{"data-field":"smtp_from_name",type:"text",value:s.smtp_from_name||"",onChange:g,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",{"data-field":"smtp_from_address",type:"email",value:s.smtp_from_address||s.smtp_user||"",onChange:g,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_tls!==!1,onChange:C}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_ssl===!0,onChange:E}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:w,disabled:a,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(Ne,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},Ae=s=>{const[t,a]=d.useState([]),[n,b]=d.useState(!0),[w,g]=d.useState(!1),[N,C]=d.useState(null),[E,j]=d.useState(!1),[M,r]=d.useState(""),[o,P]=d.useState(null),[x,k]=d.useState({}),[U,D]=d.useState(!1),[X,z]=d.useState(!1),[l,m]=d.useState(!1),[_,q]=d.useState(Z),F=d.useRef(0),K=d.useRef(null),S=d.useRef(0),L=d.useRef(null),f=d.useRef(0),T=d.useRef(null),B=d.useRef(null),y=d.useCallback((c,i)=>{P({type:c,text:i}),B.current!==null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{B.current=null,P(null)},3e3)},[]),R=d.useCallback(async()=>{var p;const c=++F.current;(p=K.current)==null||p.abort();const i=new AbortController;K.current=i,b(!0);try{const u=await we({signal:i.signal});if(!h(c,F.current))return;a(u.data||[])}catch(u){h(c,F.current)&&!i.signal.aborted&&console.error("加载通知渠道失败",u)}finally{h(c,F.current)&&b(!1)}},[]),V=d.useCallback(async()=>{var p;const c=++S.current;(p=L.current)==null||p.abort();const i=new AbortController;L.current=i;try{const u=await ke({signal:i.signal});h(c,S.current)&&k(u||{})}catch(u){h(c,S.current)&&!i.signal.aborted&&console.error("加载 SMTP 配置失败",u)}},[]);d.useEffect(()=>{var c;return R(),s?V():(S.current+=1,(c=L.current)==null||c.abort(),k({})),(()=>{var i,p;F.current+=1,(i=K.current)==null||i.abort(),S.current+=1,(p=L.current)==null||p.abort()})},[s,R,V]),d.useEffect(()=>(()=>{B.current!==null&&window.clearTimeout(B.current)}),[]);const ie=d.useCallback(()=>{C(null),q(Z()),m(!1),g(!0)},[]),de=d.useCallback(c=>{C(c),q(Me(c,x)),m(!1),g(!0)},[x]),me=d.useCallback(()=>{var c;f.current+=1,(c=T.current)==null||c.abort(),j(!1),g(!1)},[]),pe=d.useCallback(async()=>{var u;const c=qe(_);if(c){y("error",c);return}const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p,j(!0);try{const v=Re(_);if(N?await Y(N.id,v,{signal:p.signal}):await Ce(v,{signal:p.signal}),!h(i,f.current)||(g(!1),await R(),!h(i,f.current)))return;y("success",N?"已更新":"已创建")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"保存失败"))}finally{h(i,f.current)&&j(!1)}},[N,_,R,y]),ue=d.useCallback(async c=>{var u;if(!confirm(`确认删除渠道「${c.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{if(await Se(c.id,{signal:p.signal}),!h(i,f.current)||(await R(),!h(i,f.current)))return;y("success","已删除")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"删除失败"))}},[R,y]),xe=d.useCallback(async c=>{var u;const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{if(await Y(c.id,{enabled:!c.enabled},{signal:p.signal}),!h(i,f.current))return;a(v=>v.map(O=>O.id===c.id?{...O,enabled:!O.enabled}:O))}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"切换失败"))}},[y]),he=d.useCallback(async c=>{var u;r(c.id);const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{await Te(c.id,{signal:p.signal}),h(i,f.current)&&y("success","测试通知已发送,请检查对应渠道")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"发送失败"))}finally{h(i,f.current)&&r("")}},[y]),ge=d.useCallback(async()=>{var p;const c=++S.current;(p=L.current)==null||p.abort();const i=new AbortController;L.current=i,D(!0);try{const u={smtp_server:x.smtp_server||"",smtp_port:x.smtp_port||587,smtp_user:x.smtp_user||"",smtp_from_name:x.smtp_from_name||"",smtp_from_address:x.smtp_from_address||x.smtp_user||"",smtp_use_tls:x.smtp_use_tls!==!1,smtp_use_ssl:x.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(x,"smtp_password")&&(u.smtp_password=x.smtp_password),await Pe(u,{signal:i.signal}),h(c,S.current)&&y("success","SMTP 配置已保存")}catch(u){h(c,S.current)&&!i.signal.aborted&&y("error",A(u,"保存失败"))}finally{h(c,S.current)&&D(!1)}},[y,x]);return{channels:t,loading:n,showModal:w,editing:N,saving:E,testingId:M,toast:o,smtp:x,smtpSaving:U,showSmtpPassword:X,showChannelSmtpPassword:l,form:_,setForm:q,setSmtp:k,setShowSmtpPassword:z,setShowChannelSmtpPassword:m,loadChannels:R,openCreate:ie,openEdit:de,closeModal:me,showToast:y,handleSave:pe,handleDelete:ue,handleToggleEnabled:xe,handleTest:he,handleSaveSmtp:ge}},Ie=({isAdmin:s=!1})=>{const t=Ae(s);return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:t.loadChannels,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(_e,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:t.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(ve,{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(W,{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:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),t.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(I,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(Le,{channels:t.channels,testingId:t.testingId,onEdit:t.openEdit,onDelete:t.handleDelete,onToggleEnabled:t.handleToggleEnabled,onTest:t.handleTest}),s&&e.jsx(Fe,{smtp:t.smtp,setSmtp:t.setSmtp,smtpSaving:t.smtpSaving,showPassword:t.showSmtpPassword,setShowPassword:t.setShowSmtpPassword,onSave:t.handleSaveSmtp}),e.jsx($e,{showModal:t.showModal,editing:t.editing,form:t.form,setForm:t.setForm,smtp:t.smtp,showChannelSmtpPassword:t.showChannelSmtpPassword,setShowChannelSmtpPassword:t.setShowChannelSmtpPassword,saving:t.saving,onClose:t.closeModal,onSave:t.handleSave}),t.toast&&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 ${t.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[t.toast.type==="success"?e.jsx(J,{className:"w-4 h-4"}):e.jsx(te,{className:"w-4 h-4"}),t.toast.text]})]})};export{Ie as default}; diff --git a/internal/webui/static/assets/OrderList-vw6Kdzf7.js b/internal/webui/static/assets/OrderList-DpM_ZNlI.js similarity index 99% rename from internal/webui/static/assets/OrderList-vw6Kdzf7.js rename to internal/webui/static/assets/OrderList-DpM_ZNlI.js index ab64c13..be1dc17 100644 --- a/internal/webui/static/assets/OrderList-vw6Kdzf7.js +++ b/internal/webui/static/assets/OrderList-DpM_ZNlI.js @@ -1 +1 @@ -import{j as e,b as U,r as a}from"./react-vendor-C_od1ZSF.js";import{i as ee,I as te,X as H,J as ae,R as W,N as le,O as X,m as K,E as re,v as ne,V as ie,F as ce,d as de,c as oe,r as xe}from"./icons-vendor-ThcsWkZG.js";import{D as me,h as ue,a as he,E as ge,F as pe,G as be,H as ye,I as je,J as fe}from"./index-CFJ5pUjO.js";import{f as Y}from"./dateTime-DDi7rqpW.js";const ve=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Ne=s=>{const r=typeof s=="object"&&s!==null?s:{},m=Array.isArray(r.results)?r.results:[];return{total:Number(r.total||0),success_count:Number(r.success_count||0),failed_count:Number(r.failed_count||0),results:m.map(we)}},we=s=>{const r=typeof s=="object"&&s!==null?s:{};return{order_id:String(r.order_id||"unknown"),success:r.success===!0,message:String(r.message||"")}},_e=s=>(s==null?void 0:s.results.filter(ke))||[],ke=s=>!s.success,Ce=(s,r)=>s!==null&&!r,Se=s=>{if(!s)return"请选择订单文件";const r=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(r)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},q=(s,r)=>s===r,Ie=(s,r)=>s instanceof Error&&s.message?s.message:r,Ee=({filter:s,onFilterChange:r,accountFilter:m,onAccountFilterChange:p,accounts:j,accountName:x,searchText:b,onSearchChange:N})=>{const E=n=>r(n.currentTarget.dataset.status||"all"),S=n=>p(n.target.value),f=n=>N(n.target.value);return 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:ve.map(n=>e.jsx("button",{"data-status":n.key,onClick:E,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===n.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:n.label},n.key))}),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(ee,{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:m,onChange:S,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:"全部账号"}),j.map(n=>e.jsx("option",{value:n.id,children:x(n.id)},n.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(te,{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:b,onChange:f,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const r=x=>{var b;s.setImportFile(((b=x.target.files)==null?void 0:b[0])||null)},m=()=>s.closeImportModal(),p=()=>void s.handleImportOrders(),j=()=>void s.handleRetryImport();return s.showImportModal?U.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:m,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:r,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 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:j,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.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:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.importResult.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:_e(s.importResult).map((x,b)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:x.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:x.message||"导入失败"})]},`${x.order_id}-${b}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:m,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:p,disabled:!s.importFile||s.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:s.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Me=(s={pageSize:20})=>{const[r,m]=a.useState([]),[p,j]=a.useState([]),[x,b]=a.useState([]),[N,E]=a.useState("all"),[S,f]=a.useState(""),[n,d]=a.useState(""),[F,$]=a.useState(""),[I,w]=a.useState(1),[_,A]=a.useState(1),[O,i]=a.useState(!1),y=a.useRef(0),u=a.useRef(null),M=a.useRef(null),R=a.useCallback(async()=>{var h;const c=++y.current;(h=u.current)==null||h.abort();const o=new AbortController;u.current=o,i(!0);try{const k=await me(S||void 0,N,I,s.pageSize,F,{signal:o.signal});if(!q(c,y.current))return;m(k.data),A(k.total_pages)}catch(k){q(c,y.current)&&!o.signal.aborted&&console.error("加载订单失败:",k)}finally{q(c,y.current)&&i(!1)}},[S,F,N,s.pageSize,I]);a.useEffect(()=>{const c=window.setTimeout(()=>{w(1),$(n.trim())},300);return(()=>window.clearTimeout(c))},[n]),a.useEffect(()=>(R(),(()=>{var c;y.current+=1,(c=u.current)==null||c.abort()})),[R]),a.useEffect(()=>{var o;const c=new AbortController;return(o=M.current)==null||o.abort(),M.current=c,Promise.all([ue({signal:c.signal}),he(void 0,{signal:c.signal})]).then(([h,k])=>{c.signal.aborted||(b(h),j(k))}).catch(h=>{c.signal.aborted||console.error("加载订单辅助数据失败:",h)}),(()=>c.abort())},[]);const v=a.useMemo(()=>new Map(x.map(c=>[c.id,c])),[x]),P=a.useMemo(()=>{const c={};return p.forEach(o=>{o.item_id&&(c[`${o.cookie_id}:${o.item_id}`]=o.item_title||o.item_id)}),c},[p]),G=a.useCallback(c=>{const o=v.get(c),h=(o==null?void 0:o.remark)||(o==null?void 0:o.nickname);return h?`${h} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},[v]),V=a.useCallback(c=>{const o=v.get(c);return(o==null?void 0:o.remark)||(o==null?void 0:o.nickname)||"未命名账号"},[v]),z=a.useCallback((c,o,h)=>{if(h!=null&&h.trim())return h;const k=P[`${c}:${o}`];if(k)return k;const C=p.find(T=>{if(!h||!T.item_title)return!1;const B=h.toLowerCase(),L=T.item_title.toLowerCase();return L.includes(B)||B.includes(L)});return(C==null?void 0:C.item_title)||"未知商品"},[P,p]);return{orders:r,items:p,accounts:x,filter:N,setFilter:E,accountFilter:S,setAccountFilter:f,searchText:n,setSearchText:d,page:I,setPage:w,totalPages:_,loading:O,loadOrders:R,accountName:G,accountNickname:V,getItemNameById:z}},Fe=s=>{const[r,m]=a.useState(!1),[p,j]=a.useState(null),[x,b]=a.useState(null),[N,E]=a.useState(!1),[S,f]=a.useState(""),n=a.useRef(0),d=a.useRef(null),F=a.useCallback(()=>{j(null),b(null),f(""),m(!0)},[]),$=a.useCallback(()=>{var _;n.current+=1,(_=d.current)==null||_.abort(),E(!1),m(!1),j(null),b(null),f("")},[]),I=a.useCallback(async()=>{var y;if(!Ce(p,N))return;const _=p;if(!_)return;const A=Se(_);if(A){f(A);return}const O=++n.current;(y=d.current)==null||y.abort();const i=new AbortController;d.current=i,E(!0),b(null),f("");try{const u=new FormData;u.append("file",_);const M=Ne(await ge(u,{signal:i.signal}));if(!q(O,n.current))return;b(M),j(null),await s(),M.failed_count===0&&q(O,n.current)&&(alert(`订单导入成功,共 ${M.success_count} 条`),m(!1),b(null))}catch(u){q(O,n.current)&&!i.signal.aborted&&f(Ie(u,"导入失败,请检查文件格式"))}finally{q(O,n.current)&&E(!1)}},[p,N,s]),w=a.useCallback(async()=>{await I()},[I]);return{showImportModal:r,importFile:p,setImportFile:j,importResult:x,importing:N,importError:S,openImportModal:F,closeImportModal:$,handleImportOrders:I,handleRetryImport:w}},Q=(s,r)=>s instanceof Error?s.message:r,Re=({orders:s,page:r,accountFilter:m,filter:p,setPage:j,loadOrders:x})=>{const[b,N]=a.useState(!1),[E,S]=a.useState(null),[f,n]=a.useState(!1),[d,F]=a.useState(null),[$,I]=a.useState(!1),[w,_]=a.useState(""),[A,O]=a.useState(!1),[i,y]=a.useState(null),[u,M]=a.useState(null),[R,v]=a.useState(null),P=a.useCallback(async()=>{try{const l=await pe(m||void 0,p);await x(),l.message&&alert(l.message)}catch(l){console.error("同步订单失败:",l),alert(Q(l,"同步失败,请重试"))}},[m,p,x]),G=a.useCallback(l=>{_(l),y(null),I(!0)},[]),V=a.useCallback(async l=>{var g;O(!0),y(null);try{const D=(g=(await be([w],l)).results)==null?void 0:g[0];D!=null&&D.success?(y({success:!0,message:D.message}),x()):y({success:!1,message:(D==null?void 0:D.message)||"发货失败"})}catch(J){y({success:!1,message:Q(J,"请求失败")})}finally{O(!1)}},[x,w]),z=a.useCallback(l=>{S(l),N(!0)},[]),c=a.useCallback(l=>{F({...l}),n(!0)},[]),o=a.useCallback(l=>{F(g=>g&&{...g,...l})},[]),h=a.useCallback(async()=>{if(d!=null&&d.order_id)try{const l={};d.status!==void 0&&(l.order_status=d.status),d.buyer_id!==void 0&&(l.buyer_id=d.buyer_id),d.amount!==void 0&&(l.amount=d.amount),d.receiver_name!==void 0&&(l.receiver_name=d.receiver_name),d.receiver_phone!==void 0&&(l.receiver_phone=d.receiver_phone),d.receiver_address!==void 0&&(l.receiver_address=d.receiver_address),d.item_id!==void 0&&(l.item_id=d.item_id),d.quantity!==void 0&&(l.quantity=d.quantity),d.item_title!==void 0&&(l.item_title=d.item_title),await ye(d.order_id,l),n(!1),F(null),await x()}catch(l){console.error("更新订单失败:",l),alert("更新失败,请重试")}},[d,x]),k=a.useCallback(async l=>{M(l);try{const g=await je(l);g.success?await x():alert(g.message||"同步失败")}catch(g){console.error("同步订单失败:",g),alert(Q(g,"同步失败,请重试"))}finally{M(null)}},[x]),C=a.useCallback(async l=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){v(l);try{await fe(l),s.length===1&&r>1?j(g=>g-1):await x()}catch(g){console.error("删除订单失败:",g),alert(Q(g,"删除失败,请重试")),await x()}finally{v(null)}}},[x,s.length,r,j]),T=a.useCallback(()=>N(!1),[]),B=a.useCallback(()=>n(!1),[]),L=a.useCallback(()=>{I(!1),y(null)},[]);return{showDetailModal:b,selectedOrder:E,showEditModal:f,editingOrder:d,showShipModal:$,shipOrderId:w,shipLoading:A,shipResult:i,syncingOrderId:u,deletingOrderId:R,handleSync:P,handleShip:G,executeShip:V,handleViewDetail:z,handleEdit:c,handleSaveEdit:h,updateEditingOrder:o,handleSyncSingle:k,handleDelete:C,closeDetailModal:T,closeEditModal:B,closeShipModal:L}},Z=({status:s})=>{const r={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"},m={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${r[s]||r.cancelled}`,children:m[s]||s})},Pe=()=>{const s=Me(),r=Fe(s.loadOrders),{orders:m,accounts:p,filter:j,setFilter:x,accountFilter:b,setAccountFilter:N,searchText:E,setSearchText:S,page:f,setPage:n,totalPages:d,loading:F,loadOrders:$,accountName:I,accountNickname:w,getItemNameById:_}=s,A=Re({orders:m,page:f,accountFilter:b,filter:j,setPage:n,loadOrders:$}),{showDetailModal:O,selectedOrder:i,showEditModal:y,editingOrder:u,showShipModal:M,shipLoading:R,shipResult:v,syncingOrderId:P,deletingOrderId:G,handleSync:V,handleShip:z,executeShip:c,handleViewDetail:o,handleEdit:h,handleSaveEdit:k,updateEditingOrder:C,handleSyncSingle:T,handleDelete:B,closeDetailModal:L,closeEditModal:l,closeShipModal:g}=A,J=t=>{x(t),n(1),S("")},D=t=>{N(t),n(1)},se=t=>{S(t),n(1)};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:$,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(W,{className:`w-5 h-5 ${F?"animate-spin":""}`})}),e.jsxs("button",{onClick:r.openImportModal,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(le,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:V,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(X,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Ee,{filter:j,onFilterChange:J,accountFilter:b,onAccountFilterChange:D,accounts:p,accountName:I,searchText:E,onSearchChange:se}),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:m.map(t=>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:t.item_image?e.jsx("img",{src:t.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(K,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:_(t.cookie_id,t.item_id,t.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:w(t.cookie_id),children:[e.jsx(ee,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:w(t.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",t.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",t.quantity," • ",Y(t.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:t.buyer_id}),t.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:t.receiver_name})]}),t.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:t.receiver_phone})]}),t.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:t.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:t.amount?`¥${t.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(Z,{status:t.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[t.status==="pending_ship"&&e.jsx("button",{onClick:(()=>z(t.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=${t.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(re,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>o(t)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(ne,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>h(t)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(ie,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>T(t.order_id)),disabled:P===t.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(W,{className:`w-4 h-4 ${P===t.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>B(t.order_id)),disabled:G===t.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(ce,{className:"w-4 h-4"})})]})]},t.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:["第 ",f," 页 / 共 ",d," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:f<=1,onClick:(()=>n(t=>t-1)),"aria-label":"上一页",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(de,{className:"w-5 h-5"})}),e.jsx("button",{disabled:f>=d,onClick:(()=>n(t=>t+1)),"aria-label":"下一页",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(oe,{className:"w-5 h-5"})})]})]})]}),O&&i&&U.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:L,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:i.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:w(i.cookie_id),children:w(i.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(Z,{status:i.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:i.amount?`¥${i.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:i.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:Y(i.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:[i.item_image&&e.jsx("img",{src:i.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:_(i.cookie_id,i.item_id,i.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",i.item_id]}),i.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",i.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:i.buyer_id})]}),i.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:i.receiver_name})]}),i.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:i.receiver_phone})]}),i.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:i.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:L,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),i.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{L(),z(i.order_id)}),className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),e.jsx(Oe,{...r}),M&&U.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:g,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:(()=>c("status_only")),disabled:R,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(X,{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:(()=>c("full_delivery")),disabled:R,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(K,{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:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),R&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(W,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),v&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${v.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[v.success?"✓ ":"✗ ",v.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:g,className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:v!=null&&v.success?"完成":"取消"})})]})}),document.body),y&&u&&U.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:l,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:u.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:u.status,onChange:(t=>C({status:t.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:u.buyer_id,onChange:(t=>C({buyer_id:t.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:u.amount,onChange:(t=>C({amount:t.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:u.receiver_name||"",onChange:(t=>C({receiver_name:t.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:u.receiver_phone||"",onChange:(t=>C({receiver_phone:t.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:u.receiver_address||"",onChange:(t=>C({receiver_address:t.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:u.item_title||"",onChange:(t=>C({item_title:t.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:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:k,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(xe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})};export{Pe as default}; +import{j as e,b as U,r as a}from"./react-vendor-C_od1ZSF.js";import{i as ee,I as te,X as H,J as ae,R as W,N as le,O as X,m as K,E as re,v as ne,V as ie,F as ce,d as de,c as oe,r as xe}from"./icons-vendor-ThcsWkZG.js";import{D as me,h as ue,a as he,E as ge,F as pe,G as be,H as ye,I as je,J as fe}from"./index-CsLZwESi.js";import{f as Y}from"./dateTime-DDi7rqpW.js";const ve=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Ne=s=>{const r=typeof s=="object"&&s!==null?s:{},m=Array.isArray(r.results)?r.results:[];return{total:Number(r.total||0),success_count:Number(r.success_count||0),failed_count:Number(r.failed_count||0),results:m.map(we)}},we=s=>{const r=typeof s=="object"&&s!==null?s:{};return{order_id:String(r.order_id||"unknown"),success:r.success===!0,message:String(r.message||"")}},_e=s=>(s==null?void 0:s.results.filter(ke))||[],ke=s=>!s.success,Ce=(s,r)=>s!==null&&!r,Se=s=>{if(!s)return"请选择订单文件";const r=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(r)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},q=(s,r)=>s===r,Ie=(s,r)=>s instanceof Error&&s.message?s.message:r,Ee=({filter:s,onFilterChange:r,accountFilter:m,onAccountFilterChange:p,accounts:j,accountName:x,searchText:b,onSearchChange:N})=>{const E=n=>r(n.currentTarget.dataset.status||"all"),S=n=>p(n.target.value),f=n=>N(n.target.value);return 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:ve.map(n=>e.jsx("button",{"data-status":n.key,onClick:E,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===n.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:n.label},n.key))}),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(ee,{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:m,onChange:S,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:"全部账号"}),j.map(n=>e.jsx("option",{value:n.id,children:x(n.id)},n.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(te,{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:b,onChange:f,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const r=x=>{var b;s.setImportFile(((b=x.target.files)==null?void 0:b[0])||null)},m=()=>s.closeImportModal(),p=()=>void s.handleImportOrders(),j=()=>void s.handleRetryImport();return s.showImportModal?U.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:m,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:r,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 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:j,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.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:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.importResult.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:_e(s.importResult).map((x,b)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:x.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:x.message||"导入失败"})]},`${x.order_id}-${b}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:m,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:p,disabled:!s.importFile||s.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:s.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Me=(s={pageSize:20})=>{const[r,m]=a.useState([]),[p,j]=a.useState([]),[x,b]=a.useState([]),[N,E]=a.useState("all"),[S,f]=a.useState(""),[n,d]=a.useState(""),[F,$]=a.useState(""),[I,w]=a.useState(1),[_,A]=a.useState(1),[O,i]=a.useState(!1),y=a.useRef(0),u=a.useRef(null),M=a.useRef(null),R=a.useCallback(async()=>{var h;const c=++y.current;(h=u.current)==null||h.abort();const o=new AbortController;u.current=o,i(!0);try{const k=await me(S||void 0,N,I,s.pageSize,F,{signal:o.signal});if(!q(c,y.current))return;m(k.data),A(k.total_pages)}catch(k){q(c,y.current)&&!o.signal.aborted&&console.error("加载订单失败:",k)}finally{q(c,y.current)&&i(!1)}},[S,F,N,s.pageSize,I]);a.useEffect(()=>{const c=window.setTimeout(()=>{w(1),$(n.trim())},300);return(()=>window.clearTimeout(c))},[n]),a.useEffect(()=>(R(),(()=>{var c;y.current+=1,(c=u.current)==null||c.abort()})),[R]),a.useEffect(()=>{var o;const c=new AbortController;return(o=M.current)==null||o.abort(),M.current=c,Promise.all([ue({signal:c.signal}),he(void 0,{signal:c.signal})]).then(([h,k])=>{c.signal.aborted||(b(h),j(k))}).catch(h=>{c.signal.aborted||console.error("加载订单辅助数据失败:",h)}),(()=>c.abort())},[]);const v=a.useMemo(()=>new Map(x.map(c=>[c.id,c])),[x]),P=a.useMemo(()=>{const c={};return p.forEach(o=>{o.item_id&&(c[`${o.cookie_id}:${o.item_id}`]=o.item_title||o.item_id)}),c},[p]),G=a.useCallback(c=>{const o=v.get(c),h=(o==null?void 0:o.remark)||(o==null?void 0:o.nickname);return h?`${h} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},[v]),V=a.useCallback(c=>{const o=v.get(c);return(o==null?void 0:o.remark)||(o==null?void 0:o.nickname)||"未命名账号"},[v]),z=a.useCallback((c,o,h)=>{if(h!=null&&h.trim())return h;const k=P[`${c}:${o}`];if(k)return k;const C=p.find(T=>{if(!h||!T.item_title)return!1;const B=h.toLowerCase(),L=T.item_title.toLowerCase();return L.includes(B)||B.includes(L)});return(C==null?void 0:C.item_title)||"未知商品"},[P,p]);return{orders:r,items:p,accounts:x,filter:N,setFilter:E,accountFilter:S,setAccountFilter:f,searchText:n,setSearchText:d,page:I,setPage:w,totalPages:_,loading:O,loadOrders:R,accountName:G,accountNickname:V,getItemNameById:z}},Fe=s=>{const[r,m]=a.useState(!1),[p,j]=a.useState(null),[x,b]=a.useState(null),[N,E]=a.useState(!1),[S,f]=a.useState(""),n=a.useRef(0),d=a.useRef(null),F=a.useCallback(()=>{j(null),b(null),f(""),m(!0)},[]),$=a.useCallback(()=>{var _;n.current+=1,(_=d.current)==null||_.abort(),E(!1),m(!1),j(null),b(null),f("")},[]),I=a.useCallback(async()=>{var y;if(!Ce(p,N))return;const _=p;if(!_)return;const A=Se(_);if(A){f(A);return}const O=++n.current;(y=d.current)==null||y.abort();const i=new AbortController;d.current=i,E(!0),b(null),f("");try{const u=new FormData;u.append("file",_);const M=Ne(await ge(u,{signal:i.signal}));if(!q(O,n.current))return;b(M),j(null),await s(),M.failed_count===0&&q(O,n.current)&&(alert(`订单导入成功,共 ${M.success_count} 条`),m(!1),b(null))}catch(u){q(O,n.current)&&!i.signal.aborted&&f(Ie(u,"导入失败,请检查文件格式"))}finally{q(O,n.current)&&E(!1)}},[p,N,s]),w=a.useCallback(async()=>{await I()},[I]);return{showImportModal:r,importFile:p,setImportFile:j,importResult:x,importing:N,importError:S,openImportModal:F,closeImportModal:$,handleImportOrders:I,handleRetryImport:w}},Q=(s,r)=>s instanceof Error?s.message:r,Re=({orders:s,page:r,accountFilter:m,filter:p,setPage:j,loadOrders:x})=>{const[b,N]=a.useState(!1),[E,S]=a.useState(null),[f,n]=a.useState(!1),[d,F]=a.useState(null),[$,I]=a.useState(!1),[w,_]=a.useState(""),[A,O]=a.useState(!1),[i,y]=a.useState(null),[u,M]=a.useState(null),[R,v]=a.useState(null),P=a.useCallback(async()=>{try{const l=await pe(m||void 0,p);await x(),l.message&&alert(l.message)}catch(l){console.error("同步订单失败:",l),alert(Q(l,"同步失败,请重试"))}},[m,p,x]),G=a.useCallback(l=>{_(l),y(null),I(!0)},[]),V=a.useCallback(async l=>{var g;O(!0),y(null);try{const D=(g=(await be([w],l)).results)==null?void 0:g[0];D!=null&&D.success?(y({success:!0,message:D.message}),x()):y({success:!1,message:(D==null?void 0:D.message)||"发货失败"})}catch(J){y({success:!1,message:Q(J,"请求失败")})}finally{O(!1)}},[x,w]),z=a.useCallback(l=>{S(l),N(!0)},[]),c=a.useCallback(l=>{F({...l}),n(!0)},[]),o=a.useCallback(l=>{F(g=>g&&{...g,...l})},[]),h=a.useCallback(async()=>{if(d!=null&&d.order_id)try{const l={};d.status!==void 0&&(l.order_status=d.status),d.buyer_id!==void 0&&(l.buyer_id=d.buyer_id),d.amount!==void 0&&(l.amount=d.amount),d.receiver_name!==void 0&&(l.receiver_name=d.receiver_name),d.receiver_phone!==void 0&&(l.receiver_phone=d.receiver_phone),d.receiver_address!==void 0&&(l.receiver_address=d.receiver_address),d.item_id!==void 0&&(l.item_id=d.item_id),d.quantity!==void 0&&(l.quantity=d.quantity),d.item_title!==void 0&&(l.item_title=d.item_title),await ye(d.order_id,l),n(!1),F(null),await x()}catch(l){console.error("更新订单失败:",l),alert("更新失败,请重试")}},[d,x]),k=a.useCallback(async l=>{M(l);try{const g=await je(l);g.success?await x():alert(g.message||"同步失败")}catch(g){console.error("同步订单失败:",g),alert(Q(g,"同步失败,请重试"))}finally{M(null)}},[x]),C=a.useCallback(async l=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){v(l);try{await fe(l),s.length===1&&r>1?j(g=>g-1):await x()}catch(g){console.error("删除订单失败:",g),alert(Q(g,"删除失败,请重试")),await x()}finally{v(null)}}},[x,s.length,r,j]),T=a.useCallback(()=>N(!1),[]),B=a.useCallback(()=>n(!1),[]),L=a.useCallback(()=>{I(!1),y(null)},[]);return{showDetailModal:b,selectedOrder:E,showEditModal:f,editingOrder:d,showShipModal:$,shipOrderId:w,shipLoading:A,shipResult:i,syncingOrderId:u,deletingOrderId:R,handleSync:P,handleShip:G,executeShip:V,handleViewDetail:z,handleEdit:c,handleSaveEdit:h,updateEditingOrder:o,handleSyncSingle:k,handleDelete:C,closeDetailModal:T,closeEditModal:B,closeShipModal:L}},Z=({status:s})=>{const r={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"},m={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${r[s]||r.cancelled}`,children:m[s]||s})},Pe=()=>{const s=Me(),r=Fe(s.loadOrders),{orders:m,accounts:p,filter:j,setFilter:x,accountFilter:b,setAccountFilter:N,searchText:E,setSearchText:S,page:f,setPage:n,totalPages:d,loading:F,loadOrders:$,accountName:I,accountNickname:w,getItemNameById:_}=s,A=Re({orders:m,page:f,accountFilter:b,filter:j,setPage:n,loadOrders:$}),{showDetailModal:O,selectedOrder:i,showEditModal:y,editingOrder:u,showShipModal:M,shipLoading:R,shipResult:v,syncingOrderId:P,deletingOrderId:G,handleSync:V,handleShip:z,executeShip:c,handleViewDetail:o,handleEdit:h,handleSaveEdit:k,updateEditingOrder:C,handleSyncSingle:T,handleDelete:B,closeDetailModal:L,closeEditModal:l,closeShipModal:g}=A,J=t=>{x(t),n(1),S("")},D=t=>{N(t),n(1)},se=t=>{S(t),n(1)};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:$,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(W,{className:`w-5 h-5 ${F?"animate-spin":""}`})}),e.jsxs("button",{onClick:r.openImportModal,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(le,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:V,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(X,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Ee,{filter:j,onFilterChange:J,accountFilter:b,onAccountFilterChange:D,accounts:p,accountName:I,searchText:E,onSearchChange:se}),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:m.map(t=>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:t.item_image?e.jsx("img",{src:t.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(K,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:_(t.cookie_id,t.item_id,t.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:w(t.cookie_id),children:[e.jsx(ee,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:w(t.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",t.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",t.quantity," • ",Y(t.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:t.buyer_id}),t.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:t.receiver_name})]}),t.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:t.receiver_phone})]}),t.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:t.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:t.amount?`¥${t.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(Z,{status:t.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[t.status==="pending_ship"&&e.jsx("button",{onClick:(()=>z(t.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=${t.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(re,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>o(t)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(ne,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>h(t)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(ie,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>T(t.order_id)),disabled:P===t.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(W,{className:`w-4 h-4 ${P===t.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>B(t.order_id)),disabled:G===t.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(ce,{className:"w-4 h-4"})})]})]},t.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:["第 ",f," 页 / 共 ",d," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:f<=1,onClick:(()=>n(t=>t-1)),"aria-label":"上一页",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(de,{className:"w-5 h-5"})}),e.jsx("button",{disabled:f>=d,onClick:(()=>n(t=>t+1)),"aria-label":"下一页",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(oe,{className:"w-5 h-5"})})]})]})]}),O&&i&&U.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:L,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:i.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:w(i.cookie_id),children:w(i.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(Z,{status:i.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:i.amount?`¥${i.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:i.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:Y(i.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:[i.item_image&&e.jsx("img",{src:i.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:_(i.cookie_id,i.item_id,i.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",i.item_id]}),i.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",i.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:i.buyer_id})]}),i.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:i.receiver_name})]}),i.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:i.receiver_phone})]}),i.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:i.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:L,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),i.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{L(),z(i.order_id)}),className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),e.jsx(Oe,{...r}),M&&U.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:g,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:(()=>c("status_only")),disabled:R,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(X,{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:(()=>c("full_delivery")),disabled:R,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(K,{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:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),R&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(W,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),v&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${v.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[v.success?"✓ ":"✗ ",v.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:g,className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:v!=null&&v.success?"完成":"取消"})})]})}),document.body),y&&u&&U.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:l,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:u.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:u.status,onChange:(t=>C({status:t.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:u.buyer_id,onChange:(t=>C({buyer_id:t.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:u.amount,onChange:(t=>C({amount:t.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:u.receiver_name||"",onChange:(t=>C({receiver_name:t.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:u.receiver_phone||"",onChange:(t=>C({receiver_phone:t.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:u.receiver_address||"",onChange:(t=>C({receiver_address:t.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:u.item_title||"",onChange:(t=>C({item_title:t.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:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:k,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(xe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})};export{Pe as default}; diff --git a/internal/webui/static/assets/Rules-BqImksVG.js b/internal/webui/static/assets/Rules-BqImksVG.js new file mode 100644 index 0000000..c68d4b7 --- /dev/null +++ b/internal/webui/static/assets/Rules-BqImksVG.js @@ -0,0 +1 @@ +import{j as e,r,b as Ie}from"./react-vendor-C_od1ZSF.js";import{k as Ve,ae as tt,af as pt,m as bt,R as Le,N as Ue,Z as Ke,x as gt,w as We,I as yt,a1 as ft,X as Ne,V as De,F as we,d as jt,c as _t,a6 as vt,ag as Nt,r as Ze,ah as wt}from"./icons-vendor-ThcsWkZG.js";import{h as kt,K as st,a as at,a7 as Xe,a8 as Ct,a9 as St,aa as Rt,ab as Ye,ac as At,ad as Mt,ae as Pt,af as $t,ag as It,ah as Lt,ai as Dt,aj as Ft,ak as Tt,Y as zt}from"./index-CsLZwESi.js";const Fe=(s,c)=>s.allowed_resolutions.includes(c),Et=(s,c)=>({runs:s.runs.filter(d=>!c||d.cookie_id===c),pending_tasks:s.pending_tasks.filter(d=>!c||d.cookie_id===c)}),qt=s=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[s]||"自动化异常",Vt=({runs:s,pendingTasks:c,onResolveRun:d,onResolveDeferredTask:y})=>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(Ve,{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:[s.map(o=>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:["账号 ",o.cookie_id," · 订单 ",o.order_id||"-"," · 已记录发送 ",o.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:qt(o.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:o.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Fe(o,"continue")&&e.jsx("button",{onClick:(()=>d(o.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Fe(o,"retry")&&e.jsx("button",{onClick:(()=>d(o.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Fe(o,"cancel")&&e.jsx("button",{onClick:(()=>d(o.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${o.id}`)),c.map(o=>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:["账号 ",o.cookie_id," · 延迟任务重试已达 ",o.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:o.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>y(o.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>y(o.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${o.id}`))]})]}),Te=()=>({submitting:!1,result:"idle"}),ze=s=>s.submitting?s:{submitting:!0,result:"idle"},Ee=(s,c)=>({submitting:!1,result:c?"success":"failure"}),Qe=s=>s+1,qe=(s,c,d,y)=>s===c&&d===y,Ot=s=>{const[c,d]=r.useState([]),[y,o]=r.useState({runs:[],pending_tasks:[]}),[U,F]=r.useState([]),[K,C]=r.useState({}),[se,T]=r.useState([]),[V,v]=r.useState([]),[O,P]=r.useState([]),[j,W]=r.useState(!1),z=r.useRef(0),ae=r.useRef(0),[Z,B]=r.useState(0),[le,X]=r.useState(0),[E,Y]=r.useState({}),G=r.useCallback(async()=>{const A=Promise.all([kt(),st(),at(),Xe()]),[b,f,$,Q]=await A;T(b),v(f),P($),C(Q),s.setSelectedAccountId(re=>{var L;return re||((L=b[0])==null?void 0:L.id)||""})},[s.setSelectedAccountId]),l=r.useCallback(async()=>{var Q;const A=Qe(z.current);z.current=A;const b=Ct().catch(re=>(console.warn("加载自动化异常列表失败,不阻断规则展示",re),null)),f=await St({cookieId:s.selectedAccountId||void 0,triggerType:s.automationTriggerFilter,enabled:s.automationStatusFilter==="all"?void 0:s.automationStatusFilter==="enabled",search:s.debouncedAutomationSearch,page:s.automationPage,pageSize:s.automationPageSize});if(!qe(A,z.current,s.selectedAccountId,s.selectedAccountId))return;d(f.data),B(f.total),X(f.total_pages),Y(f.trigger_counts||{}),f.page!==s.automationPage&&((Q=s.onAutomationPageChange)==null||Q.call(s,f.page));const $=await b;qe(A,z.current,s.selectedAccountId,s.selectedAccountId)&&$&&o($)},[s.automationPage,s.automationPageSize,s.automationStatusFilter,s.automationTriggerFilter,s.debouncedAutomationSearch,s.onAutomationPageChange,s.selectedAccountId]),S=r.useCallback(async()=>{const A=Qe(ae.current);ae.current=A;const b=s.selectedAccountId;if(F([]),!b)return;const f=await Rt(b);qe(A,ae.current,b,s.selectedAccountId)&&F(f)},[s.selectedAccountId]),k=r.useCallback(async()=>{C(await Xe())},[]),I=r.useCallback(async()=>{W(!0);try{s.activeTab==="automation"?await l():s.activeTab==="reply"?await S():await k()}finally{W(!1)}},[l,k,S,s.activeTab]);return{automationRules:c,automationIssues:y,replyRules:U,defaultReplies:K,accounts:se,cards:V,items:O,automationTotal:Z,automationTotalPages:le,automationTriggerCounts:E,loading:j,setLoading:W,setAutomationRules:d,setCards:v,setItems:P,loadReferenceData:G,loadAutomationRules:l,loadReplyRules:S,loadDefaultReplies:k,refresh:I}},te={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:bt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:pt},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:tt}},ke=["order_paid","buyer_reviewed","review_missing_timeout"],Bt="亲,商品使用满意的话,麻烦给个评价,谢谢~",be=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),lt=s=>{if(!s)return{};try{const c=JSON.parse(s);return c&&typeof c=="object"&&!Array.isArray(c)?c:{}}catch{return{}}},de=(s,c={})=>{const d=lt(s);return JSON.stringify({after_shipped_hours:Number(d.after_shipped_hours||72),repeat_interval_hours:Number(d.repeat_interval_hours||24),max_attempts:Number(d.max_attempts||1),...c})},ge=(s,c)=>{var y;const d=((y=te[s])==null?void 0:y.label)||"自动化规则";return c?`${d} - ${c}`:d},He=s=>{const c=(s||"").trim();return c?Object.values(te).some(d=>c===d.label||c.startsWith(`${d.label} -`)):!0},ye=(s,c=0)=>{if(s==="review_missing_timeout")return[{action_type:"send_text",message_template:Bt,enabled:!0,sort_order:1}];const d={action_type:"send_card",card_id:c,delivery_count:1,enabled:!0,sort_order:1};return s==="order_paid"?[d,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[d]},Gt=s=>{var d,y;if(s.trigger_type==="review_missing_timeout")return((y=(d=s.actions)==null?void 0:d.find(o=>o.action_type==="send_text"))==null?void 0:y.message_template)||"发送求评价文案";const c=(s.actions||[]).filter(o=>o.action_type==="send_card");return c.length?c.map(o=>o.card_name||`卡密 ${o.card_id}`).join(" / "):"未配置卡密库存"},et=(s,c=!1)=>{const d={blue:c?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:c?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:c?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return d[s]||d.blue},Jt=s=>s?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Ce=s=>(s==null?void 0:s.nickname)||(s==null?void 0:s.remark)||(s==null?void 0:s.id)||"未知账号",Ut=s=>s===!0||s===1||s==="1",Kt=({selectedAccountId:s,setSelectedAccountId:c,setActiveTab:d,items:y,setAutomationRules:o,setCards:U,setItems:F,setLoading:K,loadAutomationRules:C,loadReferenceData:se,loadReplyRules:T,loadDefaultReplies:V,initialDeliveryTarget:v,onDeliveryTargetHandled:O})=>{var me;const[P,j]=r.useState(!1),[W,z]=r.useState(!1),[ae,Z]=r.useState(!1),[B,le]=r.useState(Te),[X,E]=r.useState(Te),[Y,G]=r.useState(Te),[l,S]=r.useState(null),[k,I]=r.useState(null),[R,A]=r.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),b=r.useMemo(()=>l!=null&&l.cookie_id&&l.item_id?y.find(a=>a.cookie_id===l.cookie_id&&a.item_id===l.item_id):void 0,[l==null?void 0:l.cookie_id,l==null?void 0:l.item_id,y]),f=Ut(b==null?void 0:b.is_multi_spec),$=(l==null?void 0:l.trigger_type)||"order_paid",Q=te[$],re=lt(l==null?void 0:l.config_json),L=(me=l==null?void 0:l.variants)!=null&&me.length?l.variants:[be()],J=r.useCallback((a="order_paid",n=s,h="")=>{const x=y.find(_=>_.cookie_id===n&&_.item_id===h),p=(x==null?void 0:x.item_title)||h;return{name:ge(a,p),trigger_type:a,cookie_id:n,item_id:h,item_title:(x==null?void 0:x.item_title)||"",item_keyword:p,card_group_id:0,priority:100,enabled:!0,config_json:a==="review_missing_timeout"?de():"{}",actions:ye(a),variants:a==="review_missing_timeout"?[]:[be()]}},[y,s]),xe=r.useCallback(a=>{var h,x;const n=a.trigger_type||"order_paid";S({...a,trigger_type:n,config_json:n==="review_missing_timeout"?de(a.config_json):a.config_json||"{}",actions:(h=a.actions)!=null&&h.length?a.actions.map(p=>({...p})):ye(n,a.card_group_id),variants:(x=a.variants)!=null&&x.length?a.variants.map(p=>({...p})):n==="review_missing_timeout"?[]:[be()]}),j(!0)},[]);r.useEffect(()=>{if(!v)return;let a=!1;return(async()=>{d("automation"),c(v.cookieId),K(!0);try{const[h,x,p]=await Promise.all([zt(),at(),st().catch(g=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",g),[]))]);if(a)return;o(h),F(x),U(p);const _=h.find(g=>g.cookie_id===v.cookieId&&g.item_id===v.itemId&&g.trigger_type==="order_paid");if(_)xe(_);else{const g=x.find(q=>q.cookie_id===v.cookieId&&q.item_id===v.itemId);S({...J("order_paid",v.cookieId,v.itemId),item_title:(g==null?void 0:g.item_title)||"",item_keyword:(g==null?void 0:g.item_title)||v.itemId,name:ge("order_paid",(g==null?void 0:g.item_title)||v.itemId)}),j(!0)}}catch(h){console.error("打开商品自动化规则失败",h),alert("无法加载该商品的自动化规则")}finally{a||(K(!1),O==null||O())}})(),(()=>{a=!0})},[J,v,O,xe,d,o,U,F,K,c]);const Se=r.useCallback((a="order_paid")=>{if(!s){alert("请先选择账号");return}S(J(a)),j(!0)},[J,s]),fe=r.useCallback(a=>{var x,p,_,g,q;if(!l)return;const n=((p=(x=l.variants)==null?void 0:x.find(ee=>ee.card_id))==null?void 0:p.card_id)||((g=(_=l.actions)==null?void 0:_.find(ee=>ee.action_type==="send_card"))==null?void 0:g.card_id)||l.card_group_id||0,h=(b==null?void 0:b.item_title)||l.item_title||l.item_id||"";S({...l,trigger_type:a,name:He(l.name)?ge(a,h):l.name,card_group_id:n,config_json:a==="review_missing_timeout"?de(l.config_json):"{}",actions:ye(a,n),variants:a==="review_missing_timeout"?[]:(q=l.variants)!=null&&q.length?l.variants:[{...be(),card_id:n}]})},[l,b]),Re=r.useCallback(a=>{if(!l)return;const n=y.find(x=>x.cookie_id===(l.cookie_id||s)&&x.item_id===a),h=(n==null?void 0:n.item_title)||a;S({...l,item_id:a,item_title:(n==null?void 0:n.item_title)||"",item_keyword:h,name:He(l.name)?ge($,h):l.name})},[$,l,y,s]),ue=r.useCallback((a,n)=>{var x;if(!l)return;const h=L.map((p,_)=>_===a?{...p,...n}:p);S({...l,variants:h,card_group_id:((x=h[0])==null?void 0:x.card_id)||0})},[L,l]),Ae=r.useCallback(()=>{if(!l)return;const a=L[L.length-1];S({...l,variants:[...L,{...be(),spec_name:f&&(a==null?void 0:a.spec_name)||"",spec_value:f&&(a==null?void 0:a.spec_value)||""}]})},[L,l,f]),je=r.useCallback(async()=>{var p,_,g,q,ee;if(!l||B.submitting)return;const a=l.trigger_type||"order_paid";if(!l.cookie_id)return alert("请选择账号");const n=(p=l.variants)!=null&&p.length?l.variants:[];if(a!=="review_missing_timeout"){if(!n.length||n.some(N=>!N.card_id))return alert(a==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");if(f&&n.some(N=>!N.spec_name.trim()||!N.spec_value.trim()))return alert("多规格商品必须填写每一行的规格名称和规格值")}if(a==="review_missing_timeout"&&!(((g=(_=l.actions)==null?void 0:_.find(Me=>Me.action_type==="send_text"))==null?void 0:g.message_template)||"").trim())return alert("请填写求评价文案");const h=a==="review_missing_timeout"?[]:n.map(N=>({...N,spec_name:f?N.spec_name.trim():"",spec_value:f?N.spec_value.trim():"",delivery_count:Math.max(1,Number(N.delivery_count)||1),enabled:N.enabled!==!1}));le(ze(B));let x=!1;try{await Ye({...l,trigger_type:a,name:(l.name||"").trim()||ge(a,(b==null?void 0:b.item_title)||l.item_id||""),config_json:a==="review_missing_timeout"?de(l.config_json):l.config_json||"{}",actions:(q=l.actions)!=null&&q.length?l.actions:ye(a,((ee=h[0])==null?void 0:ee.card_id)||l.card_group_id||0),variants:h}),j(!1),await Promise.all([C(),se()]),alert("保存成功"),x=!0}catch(N){console.error("保存自动化规则失败:",N),alert("保存失败:"+N.message)}finally{le(N=>Ee(N,x))}},[B,l,f,C,se,b]),u=r.useCallback(async a=>{if(confirm("确定删除该自动化规则吗?"))try{await At(a),await C(),alert("删除成功")}catch(n){alert("删除失败:"+n.message)}},[C]),D=r.useCallback(async a=>{try{await Ye({...a,enabled:!a.enabled}),await C()}catch(n){alert("操作失败:"+n.message)}},[C]),w=r.useCallback(async(a,n)=>{if(confirm(n==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":n==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Mt(a,n),await C()}catch(x){alert("处理失败:"+x.message)}},[C]),H=r.useCallback(async(a,n)=>{if(confirm(n==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Pt(a,n),await C()}catch(h){alert("处理失败:"+h.message)}},[C]),M=r.useCallback(()=>{if(!s)return alert("请先选择账号");I({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),z(!0)},[s]),ne=r.useCallback(async()=>{var h,x,p;if(!k||!s||X.submitting)return;const a=k.type==="image"?!!((h=k.image_url)!=null&&h.trim()):!!((x=k.reply_content)!=null&&x.trim());if(!((p=k.keyword)!=null&&p.trim())||!a)return alert("请填写关键词和回复内容");E(ze(X));let n=!1;try{await $t({...k,match_type:"fuzzy",enabled:!0},s),z(!1),await T(),alert("保存成功"),n=!0}catch(_){alert("保存失败:"+_.message)}finally{E(_=>Ee(_,n))}},[k,T,X,s]),he=r.useCallback(async a=>{if(!(!s||!confirm("确定删除该回复规则吗?")))try{await It(a,s),await T(),alert("删除成功")}catch(n){alert("删除失败:"+n.message)}},[T,s]),ie=r.useCallback(async(a=s)=>{if(!a)return alert("请先选择账号");try{const n=await Lt(a);A({cookie_id:a,enabled:n.enabled,reply_content:n.reply_content,reply_once:n.reply_once,reply_image_url:n.reply_image_url||""})}catch{A({cookie_id:a,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}Z(!0)},[s]),ce=r.useCallback(async()=>{if(Y.submitting)return;if(!R.cookie_id)return alert("请先选择账号");if(R.enabled&&!R.reply_content.trim()&&!R.reply_image_url.trim())return alert("启用默认回复时,请填写回复内容或图片 URL");G(ze(Y));let a=!1;try{await Dt(R.cookie_id,{enabled:R.enabled,reply_content:R.reply_content,reply_once:R.reply_once,reply_image_url:R.reply_image_url}),Z(!1),await V(),alert("保存成功"),a=!0}catch(n){alert("保存失败:"+n.message)}finally{G(n=>Ee(n,a))}},[R,Y,V]),_e=r.useCallback(async a=>{if(confirm("确定删除该账号默认回复吗?"))try{await Ft(a),await V(),alert("删除成功")}catch(n){alert("删除失败:"+n.message)}},[V]),pe=r.useCallback(async a=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Tt(a),alert("清空成功")}catch(n){alert("清空失败:"+n.message)}},[]);return{showAutomationModal:P,setShowAutomationModal:j,showReplyModal:W,setShowReplyModal:z,showDefaultModal:ae,setShowDefaultModal:Z,automationSubmitState:B,replySubmitState:X,defaultReplySubmitState:Y,editingAutomationRule:l,setEditingAutomationRule:S,editingReplyRule:k,setEditingReplyRule:I,defaultForm:R,setDefaultForm:A,selectedRuleItem:b,isMultiSpecRule:f,currentTrigger:$,currentMeta:Q,reviewConfig:re,displayVariants:L,buildAutomationDraft:J,openAutomationRule:xe,openNewAutomationRule:Se,handleTriggerChange:fe,handleAutomationItemChange:Re,updateVariant:ue,appendDeliveryContent:Ae,handleSaveAutomationRule:je,handleDeleteAutomation:u,handleToggleAutomation:D,handleResolveRunIssue:w,handleResolveDeferredIssue:H,handleAddReplyRule:M,handleSaveReplyRule:ne,handleDeleteReply:he,openDefaultReplyModal:ie,handleSaveDefaultReply:ce,handleDeleteDefaultReply:_e,handleClearDefaultReplyRecords:pe}},Yt=({initialDeliveryTarget:s,onDeliveryTargetHandled:c})=>{var Ge,Je;const[d,y]=r.useState("automation"),[o,U]=r.useState(""),[F,K]=r.useState(""),[C,se]=r.useState(""),[T,V]=r.useState(""),[v,O]=r.useState("all"),[P,j]=r.useState(1),[W,z]=r.useState(10),ae=Ot({activeTab:d,selectedAccountId:o,automationTriggerFilter:T,automationStatusFilter:v,debouncedAutomationSearch:C,automationPage:P,automationPageSize:W,setSelectedAccountId:U,onAutomationPageChange:j}),{automationRules:Z,automationIssues:B,replyRules:le,defaultReplies:X,accounts:E,cards:Y,items:G,loading:l,setLoading:S,automationTotal:k,automationTotalPages:I,automationTriggerCounts:R,setAutomationRules:A,setCards:b,setItems:f,loadReferenceData:$,loadAutomationRules:Q,loadReplyRules:re,loadDefaultReplies:L,refresh:J}=ae,xe=Kt({selectedAccountId:o,setSelectedAccountId:U,setActiveTab:y,items:G,setAutomationRules:A,setCards:b,setItems:f,setLoading:S,loadAutomationRules:Q,loadReferenceData:$,loadReplyRules:re,loadDefaultReplies:L,initialDeliveryTarget:s,onDeliveryTargetHandled:c}),{showAutomationModal:Se,setShowAutomationModal:fe,showReplyModal:Re,setShowReplyModal:ue,showDefaultModal:Ae,setShowDefaultModal:je,editingAutomationRule:u,setEditingAutomationRule:D,editingReplyRule:w,setEditingReplyRule:H,defaultForm:M,setDefaultForm:ne,selectedRuleItem:he,isMultiSpecRule:ie,currentTrigger:ce,currentMeta:_e,reviewConfig:pe,displayVariants:me,openAutomationRule:a,openNewAutomationRule:n,handleTriggerChange:h,handleAutomationItemChange:x,updateVariant:p,appendDeliveryContent:_,handleSaveAutomationRule:g,handleDeleteAutomation:q,handleToggleAutomation:ee,handleResolveRunIssue:N,handleResolveDeferredIssue:Me,handleAddReplyRule:rt,handleSaveReplyRule:nt,handleDeleteReply:it,openDefaultReplyModal:Oe,handleSaveDefaultReply:ot,handleDeleteDefaultReply:dt,handleClearDefaultReplyRecords:ct}=xe;r.useEffect(()=>{const t=window.setTimeout(()=>{j(1),se(F.trim())},300);return(()=>window.clearTimeout(t))},[F]),r.useEffect(()=>{$().catch(t=>console.error("加载规则参考数据失败",t))},[$]),r.useEffect(()=>{J().catch(t=>console.error("刷新规则页面失败",t))},[J]);const Pe=r.useMemo(()=>Z.filter(t=>!o||t.cookie_id===o),[Z,o]),ve=r.useMemo(()=>Et(B,o),[B,o]),Be=r.useMemo(()=>E.filter(t=>!o||t.id===o),[E,o]),mt=r.useMemo(()=>{if(I<=1)return[];const t=Math.max(1,Math.min(P-2,I-4)),i=Math.min(I,t+4);return Array.from({length:i-t+1},(m,oe)=>t+oe)},[P,I]),$e=!!(F.trim()||T||v!=="all"),xt=()=>{K(""),se(""),V(""),O("all"),j(1)},ut=r.useMemo(()=>{const t=(u==null?void 0:u.cookie_id)||o;return G.filter(i=>i.cookie_id===t)},[u==null?void 0:u.cookie_id,G,o]),ht=d==="automation"?"新建自动化":d==="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:o,onChange:(t=>{U(t.target.value),j(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),E.map(t=>e.jsx("option",{value:t.id,children:Ce(t)},t.id))]}),e.jsxs("button",{onClick:J,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(Le,{className:`w-4 h-4 ${l?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:d==="automation"?(()=>n("order_paid")):d==="reply"?rt:(()=>void Oe()),disabled:!o,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(Ue,{className:"w-4 h-4"}),ht]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:Ke},{id:"reply",label:"关键词回复",icon:gt},{id:"default",label:"账号默认回复",icon:We}].map(t=>{const i=t.icon;return e.jsxs("button",{onClick:(()=>y(t.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${d===t.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(i,{className:"w-4 h-4"}),t.label]},t.id)})}),d==="automation"&&(ve.runs.length>0||ve.pending_tasks.length>0)&&e.jsx(Vt,{runs:ve.runs,pendingTasks:ve.pending_tasks,onResolveRun:((t,i)=>void N(t,i)),onResolveDeferredTask:((t,i)=>void Me(t,i))}),d==="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:ke.map(t=>{const i=te[t],m=i.icon;return e.jsx("button",{type:"button",onClick:(()=>n(t)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${et(i.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(m,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:i.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:i.description})]})]})},t)})})]}),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:["共 ",k," 条"]})]}),e.jsx("div",{className:"space-y-3",children:ke.map(t=>{const i=te[t],m=i.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(m,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:i.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:R[t]||0})]},t)})})]})]}),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(yt,{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:F,onChange:(t=>{K(t.target.value),j(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(ft,{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:T,onChange:(t=>{V(t.target.value),j(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:"全部自动化类型"}),ke.map(t=>e.jsx("option",{value:t,children:te[t].shortLabel},t))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:v,onChange:(t=>{O(t.target.value),j(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:"已禁用"})]}),$e&&e.jsx("button",{type:"button",onClick:xt,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(Ne,{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:["找到 ",k," 条规则"]}),l&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Le,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),l&&Pe.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(Le,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):Pe.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(Ke,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:$e?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:$e?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):Pe.map(t=>{const i=te[t.trigger_type],m=i.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 ${et(i.accent,!0)}`,children:e.jsx(m,{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:t.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Jt(t.enabled)}`,children:t.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:i.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:t.item_title||t.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:Gt(t)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>a(t)),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(De,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>ee(t)),className:`px-4 py-2 rounded-xl text-sm font-bold ${t.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:t.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>q(t.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(we,{className:"w-4 h-4"})})]})]})},t.id)}),k>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:["第 ",P," / ",Math.max(I,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:W,onChange:(t=>{z(Number(t.target.value)),j(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(t=>e.jsxs("option",{value:t,children:[t," 条/页"]},t))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:P<=1||l,onClick:(()=>j(t=>Math.max(1,t-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(jt,{className:"h-4 w-4"})}),mt.map(t=>e.jsx("button",{type:"button",disabled:l,onClick:(()=>j(t)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${t===P?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${t} 页`,"aria-current":t===P?"page":void 0,children:t},t)),e.jsx("button",{type:"button",disabled:P>=I||l,onClick:(()=>j(t=>Math.min(I,t+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(_t,{className:"h-4 w-4"})})]})]})]})]}),d==="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(Ve,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[le.map(t=>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:["“",t.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:t.type==="image"&&t.image_url?t.image_url:t.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:(()=>{H({...t}),ue(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(De,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>it(t.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(we,{className:"w-5 h-5"})})]})]},t.id)),le.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),d==="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(Ve,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Be.map(t=>{const i=X[t.id],m=!!(i!=null&&i.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 ${m?"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 ${m?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(We,{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:Ce(t)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${m?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:m?"已启用":"未启用"}),(i==null?void 0:i.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:m?i.reply_content||i.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 Oe(t.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(De,{className:"w-4 h-4"})}),m&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void ct(t.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 dt(t.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(we,{className:"w-5 h-5"})})]})]})]},t.id)}),Be.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),Se&&u&&Ie.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:u.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:_e.description})]}),e.jsx("button",{onClick:(()=>fe(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:ke.map(t=>{const i=te[t],m=i.icon,oe=ce===t;return e.jsx("button",{type:"button",onClick:(()=>h(t)),className:`w-full rounded-2xl p-4 text-left border transition-all ${oe?"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(m,{className:`w-5 h-5 mt-0.5 ${oe?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:i.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${oe?"text-gray-500":"text-gray-400"}`,children:i.description})]})]})},t)})}),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:_e.flow.map((t,i)=>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:i+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:t})]},t))})]})]}),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(vt,{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:u.name||"",onChange:(t=>D({...u,name:t.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:u.cookie_id||"",onChange:(t=>D({...u,cookie_id:t.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:"选择账号"}),E.map(t=>e.jsx("option",{value:t.id,children:Ce(t)},t.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:u.item_id||"",onChange:(t=>x(t.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),ut.map(t=>e.jsx("option",{value:t.item_id,children:t.item_title||t.item_id},`${t.cookie_id}-${t.item_id}`))]})]})]}),he&&ce!=="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:he.item_title||he.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${ie?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:ie?"多规格商品":"普通商品"}),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:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),ce!=="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(Nt,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:ce==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:ie?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:_,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(Ue,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:me.map((t,i)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${ie?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[ie&&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:t.spec_name,onChange:(m=>p(i,{spec_name:m.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:t.spec_value,onChange:(m=>p(i,{spec_value:m.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:t.card_id||"",onChange:(m=>p(i,{card_id:Number(m.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),Y.filter(m=>m.enabled&&m.type!=="api").map(m=>e.jsx("option",{value:m.id,children:m.name},m.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:t.delivery_count,onChange:(m=>p(i,{delivery_count:Math.max(1,Number(m.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:t.delay_override===!0,onChange:(m=>p(i,{delay_override:m.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),t.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:t.delay_seconds||0,onChange:(m=>p(i,{delay_seconds:Math.max(0,Number(m.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:t.delay_override?`本动作延时 ${t.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:me.length===1,onClick:(()=>D({...u,variants:me.filter((m,oe)=>oe!==i)})),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(we,{className:"w-4 h-4"})})]},t.id||i))})]}):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(tt,{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(pe.after_shipped_hours||72),onChange:(t=>D({...u,config_json:de(u.config_json,{after_shipped_hours:Math.max(1,Number(t.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(pe.repeat_interval_hours||24),onChange:(t=>D({...u,config_json:de(u.config_json,{repeat_interval_hours:Math.max(1,Number(t.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(pe.max_attempts||1),onChange:(t=>D({...u,config_json:de(u.config_json,{max_attempts:Math.max(1,Number(t.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:((Je=(Ge=u.actions)==null?void 0:Ge.find(t=>t.action_type==="send_text"))==null?void 0:Je.message_template)||"",onChange:(t=>{var i;return D({...u,actions:((i=u.actions)!=null&&i.length?u.actions:ye("review_missing_timeout")).map(m=>m.action_type==="send_text"?{...m,message_template:t.target.value}:m)})}),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:u.priority||100,onChange:(t=>D({...u,priority:Number(t.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:u.enabled!==!1,onChange:(t=>D({...u,enabled:t.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:(()=>fe(!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:g,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Re&&w&&Ie.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:w.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>ue(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:w.item_id||"",onChange:(t=>H({...w,item_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),G.filter(t=>!o||t.cookie_id===o).map(t=>e.jsx("option",{value:t.item_id,children:t.item_title||t.item_id},`${t.cookie_id}-${t.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:w.type||"text",onChange:(t=>{const i=t.target.value;H({...w,type:i,reply_content:i==="text"?w.reply_content:"",image_url:i==="image"?w.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:w.keyword||"",onChange:(t=>H({...w,keyword:t.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),w.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:w.image_url||"",onChange:(t=>H({...w,image_url:t.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:w.reply_content||"",onChange:(t=>H({...w,reply_content:t.target.value})),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>ue(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:nt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(wt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Ae&&Ie.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:(()=>je(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:M.cookie_id,onChange:(t=>ne({...M,cookie_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),E.map(t=>e.jsx("option",{value:t.id,children:Ce(t)},t.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:(()=>ne({...M,enabled:!M.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${M.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 ${M.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:M.reply_content,onChange:(t=>ne({...M,reply_content:t.target.value})),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:M.reply_image_url,onChange:(t=>ne({...M,reply_image_url:t.target.value})),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:M.reply_once,onChange:(t=>ne({...M,reply_once:t.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>je(!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:ot,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})};export{Yt as default}; diff --git a/internal/webui/static/assets/Rules-wDFwn1GF.js b/internal/webui/static/assets/Rules-wDFwn1GF.js deleted file mode 100644 index 9800d06..0000000 --- a/internal/webui/static/assets/Rules-wDFwn1GF.js +++ /dev/null @@ -1 +0,0 @@ -import{j as e,r as i,b as ke}from"./react-vendor-C_od1ZSF.js";import{h as At,K as at,a as lt,a7 as We,a8 as It,a9 as Mt,aa as Pt,Y as $t,ab as Lt,ac as Ft,ad as Tt,ae as Ze,af as Dt,ag as zt,ah as Et,ai as qt,aj as Ot,ak as Bt}from"./index-CFJ5pUjO.js";import{k as $e,ae as rt,af as Vt,m as Gt,R as Ce,N as Xe,Z as Ye,x as Jt,w as Qe,I as Ut,a1 as Kt,X as ue,V as Se,F as he,d as Wt,c as Zt,a6 as Xt,ag as Yt,r as He,ah as Qt}from"./icons-vendor-ThcsWkZG.js";const Re=(a,o)=>a.allowed_resolutions.includes(o),Ht=(a,o)=>({runs:a.runs.filter(d=>!o||d.cookie_id===o),pending_tasks:a.pending_tasks.filter(d=>!o||d.cookie_id===o)}),es=a=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[a]||"自动化异常",ts=({runs:a,pendingTasks:o,onResolveRun:d,onResolveDeferredTask:y})=>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($e,{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:[a.map(n=>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:["账号 ",n.cookie_id," · 订单 ",n.order_id||"-"," · 已记录发送 ",n.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:es(n.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:n.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Re(n,"continue")&&e.jsx("button",{onClick:(()=>d(n.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Re(n,"retry")&&e.jsx("button",{onClick:(()=>d(n.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Re(n,"cancel")&&e.jsx("button",{onClick:(()=>d(n.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${n.id}`)),o.map(n=>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:["账号 ",n.cookie_id," · 延迟任务重试已达 ",n.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:n.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>y(n.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>y(n.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${n.id}`))]})]}),Ae=()=>({submitting:!1,result:"idle"}),Ie=a=>a.submitting?a:{submitting:!0,result:"idle"},Me=(a,o)=>({submitting:!1,result:o?"success":"failure"}),et=a=>a+1,Pe=(a,o,d,y)=>a===o&&d===y,ss=a=>{const[o,d]=i.useState([]),[y,n]=i.useState({runs:[],pending_tasks:[]}),[Z,L]=i.useState([]),[ae,le]=i.useState({}),[re,X]=i.useState([]),[ne,q]=i.useState([]),[ie,v]=i.useState([]),[f,O]=i.useState(!1),B=i.useRef(0),Y=i.useRef(0),[oe,de]=i.useState(0),[ce,ge]=i.useState(0),[I,ye]=i.useState({}),N=i.useCallback(async()=>{const k=Promise.all([At(),at(),lt(),We()]),[C,j,M,S]=await k;X(C),q(j),v(M),le(S),a.setSelectedAccountId(G=>{var Q;return G||((Q=C[0])==null?void 0:Q.id)||""})},[a.setSelectedAccountId]),w=i.useCallback(async()=>{var S;const k=et(B.current);B.current=k;const C=It().catch(G=>(console.warn("加载自动化异常列表失败,不阻断规则展示",G),null)),j=await Mt({cookieId:a.selectedAccountId||void 0,triggerType:a.automationTriggerFilter,enabled:a.automationStatusFilter==="all"?void 0:a.automationStatusFilter==="enabled",search:a.debouncedAutomationSearch,page:a.automationPage,pageSize:a.automationPageSize});if(!Pe(k,B.current,a.selectedAccountId,a.selectedAccountId))return;d(j.data),de(j.total),ge(j.total_pages),ye(j.trigger_counts||{}),j.page!==a.automationPage&&((S=a.onAutomationPageChange)==null||S.call(a,j.page));const M=await C;Pe(k,B.current,a.selectedAccountId,a.selectedAccountId)&&M&&n(M)},[a.automationPage,a.automationPageSize,a.automationStatusFilter,a.automationTriggerFilter,a.debouncedAutomationSearch,a.onAutomationPageChange,a.selectedAccountId]),V=i.useCallback(async()=>{const k=et(Y.current);Y.current=k;const C=a.selectedAccountId;if(L([]),!C)return;const j=await Pt(C);Pe(k,Y.current,C,a.selectedAccountId)&&L(j)},[a.selectedAccountId]),F=i.useCallback(async()=>{le(await We())},[]),A=i.useCallback(async()=>{O(!0);try{a.activeTab==="automation"?await w():a.activeTab==="reply"?await V():await F()}finally{O(!1)}},[w,F,V,a.activeTab]);return{automationRules:o,automationIssues:y,replyRules:Z,defaultReplies:ae,accounts:re,cards:ne,items:ie,automationTotal:oe,automationTotalPages:ce,automationTriggerCounts:I,loading:f,setLoading:O,setAutomationRules:d,setCards:q,setItems:v,loadReferenceData:N,loadAutomationRules:w,loadReplyRules:V,loadDefaultReplies:F,refresh:A}},$={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:Gt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:Vt},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:rt}},pe=["order_paid","buyer_reviewed","review_missing_timeout"],as="亲,商品使用满意的话,麻烦给个评价,谢谢~",ee=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),nt=a=>{if(!a)return{};try{const o=JSON.parse(a);return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}catch{return{}}},E=(a,o={})=>{const d=nt(a);return JSON.stringify({after_shipped_hours:Number(d.after_shipped_hours||72),repeat_interval_hours:Number(d.repeat_interval_hours||24),max_attempts:Number(d.max_attempts||1),...o})},te=(a,o)=>{var y;const d=((y=$[a])==null?void 0:y.label)||"自动化规则";return o?`${d} - ${o}`:d},tt=a=>{const o=(a||"").trim();return o?Object.values($).some(d=>o===d.label||o.startsWith(`${d.label} -`)):!0},se=(a,o=0)=>{if(a==="review_missing_timeout")return[{action_type:"send_text",message_template:as,enabled:!0,sort_order:1}];const d={action_type:"send_card",card_id:o,delivery_count:1,enabled:!0,sort_order:1};return a==="order_paid"?[d,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[d]},ls=a=>{var d,y;if(a.trigger_type==="review_missing_timeout")return((y=(d=a.actions)==null?void 0:d.find(n=>n.action_type==="send_text"))==null?void 0:y.message_template)||"发送求评价文案";const o=(a.actions||[]).filter(n=>n.action_type==="send_card");return o.length?o.map(n=>n.card_name||`卡密 ${n.card_id}`).join(" / "):"未配置卡密库存"},st=(a,o=!1)=>{const d={blue:o?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:o?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:o?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return d[a]||d.blue},rs=a=>a?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",be=a=>(a==null?void 0:a.nickname)||(a==null?void 0:a.remark)||(a==null?void 0:a.id)||"未知账号",ns=a=>a===!0||a===1||a==="1",cs=({initialDeliveryTarget:a,onDeliveryTargetHandled:o})=>{var Je,Ue,Ke;const[d,y]=i.useState("automation"),[n,Z]=i.useState(""),[L,ae]=i.useState(""),[le,re]=i.useState(""),[X,ne]=i.useState(""),[q,ie]=i.useState("all"),[v,f]=i.useState(1),[O,B]=i.useState(10),Y=ss({activeTab:d,selectedAccountId:n,automationTriggerFilter:X,automationStatusFilter:q,debouncedAutomationSearch:le,automationPage:v,automationPageSize:O,setSelectedAccountId:Z,onAutomationPageChange:f}),{automationRules:oe,automationIssues:de,replyRules:ce,defaultReplies:ge,accounts:I,cards:ye,items:N,loading:w,setLoading:V,automationTotal:F,automationTotalPages:A,automationTriggerCounts:Le,setAutomationRules:k,setCards:C,setItems:j,loadReferenceData:M,loadAutomationRules:S,loadReplyRules:G,loadDefaultReplies:Q,refresh:fe}=Y,[it,J]=i.useState(!1),[ot,H]=i.useState(!1),[dt,me]=i.useState(!1),[Fe,Te]=i.useState(Ae),[De,ze]=i.useState(Ae),[Ee,qe]=i.useState(Ae),[l,b]=i.useState(null),[m,T]=i.useState(null),[x,D]=i.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""});I.find(t=>t.id===n),i.useEffect(()=>{const t=window.setTimeout(()=>{f(1),re(L.trim())},300);return(()=>window.clearTimeout(t))},[L]),i.useEffect(()=>{M().catch(t=>console.error("加载规则参考数据失败",t))},[M]),i.useEffect(()=>{fe().catch(t=>console.error("刷新规则页面失败",t))},[fe]);const je=i.useMemo(()=>oe.filter(t=>!n||t.cookie_id===n),[oe,n]),xe=i.useMemo(()=>Ht(de,n),[de,n]),Oe=i.useMemo(()=>I.filter(t=>!n||t.id===n),[I,n]),ct=i.useMemo(()=>{if(A<=1)return[];const t=Math.max(1,Math.min(v-2,A-4)),s=Math.min(A,t+4);return Array.from({length:s-t+1},(r,c)=>t+c)},[v,A]),_e=!!(L.trim()||X||q!=="all"),mt=()=>{ae(""),re(""),ne(""),ie("all"),f(1)},xt=i.useMemo(()=>{const t=(l==null?void 0:l.cookie_id)||n;return N.filter(s=>s.cookie_id===t)},[l==null?void 0:l.cookie_id,N,n]),_=i.useMemo(()=>{if(!(!(l!=null&&l.cookie_id)||!(l!=null&&l.item_id)))return N.find(t=>t.cookie_id===l.cookie_id&&t.item_id===l.item_id)},[l==null?void 0:l.cookie_id,l==null?void 0:l.item_id,N]),R=ns(_==null?void 0:_.is_multi_spec),U=(l==null?void 0:l.trigger_type)||"order_paid",Be=$[U],ve=nt(l==null?void 0:l.config_json),Ne=i.useCallback((t="order_paid",s=n,r="")=>{const c=N.find(p=>p.cookie_id===s&&p.item_id===r),h=(c==null?void 0:c.item_title)||r;return{name:te(t,h),trigger_type:t,cookie_id:s,item_id:r,item_title:(c==null?void 0:c.item_title)||"",item_keyword:h,card_group_id:0,priority:100,enabled:!0,config_json:t==="review_missing_timeout"?E():"{}",actions:se(t),variants:t==="review_missing_timeout"?[]:[ee()]}},[N,n]),we=i.useCallback(t=>{var r,c;const s=t.trigger_type||"order_paid";b({...t,trigger_type:s,config_json:s==="review_missing_timeout"?E(t.config_json):t.config_json||"{}",actions:(r=t.actions)!=null&&r.length?t.actions.map(h=>({...h})):se(s,t.card_group_id),variants:(c=t.variants)!=null&&c.length?t.variants.map(h=>({...h})):s==="review_missing_timeout"?[]:[ee()]}),J(!0)},[]);i.useEffect(()=>{if(!a)return;let t=!1;return(async()=>{y("automation"),Z(a.cookieId),V(!0);try{const[r,c,h]=await Promise.all([$t(),lt(),at().catch(u=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",u),[]))]);if(t)return;k(r),j(c),C(h);const p=r.find(u=>u.cookie_id===a.cookieId&&u.item_id===a.itemId&&u.trigger_type==="order_paid");if(p)we(p);else{const u=c.find(P=>P.cookie_id===a.cookieId&&P.item_id===a.itemId);b({...Ne("order_paid",a.cookieId,a.itemId),item_title:(u==null?void 0:u.item_title)||"",item_keyword:(u==null?void 0:u.item_title)||a.itemId,name:te("order_paid",(u==null?void 0:u.item_title)||a.itemId)}),J(!0)}}catch(r){console.error("打开商品自动化规则失败",r),alert("无法加载该商品的自动化规则")}finally{t||(V(!1),o==null||o())}})(),(()=>{t=!0})},[Ne,a,o,we]);const Ve=(t="order_paid")=>{if(!n){alert("请先选择账号");return}b(Ne(t)),J(!0)},ut=t=>{var c,h,p,u,P;if(!l)return;const s=((h=(c=l.variants)==null?void 0:c.find(W=>W.card_id))==null?void 0:h.card_id)||((u=(p=l.actions)==null?void 0:p.find(W=>W.action_type==="send_card"))==null?void 0:u.card_id)||l.card_group_id||0,r=(_==null?void 0:_.item_title)||l.item_title||l.item_id||"";b({...l,trigger_type:t,name:tt(l.name)?te(t,r):l.name,card_group_id:s,config_json:t==="review_missing_timeout"?E(l.config_json):"{}",actions:se(t,s),variants:t==="review_missing_timeout"?[]:(P=l.variants)!=null&&P.length?l.variants:[{...ee(),card_id:s}]})},ht=t=>{if(!l)return;const s=N.find(c=>c.cookie_id===(l.cookie_id||n)&&c.item_id===t),r=(s==null?void 0:s.item_title)||t;b({...l,item_id:t,item_title:(s==null?void 0:s.item_title)||"",item_keyword:r,name:tt(l.name)?te(U,r):l.name})},z=(Je=l==null?void 0:l.variants)!=null&&Je.length?l.variants:[ee()],K=(t,s)=>{var c;if(!l)return;const r=z.map((h,p)=>p===t?{...h,...s}:h);b({...l,variants:r,card_group_id:((c=r[0])==null?void 0:c.card_id)||0})},pt=()=>{if(!l)return;const t=z[z.length-1];b({...l,variants:[...z,{...ee(),spec_name:R&&(t==null?void 0:t.spec_name)||"",spec_value:R&&(t==null?void 0:t.spec_value)||""}]})},bt=async()=>{var h,p,u,P,W;if(!l||Fe.submitting)return;const t=l.trigger_type||"order_paid";if(!l.cookie_id){alert("请选择账号");return}const s=(h=l.variants)!=null&&h.length?l.variants:[];if(t!=="review_missing_timeout"){if(!s.length||s.some(g=>!g.card_id)){alert(t==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");return}if(R&&s.some(g=>!g.spec_name.trim()||!g.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}}if(t==="review_missing_timeout"&&!(((u=(p=l.actions)==null?void 0:p.find(Rt=>Rt.action_type==="send_text"))==null?void 0:u.message_template)||"").trim()){alert("请填写求评价文案");return}const r=t==="review_missing_timeout"?[]:s.map(g=>({...g,spec_name:R?g.spec_name.trim():"",spec_value:R?g.spec_value.trim():"",delivery_count:Math.max(1,Number(g.delivery_count)||1),enabled:g.enabled!==!1}));Te(Ie(Fe));let c=!1;try{await Ze({...l,trigger_type:t,name:(l.name||"").trim()||te(t,(_==null?void 0:_.item_title)||l.item_id||""),config_json:t==="review_missing_timeout"?E(l.config_json):l.config_json||"{}",actions:(P=l.actions)!=null&&P.length?l.actions:se(t,((W=r[0])==null?void 0:W.card_id)||l.card_group_id||0),variants:r}),J(!1),await Promise.all([S(),M()]),alert("保存成功"),c=!0}catch(g){console.error("保存自动化规则失败:",g),alert("保存失败:"+g.message)}finally{Te(g=>Me(g,c))}},gt=async t=>{if(confirm("确定删除该自动化规则吗?"))try{await Dt(t),await S(),alert("删除成功")}catch(s){alert("删除失败:"+s.message)}},yt=async t=>{try{await Ze({...t,enabled:!t.enabled}),await S()}catch(s){alert("操作失败:"+s.message)}},ft=async(t,s)=>{if(confirm(s==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":s==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Tt(t,s),await S()}catch(c){alert("处理失败:"+c.message)}},jt=async(t,s)=>{if(confirm(s==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Ft(t,s),await S()}catch(r){alert("处理失败:"+r.message)}},_t=()=>{if(!n){alert("请先选择账号");return}T({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),H(!0)},vt=async()=>{var r,c,h;if(!m||!n||De.submitting)return;const t=m.type==="image"?!!((r=m.image_url)!=null&&r.trim()):!!((c=m.reply_content)!=null&&c.trim());if(!((h=m.keyword)!=null&&h.trim())||!t){alert("请填写关键词和回复内容");return}ze(Ie(De));let s=!1;try{await Ot({...m,match_type:"fuzzy",enabled:!0},n),H(!1),await G(),alert("保存成功"),s=!0}catch(p){alert("保存失败:"+p.message)}finally{ze(p=>Me(p,s))}},Nt=async t=>{if(!(!n||!confirm("确定删除该回复规则吗?")))try{await zt(t,n),await G(),alert("删除成功")}catch(s){alert("删除失败:"+s.message)}},Ge=async(t=n)=>{if(!t){alert("请先选择账号");return}try{const s=await Lt(t);D({cookie_id:t,enabled:s.enabled,reply_content:s.reply_content,reply_once:s.reply_once,reply_image_url:s.reply_image_url||""})}catch{D({cookie_id:t,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}me(!0)},wt=async()=>{if(Ee.submitting)return;if(!x.cookie_id){alert("请先选择账号");return}if(x.enabled&&!x.reply_content.trim()&&!x.reply_image_url.trim()){alert("启用默认回复时,请填写回复内容或图片 URL");return}qe(Ie(Ee));let t=!1;try{await Bt(x.cookie_id,{enabled:x.enabled,reply_content:x.reply_content,reply_once:x.reply_once,reply_image_url:x.reply_image_url}),me(!1),await Q(),alert("保存成功"),t=!0}catch(s){alert("保存失败:"+s.message)}finally{qe(s=>Me(s,t))}},kt=async t=>{if(confirm("确定删除该账号默认回复吗?"))try{await qt(t),await Q(),alert("删除成功")}catch(s){alert("删除失败:"+s.message)}},Ct=async t=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Et(t),alert("清空成功")}catch(s){alert("清空失败:"+s.message)}},St=d==="automation"?"新建自动化":d==="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:n,onChange:(t=>{Z(t.target.value),f(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),I.map(t=>e.jsx("option",{value:t.id,children:be(t)},t.id))]}),e.jsxs("button",{onClick:fe,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(Ce,{className:`w-4 h-4 ${w?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:d==="automation"?(()=>Ve("order_paid")):d==="reply"?_t:(()=>void Ge()),disabled:!n,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(Xe,{className:"w-4 h-4"}),St]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:Ye},{id:"reply",label:"关键词回复",icon:Jt},{id:"default",label:"账号默认回复",icon:Qe}].map(t=>{const s=t.icon;return e.jsxs("button",{onClick:(()=>y(t.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${d===t.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(s,{className:"w-4 h-4"}),t.label]},t.id)})}),d==="automation"&&(xe.runs.length>0||xe.pending_tasks.length>0)&&e.jsx(ts,{runs:xe.runs,pendingTasks:xe.pending_tasks,onResolveRun:((t,s)=>void ft(t,s)),onResolveDeferredTask:((t,s)=>void jt(t,s))}),d==="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:pe.map(t=>{const s=$[t],r=s.icon;return e.jsx("button",{type:"button",onClick:(()=>Ve(t)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${st(s.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(r,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:s.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:s.description})]})]})},t)})})]}),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:["共 ",F," 条"]})]}),e.jsx("div",{className:"space-y-3",children:pe.map(t=>{const s=$[t],r=s.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(r,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:s.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:Le[t]||0})]},t)})})]})]}),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(Ut,{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:L,onChange:(t=>{ae(t.target.value),f(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(Kt,{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:X,onChange:(t=>{ne(t.target.value),f(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:"全部自动化类型"}),pe.map(t=>e.jsx("option",{value:t,children:$[t].shortLabel},t))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:q,onChange:(t=>{ie(t.target.value),f(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:"已禁用"})]}),_e&&e.jsx("button",{type:"button",onClick:mt,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(ue,{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:["找到 ",F," 条规则"]}),w&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Ce,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),w&&je.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(Ce,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):je.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(Ye,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:_e?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:_e?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):je.map(t=>{const s=$[t.trigger_type],r=s.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 ${st(s.accent,!0)}`,children:e.jsx(r,{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:t.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${rs(t.enabled)}`,children:t.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:s.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:t.item_title||t.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:ls(t)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>we(t)),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(Se,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>yt(t)),className:`px-4 py-2 rounded-xl text-sm font-bold ${t.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:t.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>gt(t.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(he,{className:"w-4 h-4"})})]})]})},t.id)}),F>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:["第 ",v," / ",Math.max(A,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:O,onChange:(t=>{B(Number(t.target.value)),f(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(t=>e.jsxs("option",{value:t,children:[t," 条/页"]},t))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:v<=1||w,onClick:(()=>f(t=>Math.max(1,t-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(Wt,{className:"h-4 w-4"})}),ct.map(t=>e.jsx("button",{type:"button",disabled:w,onClick:(()=>f(t)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${t===v?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${t} 页`,"aria-current":t===v?"page":void 0,children:t},t)),e.jsx("button",{type:"button",disabled:v>=A||w,onClick:(()=>f(t=>Math.min(A,t+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(Zt,{className:"h-4 w-4"})})]})]})]})]}),d==="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($e,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[ce.map(t=>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:["“",t.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:t.type==="image"&&t.image_url?t.image_url:t.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:(()=>{T({...t}),H(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(Se,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>Nt(t.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(he,{className:"w-5 h-5"})})]})]},t.id)),ce.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),d==="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($e,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Oe.map(t=>{const s=ge[t.id],r=!!(s!=null&&s.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 ${r?"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 ${r?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(Qe,{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:be(t)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${r?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:r?"已启用":"未启用"}),(s==null?void 0:s.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:r?s.reply_content||s.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 Ge(t.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(Se,{className:"w-4 h-4"})}),r&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void Ct(t.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 kt(t.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(he,{className:"w-5 h-5"})})]})]})]},t.id)}),Oe.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),it&&l&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:l.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:Be.description})]}),e.jsx("button",{onClick:(()=>J(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(ue,{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:pe.map(t=>{const s=$[t],r=s.icon,c=U===t;return e.jsx("button",{type:"button",onClick:(()=>ut(t)),className:`w-full rounded-2xl p-4 text-left border transition-all ${c?"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(r,{className:`w-5 h-5 mt-0.5 ${c?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:s.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${c?"text-gray-500":"text-gray-400"}`,children:s.description})]})]})},t)})}),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:Be.flow.map((t,s)=>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:s+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:t})]},t))})]})]}),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(Xt,{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:l.name||"",onChange:(t=>b({...l,name:t.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:l.cookie_id||"",onChange:(t=>b({...l,cookie_id:t.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:"选择账号"}),I.map(t=>e.jsx("option",{value:t.id,children:be(t)},t.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:l.item_id||"",onChange:(t=>ht(t.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),xt.map(t=>e.jsx("option",{value:t.item_id,children:t.item_title||t.item_id},`${t.cookie_id}-${t.item_id}`))]})]})]}),_&&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:_.item_title||_.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${R?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:R?"多规格商品":"普通商品"}),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(Yt,{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:R?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:pt,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(Xe,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:z.map((t,s)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${R?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[R&&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:t.spec_name,onChange:(r=>K(s,{spec_name:r.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:t.spec_value,onChange:(r=>K(s,{spec_value:r.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:t.card_id||"",onChange:(r=>K(s,{card_id:Number(r.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),ye.filter(r=>r.enabled&&r.type!=="api").map(r=>e.jsx("option",{value:r.id,children:r.name},r.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:t.delivery_count,onChange:(r=>K(s,{delivery_count:Math.max(1,Number(r.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:t.delay_override===!0,onChange:(r=>K(s,{delay_override:r.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),t.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:t.delay_seconds||0,onChange:(r=>K(s,{delay_seconds:Math.max(0,Number(r.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:t.delay_override?`本动作延时 ${t.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:z.length===1,onClick:(()=>b({...l,variants:z.filter((r,c)=>c!==s)})),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(he,{className:"w-4 h-4"})})]},t.id||s))})]}):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(rt,{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(ve.after_shipped_hours||72),onChange:(t=>b({...l,config_json:E(l.config_json,{after_shipped_hours:Math.max(1,Number(t.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(ve.repeat_interval_hours||24),onChange:(t=>b({...l,config_json:E(l.config_json,{repeat_interval_hours:Math.max(1,Number(t.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(ve.max_attempts||1),onChange:(t=>b({...l,config_json:E(l.config_json,{max_attempts:Math.max(1,Number(t.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:((Ke=(Ue=l.actions)==null?void 0:Ue.find(t=>t.action_type==="send_text"))==null?void 0:Ke.message_template)||"",onChange:(t=>{var s;return b({...l,actions:((s=l.actions)!=null&&s.length?l.actions:se("review_missing_timeout")).map(r=>r.action_type==="send_text"?{...r,message_template:t.target.value}:r)})}),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:l.priority||100,onChange:(t=>b({...l,priority:Number(t.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:l.enabled!==!1,onChange:(t=>b({...l,enabled:t.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:(()=>J(!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:bt,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),ot&&m&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:m.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>H(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ue,{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:m.item_id||"",onChange:(t=>T({...m,item_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),N.filter(t=>!n||t.cookie_id===n).map(t=>e.jsx("option",{value:t.item_id,children:t.item_title||t.item_id},`${t.cookie_id}-${t.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:m.type||"text",onChange:(t=>{const s=t.target.value;T({...m,type:s,reply_content:s==="text"?m.reply_content:"",image_url:s==="image"?m.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:m.keyword||"",onChange:(t=>T({...m,keyword:t.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),m.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:m.image_url||"",onChange:(t=>T({...m,image_url:t.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:m.reply_content||"",onChange:(t=>T({...m,reply_content:t.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:(()=>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:vt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Qt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),dt&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:(()=>me(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(ue,{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:x.cookie_id,onChange:(t=>D({...x,cookie_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),I.map(t=>e.jsx("option",{value:t.id,children:be(t)},t.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:(()=>D({...x,enabled:!x.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${x.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 ${x.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:x.reply_content,onChange:(t=>D({...x,reply_content:t.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:x.reply_image_url,onChange:(t=>D({...x,reply_image_url:t.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:x.reply_once,onChange:(t=>D({...x,reply_once:t.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>me(!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:wt,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)]})};export{cs as default}; diff --git a/internal/webui/static/assets/Settings-BjYjZFI9.js b/internal/webui/static/assets/Settings-D-qaPnxf.js similarity index 99% rename from internal/webui/static/assets/Settings-BjYjZFI9.js rename to internal/webui/static/assets/Settings-D-qaPnxf.js index 5ebb6d8..5ba3c5d 100644 --- a/internal/webui/static/assets/Settings-BjYjZFI9.js +++ b/internal/webui/static/assets/Settings-D-qaPnxf.js @@ -1 +1 @@ -import{r as a,j as e}from"./react-vendor-C_od1ZSF.js";import{a2 as ce,a3 as ie,a4 as de,a5 as xe,a6 as ue}from"./index-CFJ5pUjO.js";import{b as pe,R as se,aa as me,p as he,u as q,v as D,ab as ge,s as ye,h as te,ac as ae,ad as be,r as fe}from"./icons-vendor-ThcsWkZG.js";const le="https://dashscope.aliyuncs.com/compatible-mode/v1",we=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],je=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","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"]),ve=s=>Object.fromEntries(Object.entries(s).filter(([c,m])=>!je.has(c)&&m!==void 0&&m!==null)),Ne=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",g=(s,c,m)=>s===c&&!m.aborted,O=s=>s instanceof Error&&s.message==="请求已取消",K=(s,c)=>s instanceof Error?s.message:c,_e=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,c)=>({type:s,text:c}),Se=()=>{const[s,c]=a.useState(null),[m,k]=a.useState(!1),[I,x]=a.useState(""),[N,E]=a.useState(!1),[P,_]=a.useState(""),[S,b]=a.useState([]),[f,A]=a.useState(!1),[M,i]=a.useState(""),[$,w]=a.useState(!1),[U,L]=a.useState(!1),[z,d]=a.useState(!1),[y,F]=a.useState(!1),[G,J]=a.useState(!1),[V,j]=a.useState(!1),[R,h]=a.useState(null),[t,X]=a.useState(()=>_e()),[re,W]=a.useState("idle"),Z=a.useRef(null),ee=a.useRef(null),u=a.useRef(0),Y=a.useRef(null);ee.current=s;const C=a.useCallback(()=>{var n;(n=Y.current)==null||n.abort();const r=new AbortController;return Y.current=r,u.current+=1,{controller:r,sequence:u.current}},[]),B=a.useCallback(async(r,n=!1,l)=>{const o=r||ee.current,p=(o==null?void 0:o.ai_api_url)||(o==null?void 0:o.ai_base_url)||le;A(!0),i("");try{const v=await ce(p,(o==null?void 0:o.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;b(v),w(n&&v.length>0),!(o!=null&&o.ai_model)&&v.length>0&&c(Q=>Q&&{...Q,ai_model:v[0]})}catch(v){if(l!=null&&l.aborted||O(v))return;b([]),w(!1),i(K(v,"读取模型失败"))}finally{l!=null&&l.aborted||A(!1)}},[]),H=a.useCallback(()=>{const{controller:r,sequence:n}=C();k(!0),W("loading"),x(""),Promise.all([ie({signal:r.signal}),de({signal:r.signal})]).then(([l,o])=>{g(u.current,n,r.signal)&&(c(l),o.username&&X(p=>({...p,new_username:o.username||""})),B(l,!1,r.signal),W("success"))}).catch(l=>{!g(u.current,n,r.signal)||O(l)||(c(null),x(K(l,"加载配置失败")),W("error"))}).finally(()=>{g(u.current,n,r.signal)&&k(!1)})},[C,B]);a.useEffect(()=>(H(),(()=>{var r;return(r=Y.current)==null?void 0:r.abort()})),[H]),a.useEffect(()=>{const r=n=>{var l;(l=Z.current)!=null&&l.contains(n.target)||w(!1)};return document.addEventListener("mousedown",r),(()=>document.removeEventListener("mousedown",r))},[]);const ne=a.useCallback(async()=>{if(!s||N)return;const{controller:r,sequence:n}=C();E(!0),_("");try{if(await xe(ve(s),{signal:r.signal}),!g(u.current,n,r.signal))return;window.alert("系统配置已保存")}catch(l){if(!g(u.current,n,r.signal)||O(l))return;_(K(l,"保存配置失败"))}finally{g(u.current,n,r.signal)&&E(!1)}},[C,N,s]),oe=a.useCallback(async r=>{r.preventDefault(),h(null);const n=Ne(t);if(n){h(T("error",n));return}const{controller:l,sequence:o}=C();j(!0);try{const p=await ue({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!g(u.current,o,l.signal))return;if(!p.success){h(T("error",p.message||"登录凭据更新失败"));return}h(T("success",p.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(p){if(!g(u.current,o,l.signal)||O(p))return;h(T("error",K(p,"登录凭据更新失败")))}finally{g(u.current,o,l.signal)&&j(!1)}},[C,t]);return{settings:s,loading:m,loadError:I,saving:N,saveError:P,aiModels:S,modelsLoading:f,modelError:M,modelDropdownOpen:$,showApiKey:U,showCaptchaSecret:z,showCurrentPassword:y,showNewPassword:G,credentialsSaving:V,credentialsMessage:R,credentials:t,requestStatus:re,modelPickerRef:Z,loadSettings:H,loadAIModels:((r,n)=>void B(r,n)),handleSave:ne,handleCredentialsSave:oe,setSettings:c,setModelDropdownOpen:w,setShowApiKey:L,setShowCaptchaSecret:d,setShowCurrentPassword:F,setShowNewPassword:J,setCredentials:X,setCredentialsMessage:h}},Ae=()=>{const{settings:s,loading:c,loadError:m,saving:k,saveError:I,aiModels:x,modelsLoading:N,modelError:E,modelDropdownOpen:P,showApiKey:_,showCaptchaSecret:S,showCurrentPassword:b,showNewPassword:f,credentialsSaving:A,credentialsMessage:M,credentials:i,modelPickerRef:$,loadSettings:w,loadAIModels:U,handleSave:L,handleCredentialsSave:z,setSettings:d,setModelDropdownOpen:y,setShowApiKey:F,setShowCaptchaSecret:G,setShowCurrentPassword:J,setShowNewPassword:V,setCredentials:j}=Se();if(!s)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[m||(c?"加载配置中...":"暂无配置"),!c&&m&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:w,children:"重新加载"})})]});const R=s.ai_model||"",h=x;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(pe,{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:w,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(se,{className:"w-4 h-4"}),"刷新"]})]}),I&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:I}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>{}),children:"重试保存"})]}),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(me,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:(t=>d({...s,log_level:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:we.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:(t=>d({...s,log_format:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:(t=>d({...s,renewal_log_retention_days:parseInt(t.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(he,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||le,onChange:(t=>d({...s,ai_api_url:t.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:_?"text":"password",value:s.ai_api_key||"",onChange:(t=>d({...s,ai_api_key:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:s.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>F(!_)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:_?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{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:$,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:R,onFocus:(()=>x.length>0&&y(!0)),onChange:(t=>{d({...s,ai_model:t.target.value}),x.length>0&&y(!0)}),onKeyDown:(t=>{t.key==="Escape"&&y(!1),t.key==="ArrowDown"&&x.length>0&&y(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>x.length>0&&y(t=>!t)),disabled:x.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(ge,{className:`w-4 h-4 transition-transform ${P?"rotate-180":""}`})}),P&&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:h.length>0?h.map(t=>e.jsxs("button",{type:"button",onClick:(()=>{d({...s,ai_model:t}),y(!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:t}),t===R&&e.jsx(ye,{className:"w-4 h-4 shrink-0 text-brand"})]},t)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>U(void 0,!0)),disabled:N,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(se,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"读取模型"]})]}),E?e.jsx("p",{className:"text-xs text-red-500",children:E}):e.jsx("p",{className:"text-xs text-gray-500",children:x.length>0?`已从当前 API 地址读取到 ${x.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(te,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:(t=>d({...s,"captcha.remote_service_url":t.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:S?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:(t=>d({...s,"captcha.remote_secret_key":t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:s["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>G(!S)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:S?"隐藏秘钥":"显示秘钥",children:S?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(t=>d({...s,"captcha.remote_pass_cookies":t.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(ae,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:z,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(be,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:i.new_username,onChange:(t=>j({...i,new_username:t.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:b?"text":"password",value:i.current_password,onChange:(t=>j({...i,current_password:t.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:(()=>J(!b)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:b?"隐藏密码":"显示密码",children:b?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{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:f?"text":"password",value:i.new_password,onChange:(t=>j({...i,new_password:t.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:(()=>V(!f)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:f?"隐藏密码":"显示密码",children:f?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{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:f?"text":"password",value:i.confirm_password,onChange:(t=>j({...i,confirm_password:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),M&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${M.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(te,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:M.text})]}),e.jsxs("button",{type:"submit",disabled:A||!i.new_username||!i.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(ae,{className:"w-4 h-4"}),A?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:L,disabled:k,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(fe,{className:"w-6 h-6"}),k?"保存中...":"保存所有配置"]})})]})};export{Ae as default}; +import{r as a,j as e}from"./react-vendor-C_od1ZSF.js";import{a2 as ce,a3 as ie,a4 as de,a5 as xe,a6 as ue}from"./index-CsLZwESi.js";import{b as pe,R as se,aa as me,p as he,u as q,v as D,ab as ge,s as ye,h as te,ac as ae,ad as be,r as fe}from"./icons-vendor-ThcsWkZG.js";const le="https://dashscope.aliyuncs.com/compatible-mode/v1",we=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],je=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","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"]),ve=s=>Object.fromEntries(Object.entries(s).filter(([c,m])=>!je.has(c)&&m!==void 0&&m!==null)),Ne=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",g=(s,c,m)=>s===c&&!m.aborted,O=s=>s instanceof Error&&s.message==="请求已取消",K=(s,c)=>s instanceof Error?s.message:c,_e=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,c)=>({type:s,text:c}),Se=()=>{const[s,c]=a.useState(null),[m,k]=a.useState(!1),[I,x]=a.useState(""),[N,E]=a.useState(!1),[P,_]=a.useState(""),[S,b]=a.useState([]),[f,A]=a.useState(!1),[M,i]=a.useState(""),[$,w]=a.useState(!1),[U,L]=a.useState(!1),[z,d]=a.useState(!1),[y,F]=a.useState(!1),[G,J]=a.useState(!1),[V,j]=a.useState(!1),[R,h]=a.useState(null),[t,X]=a.useState(()=>_e()),[re,W]=a.useState("idle"),Z=a.useRef(null),ee=a.useRef(null),u=a.useRef(0),Y=a.useRef(null);ee.current=s;const C=a.useCallback(()=>{var n;(n=Y.current)==null||n.abort();const r=new AbortController;return Y.current=r,u.current+=1,{controller:r,sequence:u.current}},[]),B=a.useCallback(async(r,n=!1,l)=>{const o=r||ee.current,p=(o==null?void 0:o.ai_api_url)||(o==null?void 0:o.ai_base_url)||le;A(!0),i("");try{const v=await ce(p,(o==null?void 0:o.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;b(v),w(n&&v.length>0),!(o!=null&&o.ai_model)&&v.length>0&&c(Q=>Q&&{...Q,ai_model:v[0]})}catch(v){if(l!=null&&l.aborted||O(v))return;b([]),w(!1),i(K(v,"读取模型失败"))}finally{l!=null&&l.aborted||A(!1)}},[]),H=a.useCallback(()=>{const{controller:r,sequence:n}=C();k(!0),W("loading"),x(""),Promise.all([ie({signal:r.signal}),de({signal:r.signal})]).then(([l,o])=>{g(u.current,n,r.signal)&&(c(l),o.username&&X(p=>({...p,new_username:o.username||""})),B(l,!1,r.signal),W("success"))}).catch(l=>{!g(u.current,n,r.signal)||O(l)||(c(null),x(K(l,"加载配置失败")),W("error"))}).finally(()=>{g(u.current,n,r.signal)&&k(!1)})},[C,B]);a.useEffect(()=>(H(),(()=>{var r;return(r=Y.current)==null?void 0:r.abort()})),[H]),a.useEffect(()=>{const r=n=>{var l;(l=Z.current)!=null&&l.contains(n.target)||w(!1)};return document.addEventListener("mousedown",r),(()=>document.removeEventListener("mousedown",r))},[]);const ne=a.useCallback(async()=>{if(!s||N)return;const{controller:r,sequence:n}=C();E(!0),_("");try{if(await xe(ve(s),{signal:r.signal}),!g(u.current,n,r.signal))return;window.alert("系统配置已保存")}catch(l){if(!g(u.current,n,r.signal)||O(l))return;_(K(l,"保存配置失败"))}finally{g(u.current,n,r.signal)&&E(!1)}},[C,N,s]),oe=a.useCallback(async r=>{r.preventDefault(),h(null);const n=Ne(t);if(n){h(T("error",n));return}const{controller:l,sequence:o}=C();j(!0);try{const p=await ue({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!g(u.current,o,l.signal))return;if(!p.success){h(T("error",p.message||"登录凭据更新失败"));return}h(T("success",p.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(p){if(!g(u.current,o,l.signal)||O(p))return;h(T("error",K(p,"登录凭据更新失败")))}finally{g(u.current,o,l.signal)&&j(!1)}},[C,t]);return{settings:s,loading:m,loadError:I,saving:N,saveError:P,aiModels:S,modelsLoading:f,modelError:M,modelDropdownOpen:$,showApiKey:U,showCaptchaSecret:z,showCurrentPassword:y,showNewPassword:G,credentialsSaving:V,credentialsMessage:R,credentials:t,requestStatus:re,modelPickerRef:Z,loadSettings:H,loadAIModels:((r,n)=>void B(r,n)),handleSave:ne,handleCredentialsSave:oe,setSettings:c,setModelDropdownOpen:w,setShowApiKey:L,setShowCaptchaSecret:d,setShowCurrentPassword:F,setShowNewPassword:J,setCredentials:X,setCredentialsMessage:h}},Ae=()=>{const{settings:s,loading:c,loadError:m,saving:k,saveError:I,aiModels:x,modelsLoading:N,modelError:E,modelDropdownOpen:P,showApiKey:_,showCaptchaSecret:S,showCurrentPassword:b,showNewPassword:f,credentialsSaving:A,credentialsMessage:M,credentials:i,modelPickerRef:$,loadSettings:w,loadAIModels:U,handleSave:L,handleCredentialsSave:z,setSettings:d,setModelDropdownOpen:y,setShowApiKey:F,setShowCaptchaSecret:G,setShowCurrentPassword:J,setShowNewPassword:V,setCredentials:j}=Se();if(!s)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[m||(c?"加载配置中...":"暂无配置"),!c&&m&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:w,children:"重新加载"})})]});const R=s.ai_model||"",h=x;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(pe,{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:w,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(se,{className:"w-4 h-4"}),"刷新"]})]}),I&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:I}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>{}),children:"重试保存"})]}),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(me,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:(t=>d({...s,log_level:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:we.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:(t=>d({...s,log_format:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:(t=>d({...s,renewal_log_retention_days:parseInt(t.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(he,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||le,onChange:(t=>d({...s,ai_api_url:t.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:_?"text":"password",value:s.ai_api_key||"",onChange:(t=>d({...s,ai_api_key:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:s.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>F(!_)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:_?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{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:$,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:R,onFocus:(()=>x.length>0&&y(!0)),onChange:(t=>{d({...s,ai_model:t.target.value}),x.length>0&&y(!0)}),onKeyDown:(t=>{t.key==="Escape"&&y(!1),t.key==="ArrowDown"&&x.length>0&&y(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>x.length>0&&y(t=>!t)),disabled:x.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(ge,{className:`w-4 h-4 transition-transform ${P?"rotate-180":""}`})}),P&&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:h.length>0?h.map(t=>e.jsxs("button",{type:"button",onClick:(()=>{d({...s,ai_model:t}),y(!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:t}),t===R&&e.jsx(ye,{className:"w-4 h-4 shrink-0 text-brand"})]},t)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>U(void 0,!0)),disabled:N,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(se,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"读取模型"]})]}),E?e.jsx("p",{className:"text-xs text-red-500",children:E}):e.jsx("p",{className:"text-xs text-gray-500",children:x.length>0?`已从当前 API 地址读取到 ${x.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(te,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:(t=>d({...s,"captcha.remote_service_url":t.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:S?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:(t=>d({...s,"captcha.remote_secret_key":t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:s["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>G(!S)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:S?"隐藏秘钥":"显示秘钥",children:S?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(t=>d({...s,"captcha.remote_pass_cookies":t.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(ae,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:z,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(be,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:i.new_username,onChange:(t=>j({...i,new_username:t.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:b?"text":"password",value:i.current_password,onChange:(t=>j({...i,current_password:t.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:(()=>J(!b)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:b?"隐藏密码":"显示密码",children:b?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{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:f?"text":"password",value:i.new_password,onChange:(t=>j({...i,new_password:t.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:(()=>V(!f)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:f?"隐藏密码":"显示密码",children:f?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{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:f?"text":"password",value:i.confirm_password,onChange:(t=>j({...i,confirm_password:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),M&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${M.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(te,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:M.text})]}),e.jsxs("button",{type:"submit",disabled:A||!i.new_username||!i.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(ae,{className:"w-4 h-4"}),A?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:L,disabled:k,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(fe,{className:"w-6 h-6"}),k?"保存中...":"保存所有配置"]})})]})};export{Ae as default}; diff --git a/internal/webui/static/assets/index-CFJ5pUjO.js b/internal/webui/static/assets/index-CsLZwESi.js similarity index 97% rename from internal/webui/static/assets/index-CFJ5pUjO.js rename to internal/webui/static/assets/index-CsLZwESi.js index c781086..c48e249 100644 --- a/internal/webui/static/assets/index-CFJ5pUjO.js +++ b/internal/webui/static/assets/index-CsLZwESi.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-COpr9cLo.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-ThcsWkZG.js","assets/charts-vendor-BxxJOyEX.js","assets/vendor-D-Edl3pr.js","assets/AccountList-Bqs514En.js","assets/OrderList-vw6Kdzf7.js","assets/CardList-CRgXJn6O.js","assets/ItemList-DE9qcEo5.js","assets/Settings-BjYjZFI9.js","assets/Rules-wDFwn1GF.js","assets/Notifications-BlIacKXE.js","assets/Chat-VbA-SOcX.js"])))=>i.map(i=>d[i]); -import{j as n,r as p,c as ee,d as xe}from"./react-vendor-C_od1ZSF.js";import{L as we,U as je,M as Le,C as Ne,B as Se,S as ke,Z as Ce,a as Ae,b as Ee,G as Z,c as $e,d as De,e as Ie,f as D,g as H,h as I,A as G,i as Oe}from"./icons-vendor-ThcsWkZG.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=s(a);fetch(a.href,i)}})();const te="ydisks.sidebar.v1",Te=()=>{try{return window.localStorage.getItem(te)==="collapsed"}catch{return!1}},Pe=e=>{try{window.localStorage.setItem(te,e?"collapsed":"expanded")}catch{}},Re=({className:e="w-full h-full text-white"})=>n.jsx("svg",{className:e,viewBox:"0 0 256 256","aria-hidden":"true",children:n.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:n.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"})})}),R=({sizeClass:e="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>n.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[n.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),n.jsxs("div",{className:`relative ${e} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[n.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[n.jsx("defs",{children:n.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[n.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),n.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),n.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)"})]}),n.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:n.jsx(Re,{className:t})})]})]}),ze="modulepreload",qe=function(e){return"/static/"+e},Q={},L=function(t,s,r){let a=Promise.resolve();if(s&&s.length>0){let o=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=o(s.map(d=>{if(d=qe(d),d in Q)return;Q[d]=!0;const u=d.endsWith(".css"),m=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":ze,u||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((x,v)=>{h.addEventListener("load",x),h.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return a.then(o=>{for(const c of o||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})},Me=3e4,Be=10*6e4;let O=!1;const se=()=>{O||typeof window>"u"||(O=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{O=!1}))},Fe=e=>{if(!e)return"";const t=new URLSearchParams;for(const[r,a]of Object.entries(e))a!=null&&t.set(r,String(a));const s=t.toString();return s?`?${s}`:""},$=async(e,t,s={})=>{var d;const r=Fe(s.params),a=`${t}${r}`,i=ae(s.signal,s.timeoutMs??Me);let o;try{o=await fetch(a,{method:e,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(u){throw i.signal.aborted?new Error((d=s.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):u}finally{i.cleanup()}const l=(o.headers.get("content-type")||"").includes("application/json");if(!o.ok){o.status===401&&!s.skipAuthLogout&&se();const u=l?await o.json().catch(()=>{}):await o.text().catch(()=>{}),m=ne(u,o.status);throw new Error(m)}return l?await o.json():await o.text()},g=async(e,t,s)=>$("GET",e,{params:t,...s}),y=async(e,t,s)=>$("POST",e,{body:t,...s}),b=async(e,t,s)=>$("PUT",e,{body:t,...s}),j=async(e,t,s)=>$("DELETE",e,{params:t,...s}),S=async(e,t,s={})=>{var l;const r=ae(s.signal,s.timeoutMs??Be);let a;try{a=await fetch(e,{method:"POST",credentials:"include",signal:r.signal,body:t})}catch(d){throw r.signal.aborted?new Error((l=s.signal)!=null&&l.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{r.cleanup()}const c=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>{}):await a.text().catch(()=>{});if(!a.ok){a.status===401&&se();const d=ne(c,a.status),u=new Error(d);throw u.payload=c,u}return c},ae=(e,t)=>{const s=new AbortController,r=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?r():e==null||e.addEventListener("abort",r,{once:!0});const a=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,t));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(a),e==null||e.removeEventListener("abort",r)}}},Ve=e=>{if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.code=="string"&&typeof t.message=="string"},ne=(e,t)=>typeof e=="string"?e:Ve(e)?e.message:`请求失败: ${t}`,E=e=>{const t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${t}-${s}-${r}`},q=(e,t)=>{const s=new Date(e);return s.setHours(12,0,0,0),s.setDate(s.getDate()+t),s},z=(e,t)=>({startDate:E(q(e,-(t-1))),endDate:E(e)}),jt=(e,t=new Date,s="",r="")=>{if(e==="custom"&&s&&r){if(s>r)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:r}}return e==="yesterday"?z(q(t,-1),1):z(t,e==="3days"?3:e==="30days"?30:e==="today"?1:7)},Lt=e=>{const t=new Date(`${e.startDate}T12:00:00`),s=new Date(`${e.endDate}T12:00:00`),r=Math.round((s.getTime()-t.getTime())/864e5)+1,a=q(t,-1);return z(a,r)},Je=e=>{const t={...e},s=["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"];for(const r of s){const a=`${r}_configured`;a in t&&(t[a]=t[a]===!0||t[a]==="true")}if("renewal_log_retention_days"in t){const r=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(r)?r:10}return t},Ue=async e=>y("/api/v1/session/login",e,{skipAuthLogout:!0}),Ke=async e=>y("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Ye=async e=>g("/api/v1/session",void 0,e),Ze=async e=>g("/health",void 0,e),He=async()=>y("/api/v1/session/logout",{}),Nt=async(e,t)=>b("/api/v1/session/credentials",e,t),Ge=(e,t)=>{const s=e.avatar_url||"";if(!s)return"";try{const r=new URL(s,window.location.origin);return r.hostname.endsWith("alicdn.com")&&r.searchParams.set("_v",t),r.toString()}catch{return s}},St=async e=>{const t=await g("/api/v1/accounts/details",void 0,e),s=Date.now().toString();return t.map(r=>({id:r.id,value:"",enabled:r.enabled,auto_confirm:r.auto_confirm,remark:r.remark,pause_duration:r.pause_duration,paused_until:Number(r.paused_until||0),paused:r.paused===!0,username:r.username||"",login_password:"",show_browser:r.show_browser===!0||r.show_browser===1||r.show_browser==="1"||r.show_browser==="true",nickname:r.nickname||r.remark||`账号 ${r.id.substring(0,6)}`,avatar_url:Ge(r,s),profile_error:r.profile_error||"",ai_enabled:!1,auto_rate_enabled:r.auto_rate_enabled,rate_content:r.rate_content||"不错的买家,交易愉快",auto_polish_enabled:r.auto_polish_enabled,polish_time:r.polish_time||"03:00",last_rate_scan_at:Number(r.last_rate_scan_at||0),last_polish_date:r.last_polish_date||"",last_polish_at:Number(r.last_polish_at||0)}))},kt=async(e,t)=>g(`/api/v1/account-tasks/${e}`,void 0,t),Ct=async(e,t,s)=>b(`/api/v1/account-tasks/${e}`,t,s),At=async(e,t,s)=>y(`/api/v1/account-tasks/${e}/run`,{task_type:t},{timeoutMs:12e4,...s}),Et=async(e,t,s,r=!1)=>{const a=await g("/api/v1/chat/sessions",{account_id:e,cursor:t,refresh:r?1:void 0},r?{timeoutMs:6e4,...s}:s);return{sessions:a.sessions||[],has_more:a.has_more===!0,next_cursor:a.next_cursor}},$t=async(e,t,s,r,a)=>{const i=await g("/api/v1/chat/messages",{account_id:e,chat_id:t,cursor:s,before_id:r},a);return{messages:i.messages||[],has_more:i.has_more===!0,next_cursor:i.next_cursor,session:i.session}},Dt=async(e,t)=>y("/api/v1/chat/messages",e,t),It=async(e,t)=>{const s=new FormData;return Object.entries(e).forEach(([r,a])=>s.append(r,a)),S("/api/v1/chat/images",s,{timeoutMs:12e4,...t})},Ot=async(e,t,s)=>y("/api/v1/chat/read",{account_id:e,chat_id:t},s),Tt=async e=>g("/api/v1/accounts/runtime-status",void 0,e),Pt=async e=>y("/api/v1/qr-login/generate",void 0,{...e,timeoutMs:(e==null?void 0:e.timeoutMs)??13e4}),Rt=async(e,t)=>g(`/api/v1/qr-login/check/${e}`,void 0,{signal:t,timeoutMs:1e4}),zt=async(e,t)=>y(`/api/v1/qr-login/complete-verification/${e}`,{target_account_id:t||""}),qt=async(e,t)=>b(`/api/v1/accounts/${e}/status`,{enabled:t}),Mt=async e=>j(`/api/v1/accounts/${e}`),Bt=async(e,t,s)=>b(`/api/v1/accounts/${e}/pause-duration`,{pause_duration:t},s),Ft=async(e,t,s)=>b(`/api/v1/accounts/${e}/settings`,t,s),Vt=async(e,t)=>g(`/api/v1/accounts/${e}/long-login`,void 0,t),Jt=async(e,t,s)=>b(`/api/v1/accounts/${e}/long-login`,{enabled:t},s),Ut=async(e,t)=>y("/api/v1/password-login",e,t),Kt=async(e,t)=>g(`/api/v1/password-login/check/${e}`,void 0,{signal:t,timeoutMs:1e4}),Yt=async(e,t)=>j(`/api/v1/password-login/cancel/${e}`,void 0,t),Zt=async e=>y(`/api/v1/accounts/${e}/refresh-profile`,{}),Ht=async e=>g("/api/v1/settings/ai-reply",void 0,e),re=e=>{const t=String(e||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Gt=async(e,t,s=1,r=20,a,i)=>{const o={page:s,page_size:r};e&&(o.cookie_id=e),t&&t!=="all"&&(o.status=t),a!=null&&a.trim()&&(o.search=a.trim());const c=await g("/api/v1/orders",o,i),d=(c.orders||c.data||[]).map(u=>({...u,id:u.id||u.order_id,status:re(u.status||u.order_status),quantity:Number(u.quantity||1)}));return{success:!0,data:d,total:c.total||d.length,page:c.page||s,page_size:c.page_size||r,total_pages:c.total_pages||1}},Qt=async(e,t)=>b(`/api/v1/orders/${e}`,t),Wt=async e=>j(`/api/v1/orders/${e}`),Xt=async(e,t,s)=>{const r=new FormData;e&&r.append("cookie_id",e),t&&r.append("status",t);const a=await S("/api/v1/orders/refresh",r,s),i=180;let o=0;try{for(;o{const m=()=>{globalThis.clearTimeout(h),u(new Error("请求已取消"))},h=globalThis.setTimeout(()=>{var x;(x=s==null?void 0:s.signal)==null||x.removeEventListener("abort",m),d()},l);s!=null&&s.signal&&(s.signal.aborted?m():s.signal.addEventListener("abort",m,{once:!0}))}),o+=1}}finally{}throw new Error("订单刷新任务等待超时")},es=async e=>y(`/api/v1/orders/${e}/refresh`),ts=async(e,t)=>y("/api/v1/orders/manual-ship",{order_ids:e,ship_mode:t}),ss=async(e,t)=>e instanceof FormData?S("/api/v1/orders/import",e,t):y("/api/v1/orders/import",e,t),as=async e=>g("/api/v1/analytics/dashboard",void 0,e),ns=async(e=7,t)=>{let s;if(typeof e=="number"){const r=new Date,a=new Date;a.setDate(a.getDate()-e),s={start_date:E(a),end_date:E(r)}}else s=e;return g("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},t)},rs=async(e,t)=>{const s=await g("/api/v1/analytics/orders/valid",{start_date:e.start_date,end_date:e.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()},t),a=(Array.isArray(s)?s:s.orders||[]).map(i=>({...i,id:i.id||i.order_id,status:re(i.status||i.order_status),quantity:Number(i.quantity||1)}));return{orders:a,total:Array.isArray(s)?a.length:Number(s.total??a.length),truncated:Array.isArray(s)?!1:s.truncated===!0}},Qe=e=>{let t=e.api_config;if(typeof t=="string"&&t.trim())try{t=JSON.parse(t)}catch{t=void 0}return{...e,api_config:t||void 0}},ie=e=>({...e,api_config:e.api_config?JSON.stringify(e.api_config):""}),is=async e=>{const t=await g("/api/v1/cards",void 0,e);return(Array.isArray(t)?t:t.cards||[]).map(Qe)},os=async e=>y("/api/v1/cards",ie(e)),cs=async(e,t)=>b(`/api/v1/cards/${e}`,ie(t)),ls=async e=>j(`/api/v1/cards/${e}`),ds=async(e,t)=>{const s=new FormData;return s.append("file",e),S("/api/v1/cards/batch",s,t)},us=async(e,t,s)=>y(`/api/v1/cards/${e}/append-data`,{content:t},s),T=e=>e===!0||e===1||e==="1",ps=async(e,t)=>{const s=await g("/api/v1/items",void 0,t);return(Array.isArray(s)?s:s.items||[]).map(a=>({...a,id:a.id||`${a.cookie_id}-${a.item_id}`,is_multi_spec:T(a.is_multi_spec),is_multi_qty_ship:T(a.is_multi_qty_ship??a.multi_quantity_delivery),multi_quantity_delivery:T(a.multi_quantity_delivery??a.is_multi_qty_ship)}))},gs=async e=>y("/api/v1/items/get-all-from-account",{cookie_id:e}),ys=async(e,t)=>j(`/api/v1/items/${e}/${t}`),ms=async(e,t)=>y(`/api/v1/items/${e}`,t),fs=async e=>{const t=new FormData;t.set("cookie_id",e.cookie_id),t.set("title",e.title),t.set("description",e.description),t.set("price",e.price),t.set("original_price",e.original_price||""),t.set("quantity",String(e.quantity)),t.set("postage_mode",e.postage_mode),t.set("postage",e.postage||""),e.location&&t.set("location",JSON.stringify(e.location));for(const s of e.images)t.append("images",s);return S("/api/v1/items/publish",t)},hs=async(e,t)=>y("/api/v1/items/publish-categories/recommend",{cookie_id:e,keyword:t}),_s=async e=>{const t=new FormData;return t.set("file",e.file),e.imagesZip&&t.set("images_zip",e.imagesZip),e.defaultCookieId&&t.set("default_cookie_id",e.defaultCookieId),t.set("fallback_category_id",e.fallbackCategory.catId),t.set("fallback_category_name",e.fallbackCategory.catName),t.set("fallback_channel_category_id",e.fallbackCategory.channelCatId||""),t.set("fallback_tb_category_id",e.fallbackCategory.tbCatId||""),e.location&&t.set("location",JSON.stringify(e.location)),S("/api/v1/items/publish-batches/preview",t)},vs=async e=>y("/api/v1/items/publish-batches",{preview_id:e}),bs=async e=>g(`/api/v1/items/publish-batches/${e}`),xs=async(e=20)=>{const t=await g("/api/v1/items/publish-batches",{limit:e});return Array.isArray(t)?t:t.batches||[]},ws=async e=>j(`/api/v1/items/publish-batches/${e}`),js=async e=>y(`/api/v1/items/publish-batches/${e}/cancel`,{}),Ls=async e=>y(`/api/v1/items/publish-batches/${e}/retry-failed`,{}),Ns=async(e,t,s)=>b(`/api/v1/items/${e}/${t}`,s),oe=e=>e.map(t=>{var s,r;return{id:String(t.id),name:t.name||"",trigger_type:t.trigger_type||"order_paid",item_keyword:t.item_title||t.item_id||"",cookie_id:t.cookie_id||"",item_id:t.item_id||"",item_title:t.item_title||"",card_group_id:Number(((s=(t.actions||[]).find(a=>a.action_type==="send_card"))==null?void 0:s.card_id)||0),card_group_name:((r=(t.actions||[]).find(a=>a.action_type==="send_card"))==null?void 0:r.card_name)||"",priority:t.priority||100,enabled:t.enabled||!1,config_json:t.config_json||"{}",actions:(t.actions||[]).map(a=>({id:a.id?String(a.id):void 0,action_type:a.action_type,card_id:Number(a.card_id||0),card_name:a.card_name||"",delivery_count:Number(a.delivery_count||1),message_template:a.message_template||"",delay_seconds:Number(a.delay_seconds||0),config_json:a.config_json||"{}",enabled:a.enabled!==!1,sort_order:Number(a.sort_order||0)})),variants:(t.actions||[]).filter(a=>a.action_type==="send_card").map(a=>{let i={};try{i=JSON.parse(a.config_json||"{}")}catch{}return{id:a.id?String(a.id):void 0,spec_name:i.spec_name||"",spec_value:i.spec_value||"",card_id:Number(a.card_id||0),card_name:a.card_name||"",delivery_count:Number(a.delivery_count||1),enabled:a.enabled!==!1,delay_override:i.delay_override===!0,delay_seconds:Number(a.delay_seconds||0),config_json:a.config_json||"{}"}})}}),Ss=async()=>{const e=await g("/api/v1/automation-rules"),t=Array.isArray(e)?e:e.data||[];return oe(t)},ks=async({cookieId:e,triggerType:t,enabled:s,search:r,page:a=1,pageSize:i=10}={})=>{const o=await g("/api/v1/automation-rules",{page:a,page_size:i,cookie_id:e||void 0,trigger_type:t||void 0,enabled:s,search:(r==null?void 0:r.trim())||void 0}),c=oe(Array.isArray(o)?o:o.data||[]);return{success:!0,data:c,total:Number(Array.isArray(o)?c.length:o.total??c.length),page:Number(Array.isArray(o)?a:o.page??a),page_size:Number(Array.isArray(o)?i:o.page_size??i),total_pages:Number(Array.isArray(o)?c.length?1:0:o.total_pages??(c.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(Array.isArray(o)?{}:o.trigger_counts||{}).map(([l,d])=>[l,Number(d)]))}},We=(e,t)=>{if(e!=="order_paid")return t.map((a,i)=>({...a,sort_order:a.sort_order||i+1}));const s=t.filter(a=>a.action_type==="send_card").map((a,i)=>({...a,sort_order:i+1})),r=t.filter(a=>a.action_type!=="send_card"&&a.action_type!=="confirm_shipment");return[...s,...r.map((a,i)=>({...a,sort_order:s.length+i+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:s.length+r.length+1}]},Cs=async e=>{const t=e.trigger_type||"order_paid",r=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[t]||"自动化规则",e.item_title||e.item_id||e.cookie_id||""].filter(Boolean).join(" - "),a=(e.actions||[]).filter(l=>l.action_type!=="send_card"&&l.action_type!=="confirm_shipment"),i=e.variants&&e.variants.length>0?[...e.variants.map((l,d)=>({action_type:"send_card",card_id:l.card_id,delivery_count:l.delivery_count||1,enabled:l.enabled!==!1,sort_order:d+1,delay_seconds:l.delay_seconds||0,config_json:JSON.stringify({spec_name:l.spec_name||"",spec_value:l.spec_value||"",delay_override:l.delay_override===!0})})),...a]:e.actions&&e.actions.length>0?e.actions:[{action_type:"send_card",card_id:e.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],o=We(t,i),c={cookie_id:e.cookie_id||"",item_id:e.item_id||"",name:(e.name||"").trim()||r||"自动化规则",trigger_type:t,enabled:e.enabled??!0,priority:e.priority||100,config_json:e.config_json||"{}",actions:o.map((l,d)=>({action_type:l.action_type,card_id:l.card_id||0,delivery_count:l.delivery_count||1,message_template:l.message_template||"",delay_seconds:l.delay_seconds||0,config_json:l.config_json||"{}",enabled:l.enabled!==!1,sort_order:l.sort_order||d+1}))};return e.id?b(`/api/v1/automation-rules/${e.id}`,c):y("/api/v1/automation-rules",c)},As=async e=>j(`/api/v1/automation-rules/${e}`),Es=async()=>{const e=await g("/api/v1/automation-issues");return{runs:Array.isArray(e==null?void 0:e.runs)?e.runs:[],pending_tasks:Array.isArray(e==null?void 0:e.pending_tasks)?e.pending_tasks:[]}},$s=async(e,t)=>y(`/api/v1/automation-runs/${e}/resolve`,{resolution:t}),Ds=async(e,t)=>y(`/api/v1/automation-pending-tasks/${e}/resolve`,{resolution:t}),Xe=e=>({id:String((e==null?void 0:e.id)||""),keyword:(e==null?void 0:e.keyword)||"",reply:(e==null?void 0:e.reply)||"",item_id:(e==null?void 0:e.item_id)||"",type:(e==null?void 0:e.type)==="image"?"image":"text",image_url:(e==null?void 0:e.image_url)||""}),et=async e=>{const t=await g(`/api/v1/reply-rules/${e}/typed`);return Array.isArray(t)?t.map(Xe):[]},Is=async e=>e?(await et(e)).map(s=>({id:s.id,keyword:s.keyword||"",reply_content:s.reply||"",match_type:"fuzzy",enabled:!0,item_id:s.item_id||"",type:s.type==="image"?"image":"text",image_url:s.image_url||""})):[],Os=async(e,t)=>{const s=e.type||"text",r={keyword:e.keyword||"",reply:s==="text"&&e.reply_content||"",item_id:e.item_id||"",type:s,image_url:s==="image"&&e.image_url||""};return e.id?b(`/api/v1/reply-rules/${t}/typed/${e.id}`,r):y(`/api/v1/reply-rules/${t}/items`,r)},Ts=async(e,t)=>j(`/api/v1/reply-rules/${t}/typed/${e}`),tt=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),st=e=>{if("values"in e||"secrets"in e)return e;const t={},s={};for(const r of Object.entries(e)){const[a,i]=r;i!=null&&(tt.has(a)?s[a]=i===""?{action:"clear"}:{action:"replace",value:String(i)}:t[a]=i)}return Object.keys(s).length>0?{values:t,secrets:s}:t},Ps=async e=>{const t=await g("/api/v1/settings/system",void 0,e);return Je(t.data||t)},Rs=async(e,t)=>{const s=st(e);return b("/api/v1/settings/system",s,t)},zs=async(e,t)=>g(`/api/v1/settings/ai-reply/${e}`,void 0,t),qs=async(e,t,s)=>{const r={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return b(`/api/v1/settings/ai-reply/${e}`,r,s)},Ms=async(e,t="",s)=>(await y("/api/v1/settings/ai-models",{base_url:e,api_key:t},s)).models||[],at=e=>{if(Array.isArray(e))return e.filter(Boolean);if(typeof e!="string"||!e.trim())return[];try{const t=JSON.parse(e);if(Array.isArray(t))return t.filter(Boolean)}catch{}return e.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ce=e=>{const t=Array.from(new Set((e||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Bs=async e=>({success:!0,data:(await g("/api/v1/notifications/channels",void 0,e)||[]).map(r=>{let a;try{a=typeof r.config=="string"?JSON.parse(r.config):r.config}catch{a={}}return{id:String(r.id),name:r.name,type:r.type==="ding_talk"?"dingtalk":r.type==="lark"?"feishu":r.type,config:a,event_types:at(r.event_types),enabled:r.enabled,created_at:r.created_at,updated_at:r.updated_at}})}),Fs=async(e,t)=>y("/api/v1/notifications/channels",{...e,config:JSON.stringify(e.config),event_types:ce(e.event_types)},t),Vs=async(e,t,s)=>{const r={...t};return"config"in t&&(r.config=JSON.stringify(t.config)),"event_types"in t&&(r.event_types=ce(t.event_types)),b(`/api/v1/notifications/channels/${e}`,r,s)},Js=async(e,t)=>j(`/api/v1/notifications/channels/${e}`,void 0,t),Us=async(e,t)=>{const s=await g(`/api/v1/notifications/accounts/${e}/bindings`,void 0,t);return(s==null?void 0:s.channel_ids)||[]},Ks=async(e,t)=>y(`/api/v1/notifications/channels/${e}/test`,{},t),Ys=async()=>g("/api/v1/default-replies"),Zs=async e=>{const t=await g(`/api/v1/default-replies/${e}`);return{cookie_id:e,enabled:t.enabled||!1,reply_content:t.reply_content||"",reply_once:t.reply_once||!1,reply_image_url:t.reply_image_url||""}},Hs=async(e,t)=>b(`/api/v1/default-replies/${e}`,{enabled:t.enabled??!1,reply_content:t.reply_content||"",reply_once:t.reply_once??!1,reply_image_url:t.reply_image_url||""}),Gs=async e=>j(`/api/v1/default-replies/${e}`),Qs=async e=>y(`/api/v1/default-replies/${e}/clear-records`,{}),nt=({activeTab:e,isAdmin:t=!1,collapsed:s,onToggleCollapsed:r,onNavigate:a,onLogout:i})=>{const[o,c]=p.useState({version:"dev",commit:"unknown"});p.useEffect(()=>{const u=new AbortController;return Ze({signal:u.signal}).then(m=>c({version:String(m.version||"dev"),commit:String(m.commit||"unknown")})).catch(m=>{m instanceof DOMException&&m.name}),(()=>u.abort())},[]);const l=[{id:"dashboard",icon:we,label:"仪表盘"},{id:"accounts",icon:je,label:"账号管理"},{id:"chat",icon:Le,label:"在线聊天"},{id:"cards",icon:Ne,label:"卡密库存"},{id:"items",icon:Se,label:"商品列表"},{id:"orders",icon:ke,label:"订单管理"},{id:"rules",icon:Ce,label:"自动化规则"},{id:"notifications",icon:Ae,label:"通知设置"},...t?[{id:"settings",icon:Ee,label:"系统与AI"}]:[]],d=/^\d+\.\d+\.\d+$/.test(o.version)?`v${o.version}`:o.version;return n.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 ${s?"w-16":"w-64"}`,children:[n.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${s?"justify-center px-2":"gap-3 px-5"}`,children:[n.jsx(R,{sizeClass:"h-10 w-10"}),!s&&n.jsxs("div",{className:"min-w-0 leading-tight",children:[n.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),n.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),n.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${s?"px-2":"px-3"}`,"aria-label":"主导航",children:l.map(u=>{const m=u.icon,h=e===u.id;return n.jsx(ee.Fragment,{children:n.jsxs("button",{type:"button",title:s?u.label:void 0,"aria-label":u.label,"aria-current":h?"page":void 0,onClick:(()=>a(u.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${s?"justify-center":"gap-3 px-3.5"} ${h?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[n.jsx(m,{className:`h-[19px] w-[19px] shrink-0 ${h?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!s&&n.jsx("span",{className:"truncate text-sm font-bold",children:u.label}),h&&!s&&n.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},u.id)})}),n.jsxs("div",{children:[n.jsx("div",{title:s?`版本 ${o.version} · ${o.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${s?"flex justify-center px-1":"px-6"}`,children:s?n.jsx(Z,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${o.version}`}):n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[n.jsx(Z,{className:"h-3.5 w-3.5"}),"运行版本"]}),n.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[n.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:d}),n.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:o.commit})]})]})}),n.jsxs("div",{className:`space-y-2 p-2 ${s?"":"p-3"}`,children:[n.jsxs("button",{type:"button",onClick:r,title:s?"展开侧边栏":"收起侧边栏","aria-label":s?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${s?"justify-center":"gap-3 px-3"}`,children:[s?n.jsx($e,{className:"h-5 w-5"}):n.jsx(De,{className:"h-5 w-5"}),!s&&n.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),n.jsxs("button",{type:"button",onClick:i,title:s?"退出登录":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 ${s?"justify-center":"gap-3 px-3"}`,children:[n.jsx(Ie,{className:"h-5 w-5"}),!s&&n.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},P=p.lazy(()=>L(()=>import("./Dashboard-COpr9cLo.js"),__vite__mapDeps([0,1,2,3,4,5]))),rt=p.lazy(()=>L(()=>import("./AccountList-Bqs514En.js"),__vite__mapDeps([6,1,3]))),it=p.lazy(()=>L(()=>import("./OrderList-vw6Kdzf7.js"),__vite__mapDeps([7,1,3,2]))),ot=p.lazy(()=>L(()=>import("./CardList-CRgXJn6O.js"),__vite__mapDeps([8,1,3]))),ct=p.lazy(()=>L(()=>import("./ItemList-DE9qcEo5.js"),__vite__mapDeps([9,1,3]))),lt=p.lazy(()=>L(()=>import("./Settings-BjYjZFI9.js"),__vite__mapDeps([10,1,3]))),dt=p.lazy(()=>L(()=>import("./Rules-wDFwn1GF.js"),__vite__mapDeps([11,1,3]))),ut=p.lazy(()=>L(()=>import("./Notifications-BlIacKXE.js"),__vite__mapDeps([12,1,3]))),pt=p.lazy(()=>L(()=>import("./Chat-VbA-SOcX.js"),__vite__mapDeps([13,1,3]))),gt=()=>n.jsx("div",{className:"flex min-h-[24rem] items-center justify-center",role:"status","aria-label":"正在加载页面",children:n.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-brand/20 border-t-brand"})}),yt=({activeTab:e,isAdmin:t,deliveryRuleTarget:s,onConfigureDelivery:r,onDeliveryTargetHandled:a})=>{const i=c=>{r({cookieId:c.cookie_id,itemId:c.item_id,requestId:Date.now()})},o=()=>{switch(e){case"dashboard":return n.jsx(P,{});case"accounts":return n.jsx(rt,{});case"chat":return n.jsx(pt,{});case"orders":return n.jsx(it,{});case"cards":return n.jsx(ot,{});case"items":return n.jsx(ct,{onConfigureDelivery:i});case"rules":return n.jsx(dt,{initialDeliveryTarget:s,onDeliveryTargetHandled:a});case"notifications":return n.jsx(ut,{isAdmin:t});case"settings":return t?n.jsx(lt,{}):n.jsx(P,{});default:return n.jsx(P,{})}};return n.jsx(p.Suspense,{fallback:n.jsx(gt,{}),children:o()})},mt=({activeTab:e,isAdmin:t,collapsed:s,deliveryRuleTarget:r,onToggleCollapsed:a,onNavigate:i,onLogout:o,onConfigureDelivery:c,onDeliveryTargetHandled:l})=>n.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[n.jsx(nt,{activeTab:e,isAdmin:t,collapsed:s,onToggleCollapsed:a,onNavigate:i,onLogout:o}),n.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${s?"ml-16":"ml-64"} ${e==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[n.jsx("div",{className:"fixed top-0 right-0 -z-10 h-[800px] w-[800px] pointer-events-none rounded-full bg-gradient-to-bl from-blue-50 to-transparent opacity-60 blur-[120px]"}),n.jsx("div",{className:`${e==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:n.jsx(yt,{activeTab:e,isAdmin:t,deliveryRuleTarget:r,onConfigureDelivery:c,onDeliveryTargetHandled:l})})]})]}),le=p.createContext(void 0),ft=({children:e})=>{const[t,s]=p.useState(!1),[r,a]=p.useState(!1),[i,o]=p.useState(!0),[c,l]=p.useState(!1),d=()=>{s(!1),a(!1)};p.useEffect(()=>{const x=new AbortController;let v=!0;Ye({signal:x.signal}).then(w=>{if(v){if((w==null?void 0:w.initialized)===!1){l(!0),d();return}l(!1),w!=null&&w.authenticated?(s(!0),a(w.is_admin===!0)):d()}}).catch(w=>{!v||w instanceof DOMException&&w.name==="AbortError"||(l(!1),d())}).finally(()=>{v&&o(!1)});const k=()=>d();return window.addEventListener("auth:logout",k),(()=>{v=!1,x.abort(),window.removeEventListener("auth:logout",k)})},[]);const u=async x=>{const v=await Ue(x);return v.success&&(l(!1),s(!0),a(v.is_admin===!0)),v},m=async x=>{const v=await Ke(x);return v.success&&(l(!1),s(!0),a(v.is_admin===!0)),v},h=async()=>{try{await He()}finally{d()}};return n.jsx(le.Provider,{value:{checkingAuth:i,isLoggedIn:t,isAdmin:r,needsInit:c,signIn:u,initialize:m,signOut:h},children:e})},ht=()=>{const e=p.useContext(le);if(!e)throw new Error("useSession 必须在 SessionProvider 内使用");return e},de={"/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"},W=Object.fromEntries(Object.entries(de).map(([e,t])=>[t,e])),X=()=>de[window.location.pathname]||"dashboard",_t=()=>{const{checkingAuth:e,isLoggedIn:t,isAdmin:s,needsInit:r,signIn:a,initialize:i,signOut:o}=ht(),[c,l]=p.useState(X),[d,u]=p.useState(""),[m,h]=p.useState(""),[x,v]=p.useState(!1),[k,w]=p.useState(""),[A,M]=p.useState(""),[B,F]=p.useState(""),[V,J]=p.useState(!1),[U,C]=p.useState(""),[pe,K]=p.useState(),[ge,ye]=p.useState(Te),Y=f=>{const _=f==="settings"&&!s?"dashboard":f,N=W[_];N&&N!==window.location.pathname&&window.history.pushState({},"",N),l(_)};p.useEffect(()=>{const f=()=>l(X());return window.addEventListener("popstate",f),()=>window.removeEventListener("popstate",f)},[]),p.useEffect(()=>{!e&&t&&!s&&c==="settings"&&(window.history.replaceState({},"",W.dashboard),l("dashboard"))},[e,t,s,c]);const me=async f=>{f.preventDefault(),v(!0),w("");try{const _=await a({username:d,password:m});_.success||w(_.message||"登录失败")}catch(_){const N=_ instanceof Error?_.message:String(_);w(N||"登录失败")}finally{v(!1)}},fe=async f=>{if(f.preventDefault(),C(""),A.length<8){C("密码至少需要 8 个字符");return}if(A!==B){C("两次输入的密码不一致");return}J(!0);try{const _=await i(A);if(!_.success){C(_.message||"初始化失败,请重试");return}M(""),F("")}catch(_){const N=_ instanceof Error?_.message:String(_);C(N||"初始化失败,请重试")}finally{J(!1)}},he=async()=>{try{await o()}catch(f){console.error("退出登录失败",f)}};if(e)return n.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface",children:n.jsx(D,{className:"w-8 h-8 text-brand animate-spin"})});if(r)return n.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[n.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),n.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"}}),n.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:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:n.jsx(R,{sizeClass:"w-24 h-24"})}),n.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"首次设置管理员密码"}),n.jsx("p",{className:"text-gray-600 font-medium",children:"设置完成后会自动进入系统,管理员账号为 admin。"})]}),n.jsxs("form",{onSubmit:fe,className:"space-y-5",children:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"relative group",children:[n.jsx(H,{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"}),n.jsx("input",{type:"password",placeholder:"设置管理员密码(至少 8 个字符)",value:A,onChange:f=>M(f.target.value),autoFocus:!0,className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),n.jsxs("div",{className:"relative group",children:[n.jsx(I,{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"}),n.jsx("input",{type:"password",placeholder:"再次输入密码",value:B,onChange:f=>F(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),U&&n.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:[n.jsx(I,{className:"w-4 h-4"})," ",U]}),n.jsx("button",{type:"submit",disabled:V,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:V?n.jsx(D,{className:"w-5 h-5 animate-spin"}):n.jsxs(n.Fragment,{children:["设置密码并进入系统 ",n.jsx(G,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),n.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:n.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!t)return n.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[n.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),n.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"}}),n.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:[n.jsxs("div",{className:"text-center mb-10",children:[n.jsx("div",{className:"group mx-auto mb-6 flex cursor-pointer justify-center",children:n.jsx(R,{sizeClass:"w-24 h-24",logoClassName:"w-full h-full text-white group-hover:scale-110 transition-transform"})}),n.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),n.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),n.jsxs("form",{onSubmit:me,className:"space-y-5",children:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"relative group",children:[n.jsx(Oe,{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"}),n.jsx("input",{type:"text",placeholder:"管理员账号",value:d,onChange:f=>u(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),n.jsxs("div",{className:"relative group",children:[n.jsx(H,{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"}),n.jsx("input",{type:"password",placeholder:"密码",value:m,onChange:f=>h(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),k&&n.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:[n.jsx(I,{className:"w-4 h-4"})," ",k]}),n.jsx("button",{type:"submit",disabled:x,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:x?n.jsx(D,{className:"w-5 h-5 animate-spin"}):n.jsxs(n.Fragment,{children:["立即登录 ",n.jsx(G,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),n.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:n.jsx("div",{className:"mt-6 text-center",children:n.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const _e=f=>{K(f),Y("rules")},ve=()=>K(void 0),be=()=>ye(f=>{const _=!f;return Pe(_),_});return n.jsx(mt,{activeTab:c,isAdmin:s,collapsed:ge,deliveryRuleTarget:pe,onToggleCollapsed:be,onNavigate:Y,onLogout:he,onConfigureDelivery:_e,onDeliveryTargetHandled:ve})},vt=()=>n.jsx(ft,{children:n.jsx(_t,{})}),ue=document.getElementById("root");if(!ue)throw new Error("Could not find root element to mount to");const bt=xe.createRoot(ue);bt.render(n.jsx(ee.StrictMode,{children:n.jsx(vt,{})}));export{Ns as $,qt as A,Zt as B,Mt as C,Gt as D,ss as E,Xt as F,ts as G,Qt as H,es as I,Wt as J,is as K,ds as L,us as M,cs as N,ls as O,os as P,xs as Q,bs as R,hs as S,_s as T,vs as U,js as V,ws as W,Ls as X,Ss as Y,gs as Z,ys as _,ps as a,ms as a0,fs as a1,Ms as a2,Ps as a3,Ye as a4,Rs as a5,Nt as a6,Ys as a7,Es as a8,ks as a9,Is as aa,Zs as ab,Ds as ac,$s as ad,Cs as ae,As as af,Ts as ag,Qs as ah,Gs as ai,Os as aj,Hs as ak,Vs as al,Fs as am,Js as an,Ks as ao,Et as ap,$t as aq,Ot as ar,Dt as as,It as at,jt as b,Lt as c,ns as d,rs as e,kt as f,as as g,St as h,Ht as i,Tt as j,Pt as k,Rt as l,zt as m,Bs as n,Us as o,Vt as p,zs as q,At as r,Jt as s,qs as t,Ct as u,Ft as v,Bt as w,Kt as x,Ut as y,Yt as z}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-Ds-nEvf-.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-ThcsWkZG.js","assets/charts-vendor-BxxJOyEX.js","assets/vendor-D-Edl3pr.js","assets/AccountList-HAZWMDQe.js","assets/OrderList-DpM_ZNlI.js","assets/CardList-DuMEp-gq.js","assets/ItemList-BfR3GASL.js","assets/Settings-D-qaPnxf.js","assets/Rules-BqImksVG.js","assets/Notifications-Cu3hjXgW.js","assets/Chat-B1v5dyJA.js"])))=>i.map(i=>d[i]); +import{j as n,r as p,c as ee,d as xe}from"./react-vendor-C_od1ZSF.js";import{L as we,U as je,M as Le,C as Ne,B as Se,S as ke,Z as Ce,a as Ae,b as Ee,G as Z,c as $e,d as De,e as Ie,f as D,g as H,h as I,A as G,i as Oe}from"./icons-vendor-ThcsWkZG.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=s(a);fetch(a.href,i)}})();const te="ydisks.sidebar.v1",Te=()=>{try{return window.localStorage.getItem(te)==="collapsed"}catch{return!1}},Pe=e=>{try{window.localStorage.setItem(te,e?"collapsed":"expanded")}catch{}},Re=({className:e="w-full h-full text-white"})=>n.jsx("svg",{className:e,viewBox:"0 0 256 256","aria-hidden":"true",children:n.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:n.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"})})}),R=({sizeClass:e="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>n.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[n.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),n.jsxs("div",{className:`relative ${e} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[n.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[n.jsx("defs",{children:n.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[n.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),n.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),n.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)"})]}),n.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:n.jsx(Re,{className:t})})]})]}),ze="modulepreload",qe=function(e){return"/static/"+e},Q={},L=function(t,s,r){let a=Promise.resolve();if(s&&s.length>0){let o=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=o(s.map(d=>{if(d=qe(d),d in Q)return;Q[d]=!0;const u=d.endsWith(".css"),m=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":ze,u||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((x,v)=>{h.addEventListener("load",x),h.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return a.then(o=>{for(const c of o||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})},Me=3e4,Be=10*6e4;let O=!1;const se=()=>{O||typeof window>"u"||(O=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{O=!1}))},Fe=e=>{if(!e)return"";const t=new URLSearchParams;for(const[r,a]of Object.entries(e))a!=null&&t.set(r,String(a));const s=t.toString();return s?`?${s}`:""},$=async(e,t,s={})=>{var d;const r=Fe(s.params),a=`${t}${r}`,i=ae(s.signal,s.timeoutMs??Me);let o;try{o=await fetch(a,{method:e,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(u){throw i.signal.aborted?new Error((d=s.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):u}finally{i.cleanup()}const l=(o.headers.get("content-type")||"").includes("application/json");if(!o.ok){o.status===401&&!s.skipAuthLogout&&se();const u=l?await o.json().catch(()=>{}):await o.text().catch(()=>{}),m=ne(u,o.status);throw new Error(m)}return l?await o.json():await o.text()},g=async(e,t,s)=>$("GET",e,{params:t,...s}),y=async(e,t,s)=>$("POST",e,{body:t,...s}),b=async(e,t,s)=>$("PUT",e,{body:t,...s}),j=async(e,t,s)=>$("DELETE",e,{params:t,...s}),S=async(e,t,s={})=>{var l;const r=ae(s.signal,s.timeoutMs??Be);let a;try{a=await fetch(e,{method:"POST",credentials:"include",signal:r.signal,body:t})}catch(d){throw r.signal.aborted?new Error((l=s.signal)!=null&&l.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{r.cleanup()}const c=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>{}):await a.text().catch(()=>{});if(!a.ok){a.status===401&&se();const d=ne(c,a.status),u=new Error(d);throw u.payload=c,u}return c},ae=(e,t)=>{const s=new AbortController,r=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?r():e==null||e.addEventListener("abort",r,{once:!0});const a=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,t));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(a),e==null||e.removeEventListener("abort",r)}}},Ve=e=>{if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.code=="string"&&typeof t.message=="string"},ne=(e,t)=>typeof e=="string"?e:Ve(e)?e.message:`请求失败: ${t}`,E=e=>{const t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${t}-${s}-${r}`},q=(e,t)=>{const s=new Date(e);return s.setHours(12,0,0,0),s.setDate(s.getDate()+t),s},z=(e,t)=>({startDate:E(q(e,-(t-1))),endDate:E(e)}),jt=(e,t=new Date,s="",r="")=>{if(e==="custom"&&s&&r){if(s>r)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:r}}return e==="yesterday"?z(q(t,-1),1):z(t,e==="3days"?3:e==="30days"?30:e==="today"?1:7)},Lt=e=>{const t=new Date(`${e.startDate}T12:00:00`),s=new Date(`${e.endDate}T12:00:00`),r=Math.round((s.getTime()-t.getTime())/864e5)+1,a=q(t,-1);return z(a,r)},Je=e=>{const t={...e},s=["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"];for(const r of s){const a=`${r}_configured`;a in t&&(t[a]=t[a]===!0||t[a]==="true")}if("renewal_log_retention_days"in t){const r=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(r)?r:10}return t},Ue=async e=>y("/api/v1/session/login",e,{skipAuthLogout:!0}),Ke=async e=>y("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Ye=async e=>g("/api/v1/session",void 0,e),Ze=async e=>g("/health",void 0,e),He=async()=>y("/api/v1/session/logout",{}),Nt=async(e,t)=>b("/api/v1/session/credentials",e,t),Ge=(e,t)=>{const s=e.avatar_url||"";if(!s)return"";try{const r=new URL(s,window.location.origin);return r.hostname.endsWith("alicdn.com")&&r.searchParams.set("_v",t),r.toString()}catch{return s}},St=async e=>{const t=await g("/api/v1/accounts/details",void 0,e),s=Date.now().toString();return t.map(r=>({id:r.id,value:"",enabled:r.enabled,auto_confirm:r.auto_confirm,remark:r.remark,pause_duration:r.pause_duration,paused_until:Number(r.paused_until||0),paused:r.paused===!0,username:r.username||"",login_password:"",show_browser:r.show_browser===!0||r.show_browser===1||r.show_browser==="1"||r.show_browser==="true",nickname:r.nickname||r.remark||`账号 ${r.id.substring(0,6)}`,avatar_url:Ge(r,s),profile_error:r.profile_error||"",ai_enabled:!1,auto_rate_enabled:r.auto_rate_enabled,rate_content:r.rate_content||"不错的买家,交易愉快",auto_polish_enabled:r.auto_polish_enabled,polish_time:r.polish_time||"03:00",last_rate_scan_at:Number(r.last_rate_scan_at||0),last_polish_date:r.last_polish_date||"",last_polish_at:Number(r.last_polish_at||0)}))},kt=async(e,t)=>g(`/api/v1/account-tasks/${e}`,void 0,t),Ct=async(e,t,s)=>b(`/api/v1/account-tasks/${e}`,t,s),At=async(e,t,s)=>y(`/api/v1/account-tasks/${e}/run`,{task_type:t},{timeoutMs:12e4,...s}),Et=async(e,t,s,r=!1)=>{const a=await g("/api/v1/chat/sessions",{account_id:e,cursor:t,refresh:r?1:void 0},r?{timeoutMs:6e4,...s}:s);return{sessions:a.sessions||[],has_more:a.has_more===!0,next_cursor:a.next_cursor}},$t=async(e,t,s,r,a)=>{const i=await g("/api/v1/chat/messages",{account_id:e,chat_id:t,cursor:s,before_id:r},a);return{messages:i.messages||[],has_more:i.has_more===!0,next_cursor:i.next_cursor,session:i.session}},Dt=async(e,t)=>y("/api/v1/chat/messages",e,t),It=async(e,t)=>{const s=new FormData;return Object.entries(e).forEach(([r,a])=>s.append(r,a)),S("/api/v1/chat/images",s,{timeoutMs:12e4,...t})},Ot=async(e,t,s)=>y("/api/v1/chat/read",{account_id:e,chat_id:t},s),Tt=async e=>g("/api/v1/accounts/runtime-status",void 0,e),Pt=async e=>y("/api/v1/qr-login/generate",void 0,{...e,timeoutMs:(e==null?void 0:e.timeoutMs)??13e4}),Rt=async(e,t)=>g(`/api/v1/qr-login/check/${e}`,void 0,{signal:t,timeoutMs:1e4}),zt=async(e,t)=>y(`/api/v1/qr-login/complete-verification/${e}`,{target_account_id:t||""}),qt=async(e,t)=>b(`/api/v1/accounts/${e}/status`,{enabled:t}),Mt=async e=>j(`/api/v1/accounts/${e}`),Bt=async(e,t,s)=>b(`/api/v1/accounts/${e}/pause-duration`,{pause_duration:t},s),Ft=async(e,t,s)=>b(`/api/v1/accounts/${e}/settings`,t,s),Vt=async(e,t)=>g(`/api/v1/accounts/${e}/long-login`,void 0,t),Jt=async(e,t,s)=>b(`/api/v1/accounts/${e}/long-login`,{enabled:t},s),Ut=async(e,t)=>y("/api/v1/password-login",e,t),Kt=async(e,t)=>g(`/api/v1/password-login/check/${e}`,void 0,{signal:t,timeoutMs:1e4}),Yt=async(e,t)=>j(`/api/v1/password-login/cancel/${e}`,void 0,t),Zt=async e=>y(`/api/v1/accounts/${e}/refresh-profile`,{}),Ht=async e=>g("/api/v1/settings/ai-reply",void 0,e),re=e=>{const t=String(e||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Gt=async(e,t,s=1,r=20,a,i)=>{const o={page:s,page_size:r};e&&(o.cookie_id=e),t&&t!=="all"&&(o.status=t),a!=null&&a.trim()&&(o.search=a.trim());const c=await g("/api/v1/orders",o,i),d=(c.orders||c.data||[]).map(u=>({...u,id:u.id||u.order_id,status:re(u.status||u.order_status),quantity:Number(u.quantity||1)}));return{success:!0,data:d,total:c.total||d.length,page:c.page||s,page_size:c.page_size||r,total_pages:c.total_pages||1}},Qt=async(e,t)=>b(`/api/v1/orders/${e}`,t),Wt=async e=>j(`/api/v1/orders/${e}`),Xt=async(e,t,s)=>{const r=new FormData;e&&r.append("cookie_id",e),t&&r.append("status",t);const a=await S("/api/v1/orders/refresh",r,s),i=180;let o=0;try{for(;o{const m=()=>{globalThis.clearTimeout(h),u(new Error("请求已取消"))},h=globalThis.setTimeout(()=>{var x;(x=s==null?void 0:s.signal)==null||x.removeEventListener("abort",m),d()},l);s!=null&&s.signal&&(s.signal.aborted?m():s.signal.addEventListener("abort",m,{once:!0}))}),o+=1}}finally{}throw new Error("订单刷新任务等待超时")},es=async e=>y(`/api/v1/orders/${e}/refresh`),ts=async(e,t)=>y("/api/v1/orders/manual-ship",{order_ids:e,ship_mode:t}),ss=async(e,t)=>e instanceof FormData?S("/api/v1/orders/import",e,t):y("/api/v1/orders/import",e,t),as=async e=>g("/api/v1/analytics/dashboard",void 0,e),ns=async(e=7,t)=>{let s;if(typeof e=="number"){const r=new Date,a=new Date;a.setDate(a.getDate()-e),s={start_date:E(a),end_date:E(r)}}else s=e;return g("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},t)},rs=async(e,t)=>{const s=await g("/api/v1/analytics/orders/valid",{start_date:e.start_date,end_date:e.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()},t),a=(Array.isArray(s)?s:s.orders||[]).map(i=>({...i,id:i.id||i.order_id,status:re(i.status||i.order_status),quantity:Number(i.quantity||1)}));return{orders:a,total:Array.isArray(s)?a.length:Number(s.total??a.length),truncated:Array.isArray(s)?!1:s.truncated===!0}},Qe=e=>{let t=e.api_config;if(typeof t=="string"&&t.trim())try{t=JSON.parse(t)}catch{t=void 0}return{...e,api_config:t||void 0}},ie=e=>({...e,api_config:e.api_config?JSON.stringify(e.api_config):""}),is=async e=>{const t=await g("/api/v1/cards",void 0,e);return(Array.isArray(t)?t:t.cards||[]).map(Qe)},os=async e=>y("/api/v1/cards",ie(e)),cs=async(e,t)=>b(`/api/v1/cards/${e}`,ie(t)),ls=async e=>j(`/api/v1/cards/${e}`),ds=async(e,t)=>{const s=new FormData;return s.append("file",e),S("/api/v1/cards/batch",s,t)},us=async(e,t,s)=>y(`/api/v1/cards/${e}/append-data`,{content:t},s),T=e=>e===!0||e===1||e==="1",ps=async(e,t)=>{const s=await g("/api/v1/items",void 0,t);return(Array.isArray(s)?s:s.items||[]).map(a=>({...a,id:a.id||`${a.cookie_id}-${a.item_id}`,is_multi_spec:T(a.is_multi_spec),is_multi_qty_ship:T(a.is_multi_qty_ship??a.multi_quantity_delivery),multi_quantity_delivery:T(a.multi_quantity_delivery??a.is_multi_qty_ship)}))},gs=async e=>y("/api/v1/items/get-all-from-account",{cookie_id:e}),ys=async(e,t)=>j(`/api/v1/items/${e}/${t}`),ms=async(e,t)=>y(`/api/v1/items/${e}`,t),fs=async e=>{const t=new FormData;t.set("cookie_id",e.cookie_id),t.set("title",e.title),t.set("description",e.description),t.set("price",e.price),t.set("original_price",e.original_price||""),t.set("quantity",String(e.quantity)),t.set("postage_mode",e.postage_mode),t.set("postage",e.postage||""),e.location&&t.set("location",JSON.stringify(e.location));for(const s of e.images)t.append("images",s);return S("/api/v1/items/publish",t)},hs=async(e,t)=>y("/api/v1/items/publish-categories/recommend",{cookie_id:e,keyword:t}),_s=async e=>{const t=new FormData;return t.set("file",e.file),e.imagesZip&&t.set("images_zip",e.imagesZip),e.defaultCookieId&&t.set("default_cookie_id",e.defaultCookieId),t.set("fallback_category_id",e.fallbackCategory.catId),t.set("fallback_category_name",e.fallbackCategory.catName),t.set("fallback_channel_category_id",e.fallbackCategory.channelCatId||""),t.set("fallback_tb_category_id",e.fallbackCategory.tbCatId||""),e.location&&t.set("location",JSON.stringify(e.location)),S("/api/v1/items/publish-batches/preview",t)},vs=async e=>y("/api/v1/items/publish-batches",{preview_id:e}),bs=async e=>g(`/api/v1/items/publish-batches/${e}`),xs=async(e=20)=>{const t=await g("/api/v1/items/publish-batches",{limit:e});return Array.isArray(t)?t:t.batches||[]},ws=async e=>j(`/api/v1/items/publish-batches/${e}`),js=async e=>y(`/api/v1/items/publish-batches/${e}/cancel`,{}),Ls=async e=>y(`/api/v1/items/publish-batches/${e}/retry-failed`,{}),Ns=async(e,t,s)=>b(`/api/v1/items/${e}/${t}`,s),oe=e=>e.map(t=>{var s,r;return{id:String(t.id),name:t.name||"",trigger_type:t.trigger_type||"order_paid",item_keyword:t.item_title||t.item_id||"",cookie_id:t.cookie_id||"",item_id:t.item_id||"",item_title:t.item_title||"",card_group_id:Number(((s=(t.actions||[]).find(a=>a.action_type==="send_card"))==null?void 0:s.card_id)||0),card_group_name:((r=(t.actions||[]).find(a=>a.action_type==="send_card"))==null?void 0:r.card_name)||"",priority:t.priority||100,enabled:t.enabled||!1,config_json:t.config_json||"{}",actions:(t.actions||[]).map(a=>({id:a.id?String(a.id):void 0,action_type:a.action_type,card_id:Number(a.card_id||0),card_name:a.card_name||"",delivery_count:Number(a.delivery_count||1),message_template:a.message_template||"",delay_seconds:Number(a.delay_seconds||0),config_json:a.config_json||"{}",enabled:a.enabled!==!1,sort_order:Number(a.sort_order||0)})),variants:(t.actions||[]).filter(a=>a.action_type==="send_card").map(a=>{let i={};try{i=JSON.parse(a.config_json||"{}")}catch{}return{id:a.id?String(a.id):void 0,spec_name:i.spec_name||"",spec_value:i.spec_value||"",card_id:Number(a.card_id||0),card_name:a.card_name||"",delivery_count:Number(a.delivery_count||1),enabled:a.enabled!==!1,delay_override:i.delay_override===!0,delay_seconds:Number(a.delay_seconds||0),config_json:a.config_json||"{}"}})}}),Ss=async()=>{const e=await g("/api/v1/automation-rules"),t=Array.isArray(e)?e:e.data||[];return oe(t)},ks=async({cookieId:e,triggerType:t,enabled:s,search:r,page:a=1,pageSize:i=10}={})=>{const o=await g("/api/v1/automation-rules",{page:a,page_size:i,cookie_id:e||void 0,trigger_type:t||void 0,enabled:s,search:(r==null?void 0:r.trim())||void 0}),c=oe(Array.isArray(o)?o:o.data||[]);return{success:!0,data:c,total:Number(Array.isArray(o)?c.length:o.total??c.length),page:Number(Array.isArray(o)?a:o.page??a),page_size:Number(Array.isArray(o)?i:o.page_size??i),total_pages:Number(Array.isArray(o)?c.length?1:0:o.total_pages??(c.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(Array.isArray(o)?{}:o.trigger_counts||{}).map(([l,d])=>[l,Number(d)]))}},We=(e,t)=>{if(e!=="order_paid")return t.map((a,i)=>({...a,sort_order:a.sort_order||i+1}));const s=t.filter(a=>a.action_type==="send_card").map((a,i)=>({...a,sort_order:i+1})),r=t.filter(a=>a.action_type!=="send_card"&&a.action_type!=="confirm_shipment");return[...s,...r.map((a,i)=>({...a,sort_order:s.length+i+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:s.length+r.length+1}]},Cs=async e=>{const t=e.trigger_type||"order_paid",r=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[t]||"自动化规则",e.item_title||e.item_id||e.cookie_id||""].filter(Boolean).join(" - "),a=(e.actions||[]).filter(l=>l.action_type!=="send_card"&&l.action_type!=="confirm_shipment"),i=e.variants&&e.variants.length>0?[...e.variants.map((l,d)=>({action_type:"send_card",card_id:l.card_id,delivery_count:l.delivery_count||1,enabled:l.enabled!==!1,sort_order:d+1,delay_seconds:l.delay_seconds||0,config_json:JSON.stringify({spec_name:l.spec_name||"",spec_value:l.spec_value||"",delay_override:l.delay_override===!0})})),...a]:e.actions&&e.actions.length>0?e.actions:[{action_type:"send_card",card_id:e.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],o=We(t,i),c={cookie_id:e.cookie_id||"",item_id:e.item_id||"",name:(e.name||"").trim()||r||"自动化规则",trigger_type:t,enabled:e.enabled??!0,priority:e.priority||100,config_json:e.config_json||"{}",actions:o.map((l,d)=>({action_type:l.action_type,card_id:l.card_id||0,delivery_count:l.delivery_count||1,message_template:l.message_template||"",delay_seconds:l.delay_seconds||0,config_json:l.config_json||"{}",enabled:l.enabled!==!1,sort_order:l.sort_order||d+1}))};return e.id?b(`/api/v1/automation-rules/${e.id}`,c):y("/api/v1/automation-rules",c)},As=async e=>j(`/api/v1/automation-rules/${e}`),Es=async()=>{const e=await g("/api/v1/automation-issues");return{runs:Array.isArray(e==null?void 0:e.runs)?e.runs:[],pending_tasks:Array.isArray(e==null?void 0:e.pending_tasks)?e.pending_tasks:[]}},$s=async(e,t)=>y(`/api/v1/automation-runs/${e}/resolve`,{resolution:t}),Ds=async(e,t)=>y(`/api/v1/automation-pending-tasks/${e}/resolve`,{resolution:t}),Xe=e=>({id:String((e==null?void 0:e.id)||""),keyword:(e==null?void 0:e.keyword)||"",reply:(e==null?void 0:e.reply)||"",item_id:(e==null?void 0:e.item_id)||"",type:(e==null?void 0:e.type)==="image"?"image":"text",image_url:(e==null?void 0:e.image_url)||""}),et=async e=>{const t=await g(`/api/v1/reply-rules/${e}/typed`);return Array.isArray(t)?t.map(Xe):[]},Is=async e=>e?(await et(e)).map(s=>({id:s.id,keyword:s.keyword||"",reply_content:s.reply||"",match_type:"fuzzy",enabled:!0,item_id:s.item_id||"",type:s.type==="image"?"image":"text",image_url:s.image_url||""})):[],Os=async(e,t)=>{const s=e.type||"text",r={keyword:e.keyword||"",reply:s==="text"&&e.reply_content||"",item_id:e.item_id||"",type:s,image_url:s==="image"&&e.image_url||""};return e.id?b(`/api/v1/reply-rules/${t}/typed/${e.id}`,r):y(`/api/v1/reply-rules/${t}/items`,r)},Ts=async(e,t)=>j(`/api/v1/reply-rules/${t}/typed/${e}`),tt=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),st=e=>{if("values"in e||"secrets"in e)return e;const t={},s={};for(const r of Object.entries(e)){const[a,i]=r;i!=null&&(tt.has(a)?s[a]=i===""?{action:"clear"}:{action:"replace",value:String(i)}:t[a]=i)}return Object.keys(s).length>0?{values:t,secrets:s}:t},Ps=async e=>{const t=await g("/api/v1/settings/system",void 0,e);return Je(t.data||t)},Rs=async(e,t)=>{const s=st(e);return b("/api/v1/settings/system",s,t)},zs=async(e,t)=>g(`/api/v1/settings/ai-reply/${e}`,void 0,t),qs=async(e,t,s)=>{const r={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return b(`/api/v1/settings/ai-reply/${e}`,r,s)},Ms=async(e,t="",s)=>(await y("/api/v1/settings/ai-models",{base_url:e,api_key:t},s)).models||[],at=e=>{if(Array.isArray(e))return e.filter(Boolean);if(typeof e!="string"||!e.trim())return[];try{const t=JSON.parse(e);if(Array.isArray(t))return t.filter(Boolean)}catch{}return e.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ce=e=>{const t=Array.from(new Set((e||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Bs=async e=>({success:!0,data:(await g("/api/v1/notifications/channels",void 0,e)||[]).map(r=>{let a;try{a=typeof r.config=="string"?JSON.parse(r.config):r.config}catch{a={}}return{id:String(r.id),name:r.name,type:r.type==="ding_talk"?"dingtalk":r.type==="lark"?"feishu":r.type,config:a,event_types:at(r.event_types),enabled:r.enabled,created_at:r.created_at,updated_at:r.updated_at}})}),Fs=async(e,t)=>y("/api/v1/notifications/channels",{...e,config:JSON.stringify(e.config),event_types:ce(e.event_types)},t),Vs=async(e,t,s)=>{const r={...t};return"config"in t&&(r.config=JSON.stringify(t.config)),"event_types"in t&&(r.event_types=ce(t.event_types)),b(`/api/v1/notifications/channels/${e}`,r,s)},Js=async(e,t)=>j(`/api/v1/notifications/channels/${e}`,void 0,t),Us=async(e,t)=>{const s=await g(`/api/v1/notifications/accounts/${e}/bindings`,void 0,t);return(s==null?void 0:s.channel_ids)||[]},Ks=async(e,t)=>y(`/api/v1/notifications/channels/${e}/test`,{},t),Ys=async()=>g("/api/v1/default-replies"),Zs=async e=>{const t=await g(`/api/v1/default-replies/${e}`);return{cookie_id:e,enabled:t.enabled||!1,reply_content:t.reply_content||"",reply_once:t.reply_once||!1,reply_image_url:t.reply_image_url||""}},Hs=async(e,t)=>b(`/api/v1/default-replies/${e}`,{enabled:t.enabled??!1,reply_content:t.reply_content||"",reply_once:t.reply_once??!1,reply_image_url:t.reply_image_url||""}),Gs=async e=>j(`/api/v1/default-replies/${e}`),Qs=async e=>y(`/api/v1/default-replies/${e}/clear-records`,{}),nt=({activeTab:e,isAdmin:t=!1,collapsed:s,onToggleCollapsed:r,onNavigate:a,onLogout:i})=>{const[o,c]=p.useState({version:"dev",commit:"unknown"});p.useEffect(()=>{const u=new AbortController;return Ze({signal:u.signal}).then(m=>c({version:String(m.version||"dev"),commit:String(m.commit||"unknown")})).catch(m=>{m instanceof DOMException&&m.name}),(()=>u.abort())},[]);const l=[{id:"dashboard",icon:we,label:"仪表盘"},{id:"accounts",icon:je,label:"账号管理"},{id:"chat",icon:Le,label:"在线聊天"},{id:"cards",icon:Ne,label:"卡密库存"},{id:"items",icon:Se,label:"商品列表"},{id:"orders",icon:ke,label:"订单管理"},{id:"rules",icon:Ce,label:"自动化规则"},{id:"notifications",icon:Ae,label:"通知设置"},...t?[{id:"settings",icon:Ee,label:"系统与AI"}]:[]],d=/^\d+\.\d+\.\d+$/.test(o.version)?`v${o.version}`:o.version;return n.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 ${s?"w-16":"w-64"}`,children:[n.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${s?"justify-center px-2":"gap-3 px-5"}`,children:[n.jsx(R,{sizeClass:"h-10 w-10"}),!s&&n.jsxs("div",{className:"min-w-0 leading-tight",children:[n.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),n.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),n.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${s?"px-2":"px-3"}`,"aria-label":"主导航",children:l.map(u=>{const m=u.icon,h=e===u.id;return n.jsx(ee.Fragment,{children:n.jsxs("button",{type:"button",title:s?u.label:void 0,"aria-label":u.label,"aria-current":h?"page":void 0,onClick:(()=>a(u.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${s?"justify-center":"gap-3 px-3.5"} ${h?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[n.jsx(m,{className:`h-[19px] w-[19px] shrink-0 ${h?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!s&&n.jsx("span",{className:"truncate text-sm font-bold",children:u.label}),h&&!s&&n.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},u.id)})}),n.jsxs("div",{children:[n.jsx("div",{title:s?`版本 ${o.version} · ${o.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${s?"flex justify-center px-1":"px-6"}`,children:s?n.jsx(Z,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${o.version}`}):n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[n.jsx(Z,{className:"h-3.5 w-3.5"}),"运行版本"]}),n.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[n.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:d}),n.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:o.commit})]})]})}),n.jsxs("div",{className:`space-y-2 p-2 ${s?"":"p-3"}`,children:[n.jsxs("button",{type:"button",onClick:r,title:s?"展开侧边栏":"收起侧边栏","aria-label":s?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${s?"justify-center":"gap-3 px-3"}`,children:[s?n.jsx($e,{className:"h-5 w-5"}):n.jsx(De,{className:"h-5 w-5"}),!s&&n.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),n.jsxs("button",{type:"button",onClick:i,title:s?"退出登录":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 ${s?"justify-center":"gap-3 px-3"}`,children:[n.jsx(Ie,{className:"h-5 w-5"}),!s&&n.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},P=p.lazy(()=>L(()=>import("./Dashboard-Ds-nEvf-.js"),__vite__mapDeps([0,1,2,3,4,5]))),rt=p.lazy(()=>L(()=>import("./AccountList-HAZWMDQe.js"),__vite__mapDeps([6,1,3]))),it=p.lazy(()=>L(()=>import("./OrderList-DpM_ZNlI.js"),__vite__mapDeps([7,1,3,2]))),ot=p.lazy(()=>L(()=>import("./CardList-DuMEp-gq.js"),__vite__mapDeps([8,1,3]))),ct=p.lazy(()=>L(()=>import("./ItemList-BfR3GASL.js"),__vite__mapDeps([9,1,3]))),lt=p.lazy(()=>L(()=>import("./Settings-D-qaPnxf.js"),__vite__mapDeps([10,1,3]))),dt=p.lazy(()=>L(()=>import("./Rules-BqImksVG.js"),__vite__mapDeps([11,1,3]))),ut=p.lazy(()=>L(()=>import("./Notifications-Cu3hjXgW.js"),__vite__mapDeps([12,1,3]))),pt=p.lazy(()=>L(()=>import("./Chat-B1v5dyJA.js"),__vite__mapDeps([13,1,3]))),gt=()=>n.jsx("div",{className:"flex min-h-[24rem] items-center justify-center",role:"status","aria-label":"正在加载页面",children:n.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-brand/20 border-t-brand"})}),yt=({activeTab:e,isAdmin:t,deliveryRuleTarget:s,onConfigureDelivery:r,onDeliveryTargetHandled:a})=>{const i=c=>{r({cookieId:c.cookie_id,itemId:c.item_id,requestId:Date.now()})},o=()=>{switch(e){case"dashboard":return n.jsx(P,{});case"accounts":return n.jsx(rt,{});case"chat":return n.jsx(pt,{});case"orders":return n.jsx(it,{});case"cards":return n.jsx(ot,{});case"items":return n.jsx(ct,{onConfigureDelivery:i});case"rules":return n.jsx(dt,{initialDeliveryTarget:s,onDeliveryTargetHandled:a});case"notifications":return n.jsx(ut,{isAdmin:t});case"settings":return t?n.jsx(lt,{}):n.jsx(P,{});default:return n.jsx(P,{})}};return n.jsx(p.Suspense,{fallback:n.jsx(gt,{}),children:o()})},mt=({activeTab:e,isAdmin:t,collapsed:s,deliveryRuleTarget:r,onToggleCollapsed:a,onNavigate:i,onLogout:o,onConfigureDelivery:c,onDeliveryTargetHandled:l})=>n.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[n.jsx(nt,{activeTab:e,isAdmin:t,collapsed:s,onToggleCollapsed:a,onNavigate:i,onLogout:o}),n.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${s?"ml-16":"ml-64"} ${e==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[n.jsx("div",{className:"fixed top-0 right-0 -z-10 h-[800px] w-[800px] pointer-events-none rounded-full bg-gradient-to-bl from-blue-50 to-transparent opacity-60 blur-[120px]"}),n.jsx("div",{className:`${e==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:n.jsx(yt,{activeTab:e,isAdmin:t,deliveryRuleTarget:r,onConfigureDelivery:c,onDeliveryTargetHandled:l})})]})]}),le=p.createContext(void 0),ft=({children:e})=>{const[t,s]=p.useState(!1),[r,a]=p.useState(!1),[i,o]=p.useState(!0),[c,l]=p.useState(!1),d=()=>{s(!1),a(!1)};p.useEffect(()=>{const x=new AbortController;let v=!0;Ye({signal:x.signal}).then(w=>{if(v){if((w==null?void 0:w.initialized)===!1){l(!0),d();return}l(!1),w!=null&&w.authenticated?(s(!0),a(w.is_admin===!0)):d()}}).catch(w=>{!v||w instanceof DOMException&&w.name==="AbortError"||(l(!1),d())}).finally(()=>{v&&o(!1)});const k=()=>d();return window.addEventListener("auth:logout",k),(()=>{v=!1,x.abort(),window.removeEventListener("auth:logout",k)})},[]);const u=async x=>{const v=await Ue(x);return v.success&&(l(!1),s(!0),a(v.is_admin===!0)),v},m=async x=>{const v=await Ke(x);return v.success&&(l(!1),s(!0),a(v.is_admin===!0)),v},h=async()=>{try{await He()}finally{d()}};return n.jsx(le.Provider,{value:{checkingAuth:i,isLoggedIn:t,isAdmin:r,needsInit:c,signIn:u,initialize:m,signOut:h},children:e})},ht=()=>{const e=p.useContext(le);if(!e)throw new Error("useSession 必须在 SessionProvider 内使用");return e},de={"/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"},W=Object.fromEntries(Object.entries(de).map(([e,t])=>[t,e])),X=()=>de[window.location.pathname]||"dashboard",_t=()=>{const{checkingAuth:e,isLoggedIn:t,isAdmin:s,needsInit:r,signIn:a,initialize:i,signOut:o}=ht(),[c,l]=p.useState(X),[d,u]=p.useState(""),[m,h]=p.useState(""),[x,v]=p.useState(!1),[k,w]=p.useState(""),[A,M]=p.useState(""),[B,F]=p.useState(""),[V,J]=p.useState(!1),[U,C]=p.useState(""),[pe,K]=p.useState(),[ge,ye]=p.useState(Te),Y=f=>{const _=f==="settings"&&!s?"dashboard":f,N=W[_];N&&N!==window.location.pathname&&window.history.pushState({},"",N),l(_)};p.useEffect(()=>{const f=()=>l(X());return window.addEventListener("popstate",f),()=>window.removeEventListener("popstate",f)},[]),p.useEffect(()=>{!e&&t&&!s&&c==="settings"&&(window.history.replaceState({},"",W.dashboard),l("dashboard"))},[e,t,s,c]);const me=async f=>{f.preventDefault(),v(!0),w("");try{const _=await a({username:d,password:m});_.success||w(_.message||"登录失败")}catch(_){const N=_ instanceof Error?_.message:String(_);w(N||"登录失败")}finally{v(!1)}},fe=async f=>{if(f.preventDefault(),C(""),A.length<8){C("密码至少需要 8 个字符");return}if(A!==B){C("两次输入的密码不一致");return}J(!0);try{const _=await i(A);if(!_.success){C(_.message||"初始化失败,请重试");return}M(""),F("")}catch(_){const N=_ instanceof Error?_.message:String(_);C(N||"初始化失败,请重试")}finally{J(!1)}},he=async()=>{try{await o()}catch(f){console.error("退出登录失败",f)}};if(e)return n.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface",children:n.jsx(D,{className:"w-8 h-8 text-brand animate-spin"})});if(r)return n.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[n.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),n.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"}}),n.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:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:n.jsx(R,{sizeClass:"w-24 h-24"})}),n.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"首次设置管理员密码"}),n.jsx("p",{className:"text-gray-600 font-medium",children:"设置完成后会自动进入系统,管理员账号为 admin。"})]}),n.jsxs("form",{onSubmit:fe,className:"space-y-5",children:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"relative group",children:[n.jsx(H,{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"}),n.jsx("input",{type:"password",placeholder:"设置管理员密码(至少 8 个字符)",value:A,onChange:f=>M(f.target.value),autoFocus:!0,className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),n.jsxs("div",{className:"relative group",children:[n.jsx(I,{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"}),n.jsx("input",{type:"password",placeholder:"再次输入密码",value:B,onChange:f=>F(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),U&&n.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:[n.jsx(I,{className:"w-4 h-4"})," ",U]}),n.jsx("button",{type:"submit",disabled:V,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:V?n.jsx(D,{className:"w-5 h-5 animate-spin"}):n.jsxs(n.Fragment,{children:["设置密码并进入系统 ",n.jsx(G,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),n.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:n.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!t)return n.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[n.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),n.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"}}),n.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:[n.jsxs("div",{className:"text-center mb-10",children:[n.jsx("div",{className:"group mx-auto mb-6 flex cursor-pointer justify-center",children:n.jsx(R,{sizeClass:"w-24 h-24",logoClassName:"w-full h-full text-white group-hover:scale-110 transition-transform"})}),n.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),n.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),n.jsxs("form",{onSubmit:me,className:"space-y-5",children:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"relative group",children:[n.jsx(Oe,{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"}),n.jsx("input",{type:"text",placeholder:"管理员账号",value:d,onChange:f=>u(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),n.jsxs("div",{className:"relative group",children:[n.jsx(H,{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"}),n.jsx("input",{type:"password",placeholder:"密码",value:m,onChange:f=>h(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),k&&n.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:[n.jsx(I,{className:"w-4 h-4"})," ",k]}),n.jsx("button",{type:"submit",disabled:x,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:x?n.jsx(D,{className:"w-5 h-5 animate-spin"}):n.jsxs(n.Fragment,{children:["立即登录 ",n.jsx(G,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),n.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:n.jsx("div",{className:"mt-6 text-center",children:n.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const _e=f=>{K(f),Y("rules")},ve=()=>K(void 0),be=()=>ye(f=>{const _=!f;return Pe(_),_});return n.jsx(mt,{activeTab:c,isAdmin:s,collapsed:ge,deliveryRuleTarget:pe,onToggleCollapsed:be,onNavigate:Y,onLogout:he,onConfigureDelivery:_e,onDeliveryTargetHandled:ve})},vt=()=>n.jsx(ft,{children:n.jsx(_t,{})}),ue=document.getElementById("root");if(!ue)throw new Error("Could not find root element to mount to");const bt=xe.createRoot(ue);bt.render(n.jsx(ee.StrictMode,{children:n.jsx(vt,{})}));export{Ns as $,qt as A,Zt as B,Mt as C,Gt as D,ss as E,Xt as F,ts as G,Qt as H,es as I,Wt as J,is as K,ds as L,us as M,cs as N,ls as O,os as P,xs as Q,bs as R,hs as S,_s as T,vs as U,js as V,ws as W,Ls as X,Ss as Y,gs as Z,ys as _,ps as a,ms as a0,fs as a1,Ms as a2,Ps as a3,Ye as a4,Rs as a5,Nt as a6,Ys as a7,Es as a8,ks as a9,Is as aa,Cs as ab,As as ac,$s as ad,Ds as ae,Os as af,Ts as ag,Zs as ah,Hs as ai,Gs as aj,Qs as ak,Vs as al,Fs as am,Js as an,Ks as ao,Et as ap,$t as aq,Ot as ar,Dt as as,It as at,jt as b,Lt as c,ns as d,rs as e,kt as f,as as g,St as h,Ht as i,Tt as j,Pt as k,Rt as l,zt as m,Bs as n,Us as o,Vt as p,zs as q,At as r,Jt as s,qs as t,Ct as u,Ft as v,Bt as w,Kt as x,Ut as y,Yt as z}; diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html index cc8fccf..f5d51bb 100644 --- a/internal/webui/static/index.html +++ b/internal/webui/static/index.html @@ -6,7 +6,7 @@ Ydisks闲鱼助手 - 自动发货与管家系统 - +