diff --git a/cmd/server/main.go b/cmd/server/main.go index 68030a0..7b02b26 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -334,6 +334,7 @@ func runServer(parent context.Context, opts serverOptions) error { } srv.StartPublishBatchRecovery(ctx) srv.StartOrderReconciliationRecovery(ctx) + srv.StartOrderRefreshRecovery(ctx) // err 是 HTTP 服务显式启动失败的原因。 if err := srv.Start(ctx); err != nil { return fmt.Errorf("启动 HTTP 服务失败: %w", err) diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 8f5cdc0..6bd87d7 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -745,3 +745,4 @@ npm --prefix frontend run build | 2026-08-15 | P2 商品多规格探测批量与并发边界切片 | 已完成 | 商品同步先用 `MultiSpecFlags` 一次读取本地多规格标记,消除逐商品数据库查询;剩余远端详情探测使用 4 路有界并发,Session 过期可取消同批次探测,普通单项失败保留告警并继续;新增批量标记和并发上限回归测试,定向测试与中文注释门禁通过。跨请求缓存、跨批次去重、平台限流指标和 MySQL/Postgres 查询计划仍待完成,P2 批量同步保持“进行中” | | 2026-08-15 | P2 商品多规格跨请求缓存切片 | 已完成 | Server 新增按账号/商品隔离的 10 分钟 TTL 多规格缓存;同步成功结果(含 false)均缓存,后续同步命中缓存时跳过远端探测,过期项自动清理;新增缓存命中、过期和并发探测回归测试,注释门禁通过。跨实例共享缓存、主动失效通知、平台限流指标和 MySQL/Postgres 查询计划仍待完成,P2 批量同步保持“进行中” | | 2026-08-15 | P2 订单复合游标索引与查询计划切片 | 已完成 | SQLite/MySQL/Postgres 新增 `idx_orders_cursor(cookie_id, deleted_at, created_at, order_id)` 复合索引;新增 SQLite `EXPLAIN QUERY PLAN` 回归,确认订单游标查询使用该索引;迁移、订单扫描和中文注释门禁通过。MySQL/Postgres 实际执行计划仍需外部数据库环境验证,P2 批量同步保持“进行中” | +| 2026-08-15 | P1 订单刷新持久化后台任务切片 | 已完成 | 新增 SQLite/MySQL/Postgres `order_refresh_jobs` 迁移及应用层 `RefreshJobRepository` Port;订单刷新 HTTP 端点改为 202 + 用户隔离的状态查询,后台 worker 受 Server 生命周期管理,使用 worker token/lease fencing,并提供过期任务恢复扫描;React 客户端改为可取消的状态轮询;新增任务生命周期、跨用户隔离、旧 worker 拒绝写入、成功/失败/取消和 HTTP/前端契约回归;Go 全量测试、架构/中文注释门禁、前端 317 测试、类型检查和生产构建通过。仍待补充取消端点、进度事件、MySQL/Postgres 实际任务迁移回归与统一运维查询,阶段 4/5/8/9 继续保持“进行中” | diff --git a/frontend/services/api.test.ts b/frontend/services/api.test.ts index d737d19..feafc53 100644 --- a/frontend/services/api.test.ts +++ b/frontend/services/api.test.ts @@ -172,12 +172,38 @@ test('automation issue APIs expose and resolve quarantined work', async () => { } /* 回调函数负责当前业务流程。 */); test('order multipart requests use the shared authenticated form request path', async () => { - const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */ + const fetchMock = vi.fn() + .mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-1', status: 'running' })) + .mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-1', status: 'succeeded', result: { partial_failure: false, message: '同步完成', summary: { discovered: 0, list_updated: 0, soft_deleted: 0, detail_total: 0, total: 0, updated: 0, no_change: 0, failed: 0 }, results: [] } })) + .mockResolvedValueOnce(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */ vi.stubGlobal('fetch', fetchMock); await syncOrders('acc1', 'pending_ship'); await importOrders(new FormData()); expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/orders/refresh', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) })); - expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/import', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) })); + expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/refresh/job-1', expect.objectContaining({ method: 'GET', credentials: 'include' })); + expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/orders/import', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) })); +} /* 回调函数负责当前业务流程。 */); + +test('syncOrders surfaces failed persisted job status', async () => { + const fetchMock = vi.fn() + .mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-failed', status: 'running' })) + .mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-failed', status: 'failed', error_message: '平台会话已过期' })); /* fetchMock 表示fetchMock。 */ + vi.stubGlobal('fetch', fetchMock); + await expect(syncOrders()).rejects.toThrow('平台会话已过期'); +} /* 回调函数负责当前业务流程。 */); + +test('syncOrders aborts while waiting for persisted job status', async () => { + const fetchMock = vi.fn() + .mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-running', status: 'running' })) + .mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-running', status: 'running' })); /* fetchMock 表示fetchMock。 */ + vi.stubGlobal('fetch', fetchMock); + // controller 控制订单刷新轮询的取消信号。 + const controller = new AbortController(); + // pending 保存等待取消结果的订单刷新请求。 + const pending = syncOrders(undefined, undefined, { signal: controller.signal }); + await Promise.resolve(); + controller.abort(); + await expect(pending).rejects.toThrow('请求已取消'); } /* 回调函数负责当前业务流程。 */); test('legacy notification channel aliases are normalized for the editor', async () => { diff --git a/frontend/services/api.ts b/frontend/services/api.ts index bb27627..6a1cd28 100644 --- a/frontend/services/api.ts +++ b/frontend/services/api.ts @@ -4,7 +4,7 @@ import { AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics, Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType, NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope, - CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse + CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse } from '../types'; import { formatLocalDate } from '../dateRange'; @@ -423,13 +423,47 @@ export const deleteOrder = async (orderId: string): Promise = }; // syncOrders 同步订单。 -export const syncOrders = async (cookieId?: string, status?: string): Promise => { +export const syncOrders = async (cookieId?: string, status?: string, options?: RequestControlOptions): Promise => { // formData 表单数据,用于当前 API 处理流程。 const formData = new FormData(); if (cookieId) formData.append('cookie_id', cookieId); if (status) formData.append('status', status); - return postForm('/api/v1/orders/refresh', formData); + // start 表示后台订单刷新任务创建响应。 + const start = await postForm('/api/v1/orders/refresh', formData, options); + // pollLimit 限制前端等待后台任务的轮询次数。 + const pollLimit = 180; + // pollIndex 表示当前订单刷新任务状态轮询次数。 + let pollIndex = 0; + while (pollIndex < pollLimit) { + // job 表示当前轮询得到的后台任务状态。 + const job = await get(`/api/v1/orders/refresh/${start.job_id}`, undefined, options); + if (job.status === 'succeeded' && job.result) { + return job.result; + } + if (job.status === 'failed' || job.status === 'cancelled') { + throw new Error(job.error_message || '订单刷新任务失败'); + } + // waitMs 是下一次任务状态轮询前的等待时间。 + const waitMs = 500; + await new Promise(/* 轮询等待器负责等待下一次任务状态查询。 */ (resolve, reject) => { + // abort 负责响应调用方取消轮询。 + const abort = () => { + globalThis.clearTimeout(timer); + reject(new Error('请求已取消')); + }; + // timer 表示当前轮询等待定时器。 + const timer = globalThis.setTimeout(/* 轮询完成回调清理取消监听并结束等待。 */ () => { + options?.signal?.removeEventListener('abort', abort); + resolve(); + }, waitMs); + if (!options?.signal) return; + if (options.signal.aborted) abort(); + else options.signal.addEventListener('abort', abort, { once: true }); + }); + pollIndex += 1; + } + throw new Error('订单刷新任务等待超时'); }; // syncSingleOrder 同步单个订单。 diff --git a/frontend/types.ts b/frontend/types.ts index 7a163e1..ace75cb 100644 --- a/frontend/types.ts +++ b/frontend/types.ts @@ -1561,6 +1561,30 @@ export interface OrderRefreshResponse { results: OrderRefreshResultResponse[]; } +/** 创建订单刷新后台任务的响应。 */ +export interface OrderRefreshJobStartResponse { + /** 任务是否创建成功。 */ + success: boolean; + /** 后台任务标识。 */ + job_id: string; + /** 任务当前状态。 */ + status: 'queued' | 'running'; +} + +/** 查询订单刷新后台任务的响应。 */ +export interface OrderRefreshJobStatusResponse { + /** 查询是否成功。 */ + success: boolean; + /** 后台任务标识。 */ + job_id: string; + /** 任务当前状态。 */ + status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; + /** 任务失败原因。 */ + error_message?: string; + /** 任务成功后的订单刷新结果。 */ + result?: OrderRefreshResponse; +} + // ItemListEnvelope 是商品列表接口的兼容分页响应。 export interface ItemListEnvelope { /** items 是兼容分页响应中的商品列表。 */ diff --git a/internal/application/orders/refresh_job.go b/internal/application/orders/refresh_job.go new file mode 100644 index 0000000..5bd264a --- /dev/null +++ b/internal/application/orders/refresh_job.go @@ -0,0 +1,51 @@ +package orders + +import ( + "context" + "errors" +) + +// ErrRefreshJobNotFound 表示当前用户无法读取指定订单刷新任务。 +var ErrRefreshJobNotFound = errors.New("订单刷新任务不存在") + +// RefreshJob 是订单刷新后台任务的应用层模型,不暴露数据库类型。 +type RefreshJob struct { + // ID 是任务唯一标识。 + ID string + // UserID 是任务所属用户标识。 + UserID int64 + // CookieID 是可选的目标账号标识。 + CookieID string + // FilterStatus 是订单状态筛选条件。 + FilterStatus string + // Status 是 queued/running/succeeded/failed/cancelled 之一。 + Status string + // ResultJSON 保存成功后的具名刷新结果 JSON。 + ResultJSON string + // ErrorMessage 保存任务失败原因。 + ErrorMessage string + // WorkerToken 是当前执行者租约令牌。 + WorkerToken string + // LeaseExpiresAt 是租约过期 Unix 秒时间戳。 + LeaseExpiresAt int64 + // CreatedAt 是任务创建时间。 + CreatedAt string + // UpdatedAt 是任务最后更新时间。 + UpdatedAt string +} + +// RefreshJobRepository 定义订单刷新任务需要的持久化能力。 +type RefreshJobRepository interface { + // Create 创建一个 queued 状态的订单刷新任务。 + Create(ctx context.Context, job *RefreshJob) error + // Get 按用户读取订单刷新任务。 + Get(ctx context.Context, userID int64, id string) (*RefreshJob, error) + // Claim 原子抢占 queued 任务并写入租约令牌。 + Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error) + // Complete 在租约令牌匹配时写入任务终态。 + Complete(ctx context.Context, id, token, status, resultJSON, errorMessage string) (bool, error) + // Recoverable 返回租约已过期的 running 任务。 + Recoverable(ctx context.Context, now int64, limit int) ([]RefreshJob, error) + // RequeueExpired 将过期运行任务恢复为 queued。 + RequeueExpired(ctx context.Context, id string, now int64) (bool, error) +} diff --git a/internal/db/migrations/mysql/00031_order_refresh_jobs.sql b/internal/db/migrations/mysql/00031_order_refresh_jobs.sql new file mode 100644 index 0000000..62e2dc9 --- /dev/null +++ b/internal/db/migrations/mysql/00031_order_refresh_jobs.sql @@ -0,0 +1,20 @@ +-- +goose Up +CREATE TABLE IF NOT EXISTS order_refresh_jobs ( + id VARCHAR(64) PRIMARY KEY, + user_id BIGINT NOT NULL, + cookie_id VARCHAR(255) NOT NULL DEFAULT '', + filter_status VARCHAR(64) NOT NULL DEFAULT '', + status VARCHAR(32) NOT NULL DEFAULT 'queued', + result_json LONGTEXT NOT NULL, + error_message TEXT NOT NULL, + worker_token VARCHAR(128) NOT NULL DEFAULT '', + lease_expires_at BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_order_refresh_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_order_refresh_jobs_user (user_id, created_at, id), + INDEX idx_order_refresh_jobs_lease (status, lease_expires_at) +); + +-- +goose Down +DROP TABLE IF EXISTS order_refresh_jobs; diff --git a/internal/db/migrations/postgres/00031_order_refresh_jobs.sql b/internal/db/migrations/postgres/00031_order_refresh_jobs.sql new file mode 100644 index 0000000..66e1ee6 --- /dev/null +++ b/internal/db/migrations/postgres/00031_order_refresh_jobs.sql @@ -0,0 +1,21 @@ +-- +goose Up +CREATE TABLE IF NOT EXISTS order_refresh_jobs ( + id TEXT PRIMARY KEY, + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + cookie_id TEXT NOT NULL DEFAULT '', + filter_status TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'queued', + result_json TEXT NOT NULL DEFAULT '{}', + error_message TEXT NOT NULL DEFAULT '', + worker_token TEXT NOT NULL DEFAULT '', + lease_expires_at BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC); +CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at); + +-- +goose Down +DROP INDEX IF EXISTS idx_order_refresh_jobs_lease; +DROP INDEX IF EXISTS idx_order_refresh_jobs_user; +DROP TABLE IF EXISTS order_refresh_jobs; diff --git a/internal/db/migrations/sqlite/00031_order_refresh_jobs.sql b/internal/db/migrations/sqlite/00031_order_refresh_jobs.sql new file mode 100644 index 0000000..900fa50 --- /dev/null +++ b/internal/db/migrations/sqlite/00031_order_refresh_jobs.sql @@ -0,0 +1,21 @@ +-- +goose Up +CREATE TABLE IF NOT EXISTS order_refresh_jobs ( + id TEXT PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + cookie_id TEXT NOT NULL DEFAULT '', + filter_status TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'queued', + result_json TEXT NOT NULL DEFAULT '{}', + error_message TEXT NOT NULL DEFAULT '', + worker_token TEXT NOT NULL DEFAULT '', + lease_expires_at INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC); +CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at); + +-- +goose Down +DROP INDEX IF EXISTS idx_order_refresh_jobs_lease; +DROP INDEX IF EXISTS idx_order_refresh_jobs_user; +DROP TABLE IF EXISTS order_refresh_jobs; diff --git a/internal/db/order_refresh_jobs.go b/internal/db/order_refresh_jobs.go new file mode 100644 index 0000000..0f50a6f --- /dev/null +++ b/internal/db/order_refresh_jobs.go @@ -0,0 +1,153 @@ +package db + +import ( + "context" + "database/sql" + "errors" +) + +// OrderRefreshJobs 持久化订单刷新后台任务及其租约状态。 +type OrderRefreshJobs struct { + // DB 保存任务表使用的数据库连接。 + DB *sql.DB +} + +// OrderRefreshJob 是订单刷新任务的持久化模型。 +type OrderRefreshJob struct { + // ID 是任务唯一标识。 + ID string + // UserID 是任务所属用户标识。 + UserID int64 + // CookieID 是可选的目标账号标识。 + CookieID string + // FilterStatus 是订单状态筛选条件。 + FilterStatus string + // Status 是 queued/running/succeeded/failed/cancelled 之一。 + Status string + // ResultJSON 保存成功后的具名刷新结果 JSON。 + ResultJSON string + // ErrorMessage 保存任务失败原因。 + ErrorMessage string + // WorkerToken 是当前执行者租约令牌。 + WorkerToken string + // LeaseExpiresAt 是租约过期 Unix 秒时间戳。 + LeaseExpiresAt int64 + // CreatedAt 是任务创建时间。 + CreatedAt string + // UpdatedAt 是任务最后更新时间。 + UpdatedAt string +} + +// Create 创建一个 queued 状态的订单刷新任务。 +func (j *OrderRefreshJobs) Create(ctx context.Context, job *OrderRefreshJob) error { + if job.Status == "" { + job.Status = "queued" + } + if job.ResultJSON == "" { + job.ResultJSON = "{}" + } + // err 表示创建订单刷新任务的数据库错误。 + _, err := j.DB.ExecContext(ctx, + `INSERT INTO order_refresh_jobs + (id,user_id,cookie_id,filter_status,status,result_json,error_message,worker_token,lease_expires_at) + VALUES (?,?,?,?,?,?,?,?,?)`, + job.ID, job.UserID, job.CookieID, job.FilterStatus, job.Status, job.ResultJSON, + job.ErrorMessage, job.WorkerToken, job.LeaseExpiresAt) + return err +} + +// Get 按用户读取订单刷新任务,防止跨用户查询任务结果。 +func (j *OrderRefreshJobs) Get(ctx context.Context, userID int64, id string) (*OrderRefreshJob, error) { + // job 保存读取到的任务模型。 + job := &OrderRefreshJob{} + // err 保存任务查询错误。 + err := j.DB.QueryRowContext(ctx, + `SELECT id,user_id,cookie_id,filter_status,status,COALESCE(result_json,'{}'), + COALESCE(error_message,''),COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at + FROM order_refresh_jobs WHERE id=? AND user_id=?`, id, userID).Scan( + &job.ID, &job.UserID, &job.CookieID, &job.FilterStatus, &job.Status, &job.ResultJSON, + &job.ErrorMessage, &job.WorkerToken, &job.LeaseExpiresAt, &job.CreatedAt, &job.UpdatedAt) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return job, nil +} + +// Claim 将 queued 任务原子切换为 running 并写入租约。 +func (j *OrderRefreshJobs) Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error) { + // result、err 保存抢占更新结果及错误。 + result, err := j.DB.ExecContext(ctx, + `UPDATE order_refresh_jobs + SET status='running',worker_token=?,lease_expires_at=?,updated_at=CURRENT_TIMESTAMP + WHERE id=? AND status='queued'`, token, leaseExpiresAt, id) + if err != nil { + return false, err + } + // affected、err 保存抢占更新影响行数及错误。 + affected, err := result.RowsAffected() + return affected == 1, err +} + +// Complete 在租约令牌匹配时写入任务终态,过期 worker 不能覆盖新执行者结果。 +func (j *OrderRefreshJobs) Complete(ctx context.Context, id, token, status, resultJSON, errorMessage string) (bool, error) { + // result、err 保存任务终态更新结果及错误。 + result, err := j.DB.ExecContext(ctx, + `UPDATE order_refresh_jobs + SET status=?,result_json=?,error_message=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP + WHERE id=? AND status='running' AND worker_token=?`, status, resultJSON, errorMessage, id, token) + if err != nil { + return false, err + } + // affected、err 保存终态更新影响行数及错误。 + affected, err := result.RowsAffected() + return affected == 1, err +} + +// Recoverable 返回租约已过期的 running 任务,供恢复扫描器重新排队。 +func (j *OrderRefreshJobs) Recoverable(ctx context.Context, now int64, limit int) ([]OrderRefreshJob, error) { + if limit <= 0 || limit > 100 { + limit = 20 + } + // rows、err 保存可恢复任务查询结果及错误。 + rows, err := j.DB.QueryContext(ctx, + `SELECT id,user_id,cookie_id,filter_status,status,COALESCE(result_json,'{}'), + COALESCE(error_message,''),COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at + FROM order_refresh_jobs + WHERE status='running' AND lease_expires_at>0 AND lease_expires_at<=? + ORDER BY updated_at ASC,id ASC LIMIT ?`, now, limit) + if err != nil { + return nil, err + } + defer rows.Close() + // jobs 保存可恢复任务列表。 + jobs := make([]OrderRefreshJob, 0, limit) + for rows.Next() { + // job 保存当前可恢复任务。 + var job OrderRefreshJob + // err 表示扫描可恢复任务的数据库错误。 + if err := rows.Scan(&job.ID, &job.UserID, &job.CookieID, &job.FilterStatus, &job.Status, + &job.ResultJSON, &job.ErrorMessage, &job.WorkerToken, &job.LeaseExpiresAt, &job.CreatedAt, &job.UpdatedAt); err != nil { + return nil, err + } + jobs = append(jobs, job) + } + return jobs, rows.Err() +} + +// RequeueExpired 将过期运行任务恢复为 queued,并清理旧 worker 租约。 +func (j *OrderRefreshJobs) RequeueExpired(ctx context.Context, id string, now int64) (bool, error) { + // result、err 保存任务重新入队结果及错误。 + result, err := j.DB.ExecContext(ctx, + `UPDATE order_refresh_jobs + SET status='queued',worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP + WHERE id=? AND status='running' AND lease_expires_at>0 AND lease_expires_at<=?`, id, now) + if err != nil { + return false, err + } + // affected、err 保存重新入队影响行数及错误。 + affected, err := result.RowsAffected() + return affected == 1, err +} diff --git a/internal/db/order_refresh_jobs_test.go b/internal/db/order_refresh_jobs_test.go new file mode 100644 index 0000000..d196cd3 --- /dev/null +++ b/internal/db/order_refresh_jobs_test.go @@ -0,0 +1,81 @@ +package db + +import ( + "context" + "errors" + "testing" + "time" +) + +// TestOrderRefreshJobsLifecycle 验证订单刷新任务的创建、租约、终态和过期恢复生命周期。 +func TestOrderRefreshJobsLifecycle(t *testing.T) { + // store、cleanup 保存当前测试数据库及清理函数。 + store, cleanup := newTestDB(t) + defer cleanup() + // ctx 保存当前任务测试使用的上下文。 + ctx := context.Background() + // userID、cookieID 保存测试账号归属信息。 + userID, cookieID := seedAccount(t, store) + // job 保存待测试的订单刷新任务。 + job := &OrderRefreshJob{ID: "refresh-job-1", UserID: userID, CookieID: cookieID, FilterStatus: "pending_ship"} + // err 表示创建任务的数据库错误。 + if err := store.OrderRefreshJobs.Create(ctx, job); err != nil { + t.Fatalf("create job: %v", err) + } + // loaded、err 保存创建后的任务读取结果及错误。 + loaded, err := store.OrderRefreshJobs.Get(ctx, userID, job.ID) + if err != nil || loaded.Status != "queued" || loaded.ResultJSON != "{}" { + t.Fatalf("created job=%+v err=%v", loaded, err) + } + // claimed、err 保存首次租约抢占结果及错误。 + claimed, err := store.OrderRefreshJobs.Claim(ctx, job.ID, "worker-1", time.Now().Add(time.Minute).Unix()) + if err != nil || !claimed { + t.Fatalf("claim job: claimed=%v err=%v", claimed, err) + } + // err 表示重复抢占的数据库错误。 + if claimed, err = store.OrderRefreshJobs.Claim(ctx, job.ID, "worker-2", time.Now().Add(time.Minute).Unix()); err != nil || claimed { + t.Fatalf("duplicate claim should fail: claimed=%v err=%v", claimed, err) + } + // completed、err 表示错误 worker 的终态写入结果及错误。 + if completed, err := store.OrderRefreshJobs.Complete(ctx, job.ID, "worker-2", "succeeded", `{"message":"wrong worker"}`, ""); err != nil || completed { + t.Fatalf("wrong worker must not complete: completed=%v err=%v", completed, err) + } + // completed、err 表示合法 worker 的终态写入结果及错误。 + if completed, err := store.OrderRefreshJobs.Complete(ctx, job.ID, "worker-1", "succeeded", `{"message":"ok"}`, ""); err != nil || !completed { + t.Fatalf("complete job: completed=%v err=%v", completed, err) + } + // completedJob、err 保存成功任务的终态读取结果及错误。 + completedJob, err := store.OrderRefreshJobs.Get(ctx, userID, job.ID) + if err != nil || completedJob.Status != "succeeded" || completedJob.WorkerToken != "" { + t.Fatalf("completed job=%+v err=%v", completedJob, err) + } + + // expiredJob 保存用于验证租约过期恢复的任务。 + expiredJob := &OrderRefreshJob{ID: "refresh-job-expired", UserID: userID, CookieID: cookieID} + // err 表示创建过期任务的数据库错误。 + if err := store.OrderRefreshJobs.Create(ctx, expiredJob); err != nil { + t.Fatalf("create expired job: %v", err) + } + // claimed、err 表示过期任务的租约抢占结果及错误。 + if claimed, err := store.OrderRefreshJobs.Claim(ctx, expiredJob.ID, "worker-old", time.Now().Add(-time.Minute).Unix()); err != nil || !claimed { + t.Fatalf("claim expired job: claimed=%v err=%v", claimed, err) + } + // recoverable、err 保存过期任务扫描结果及错误。 + recoverable, err := store.OrderRefreshJobs.Recoverable(ctx, time.Now().Unix(), 10) + if err != nil || len(recoverable) != 1 || recoverable[0].ID != expiredJob.ID { + t.Fatalf("recoverable=%+v err=%v", recoverable, err) + } + // requeued、err 表示过期任务重新入队结果及错误。 + if requeued, err := store.OrderRefreshJobs.RequeueExpired(ctx, expiredJob.ID, time.Now().Unix()); err != nil || !requeued { + t.Fatalf("requeue expired job: requeued=%v err=%v", requeued, err) + } + // requeuedJob、err 保存重新入队后的任务及错误。 + requeuedJob, err := store.OrderRefreshJobs.Get(ctx, userID, expiredJob.ID) + if err != nil || requeuedJob.Status != "queued" || requeuedJob.WorkerToken != "" { + t.Fatalf("requeued job=%+v err=%v", requeuedJob, err) + } + // err 表示跨用户读取任务的查询错误。 + if _, err := store.OrderRefreshJobs.Get(ctx, userID+1, job.ID); !errors.Is(err, ErrNotFound) { + t.Fatalf("cross-user job lookup should be hidden, err=%v", err) + } +} diff --git a/internal/db/store.go b/internal/db/store.go index 7e6ae2f..a06125a 100644 --- a/internal/db/store.go +++ b/internal/db/store.go @@ -7,33 +7,34 @@ import ( // Store 聚合各 repository,供上层(HTTP server、account supervisor 等)统一持有。 type Store struct { - DB *sql.DB - Dialect Dialect - Users *Users - Sessions *Sessions - Cookies *Cookies - Items *Items - Cards *Cards - Automation *AutomationRules - Orders *Orders - Reconciliations *OrderReconciliations - Keywords *Keywords - DefaultReps *DefaultReplies - ItemReps *ItemReplies - AIReply *AIReply - Notifications *Notifications - Settings *SystemSettings - UserSettings *UserSettings - WSMessages *WSMessageStore - PublishBatches *ItemPublishBatches - Tokens *AccountTokens - Renewal *RenewalStore - LoginLogs *AccountLoginLogs - RiskLogs *RiskControlLogs - Chats *ChatStore - AccountTasks *AccountTaskStore - Admin *AdminQueries - Analytics *AnalyticsQueries + DB *sql.DB + Dialect Dialect + Users *Users + Sessions *Sessions + Cookies *Cookies + Items *Items + Cards *Cards + Automation *AutomationRules + Orders *Orders + Reconciliations *OrderReconciliations + OrderRefreshJobs *OrderRefreshJobs + Keywords *Keywords + DefaultReps *DefaultReplies + ItemReps *ItemReplies + AIReply *AIReply + Notifications *Notifications + Settings *SystemSettings + UserSettings *UserSettings + WSMessages *WSMessageStore + PublishBatches *ItemPublishBatches + Tokens *AccountTokens + Renewal *RenewalStore + LoginLogs *AccountLoginLogs + RiskLogs *RiskControlLogs + Chats *ChatStore + AccountTasks *AccountTaskStore + Admin *AdminQueries + Analytics *AnalyticsQueries credentialMu sync.Mutex credentialLocks map[string]*credentialLockEntry @@ -52,34 +53,35 @@ func NewStore(db *sql.DB, dialect Dialect) *Store { // codec 保存codec,供当前处理流程使用 codec := secretCodecFromEnvironment() return &Store{ - DB: db, - Dialect: dialect, - Users: &Users{DB: db}, - Sessions: &Sessions{DB: db}, - Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec}, - Items: &Items{DB: db, Dialect: dialect}, - Cards: &Cards{DB: db, Dialect: dialect}, - Automation: &AutomationRules{DB: db, Dialect: dialect}, - Orders: &Orders{DB: db, Dialect: dialect}, - Reconciliations: &OrderReconciliations{DB: db}, - Keywords: &Keywords{DB: db, Dialect: dialect}, - DefaultReps: &DefaultReplies{DB: db, Dialect: dialect}, - ItemReps: &ItemReplies{DB: db, Dialect: dialect}, - AIReply: &AIReply{DB: db, Dialect: dialect, codec: codec}, - Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec}, - Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec}, - UserSettings: &UserSettings{DB: db, Dialect: dialect}, - WSMessages: &WSMessageStore{DB: db}, - PublishBatches: &ItemPublishBatches{DB: db}, - Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec}, - Renewal: &RenewalStore{DB: db, Dialect: dialect}, - LoginLogs: &AccountLoginLogs{DB: db}, - RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect}, - Chats: &ChatStore{DB: db, Dialect: dialect}, - AccountTasks: &AccountTaskStore{DB: db, Dialect: dialect}, - Admin: &AdminQueries{DB: db}, - Analytics: &AnalyticsQueries{DB: db}, - credentialLocks: make(map[string]*credentialLockEntry), + DB: db, + Dialect: dialect, + Users: &Users{DB: db}, + Sessions: &Sessions{DB: db}, + Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec}, + Items: &Items{DB: db, Dialect: dialect}, + Cards: &Cards{DB: db, Dialect: dialect}, + Automation: &AutomationRules{DB: db, Dialect: dialect}, + Orders: &Orders{DB: db, Dialect: dialect}, + Reconciliations: &OrderReconciliations{DB: db}, + OrderRefreshJobs: &OrderRefreshJobs{DB: db}, + Keywords: &Keywords{DB: db, Dialect: dialect}, + DefaultReps: &DefaultReplies{DB: db, Dialect: dialect}, + ItemReps: &ItemReplies{DB: db, Dialect: dialect}, + AIReply: &AIReply{DB: db, Dialect: dialect, codec: codec}, + Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec}, + Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec}, + UserSettings: &UserSettings{DB: db, Dialect: dialect}, + WSMessages: &WSMessageStore{DB: db}, + PublishBatches: &ItemPublishBatches{DB: db}, + Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec}, + Renewal: &RenewalStore{DB: db, Dialect: dialect}, + LoginLogs: &AccountLoginLogs{DB: db}, + RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect}, + Chats: &ChatStore{DB: db, Dialect: dialect}, + AccountTasks: &AccountTaskStore{DB: db, Dialect: dialect}, + Admin: &AdminQueries{DB: db}, + Analytics: &AnalyticsQueries{DB: db}, + credentialLocks: make(map[string]*credentialLockEntry), } } diff --git a/internal/server/application_services.go b/internal/server/application_services.go index ec7dd03..3228b7a 100644 --- a/internal/server/application_services.go +++ b/internal/server/application_services.go @@ -17,7 +17,7 @@ type applicationServices struct { // newApplicationServices 为指定 Server 装配全部应用服务实例。 func newApplicationServices(server *Server) *applicationServices { return &applicationServices{ - orders: &orderApplicationService{server: newServerOrderRuntime(server), repository: newStoreOrderRepository(server.Store)}, + orders: &orderApplicationService{server: newServerOrderRuntime(server), repository: newStoreOrderRepository(server.Store), refreshJobs: newStoreOrderRefreshJobRepository(server.Store)}, itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)}, accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store)}, communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)}, diff --git a/internal/server/order_handlers.go b/internal/server/order_handlers.go index f7d409f..e6eef2d 100644 --- a/internal/server/order_handlers.go +++ b/internal/server/order_handlers.go @@ -36,7 +36,7 @@ type orderDetailMTop interface { func (s *Server) mountOrdersReal(r chi.Router) { r.Get("/api/orders", s.listOrders) r.Get("/api/orders/{order_id}", s.getOrder) - r.Post("/api/orders/refresh", s.refreshOrders) + s.mountOrderRefreshJobRoutes(r, "/api") r.Post("/api/orders/{order_id}/refresh", s.refreshSingleOrder) r.Post("/api/orders/manual-ship", s.manualShipOrders) r.Post("/api/orders/import", s.importOrders) @@ -93,23 +93,6 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) { }) } -// refreshOrders 将 HTTP 请求转换为订单刷新应用服务调用并编码兼容响应。 -func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 - sess := auth.SessionFromContext(r.Context()) - // result、err 保存result、err,供当前处理流程使用 - result, err := s.orders().Refresh(r.Context(), sess.UserID, r.FormValue("cookie_id"), r.FormValue("status")) - if errors.Is(err, db.ErrForbidden) { - writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问") - return - } - if err != nil { - writeErr(w, http.StatusInternalServerError, "查询账号失败") - return - } - writeJSON(w, http.StatusOK, result) -} - // 订单发现阶段将远端订单索引与本地软删除状态保持一致。 func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, map[string]struct{}, error) { // discoverSoldOrders 拉取远端订单列表并同步本地订单索引。 discovered, updated := 0, 0 diff --git a/internal/server/order_handlers_extra_test.go b/internal/server/order_handlers_extra_test.go index 25d5c38..bf1e37e 100644 --- a/internal/server/order_handlers_extra_test.go +++ b/internal/server/order_handlers_extra_test.go @@ -15,6 +15,42 @@ import ( "xianyu-go/internal/db" ) +// waitOrderRefreshJob 等待订单刷新后台任务完成并返回具名刷新结果。 +func waitOrderRefreshJob(t *testing.T, handler http.Handler, cookie *http.Cookie, jobID string) orderRefreshResponse { + t.Helper() + // deadline 保存测试任务允许的最长等待时间。 + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + // req 保存当前任务状态查询请求。 + req := httptest.NewRequest(http.MethodGet, "/api/orders/refresh/"+jobID, nil) + req.AddCookie(cookie) + // rec 保存当前任务状态响应。 + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("refresh job status=%d body=%s", rec.Code, rec.Body.String()) + } + // status 保存任务状态响应。 + var status orderRefreshJobStatusResponse + // err 表示任务状态 JSON 解析错误。 + if err := json.Unmarshal(rec.Body.Bytes(), &status); err != nil { + t.Fatalf("decode refresh job status: %v", err) + } + if status.Status == "succeeded" { + if status.Result == nil { + t.Fatalf("succeeded refresh job has no result: %+v", status) + } + return *status.Result + } + if status.Status == "failed" { + t.Fatalf("refresh job failed: %+v", status) + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("refresh job %s did not complete", jobID) + return orderRefreshResponse{} +} + // TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。 func TestRefreshOrdersNoBrowser(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 @@ -31,9 +67,20 @@ func TestRefreshOrdersNoBrowser(t *testing.T) { // rec 保存rec,供当前处理流程使用 rec := httptest.NewRecorder() h.ServeHTTP(rec, req) - if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "订单列表同步完成") { + if rec.Code != http.StatusAccepted { t.Fatalf("无浏览器仍应同步列表,got %d body=%s", rec.Code, rec.Body.String()) } + // start 保存后台任务创建响应。 + var start orderRefreshJobStartResponse + // err 表示任务创建响应 JSON 解析错误。 + if err := json.Unmarshal(rec.Body.Bytes(), &start); err != nil { + t.Fatal(err) + } + // result 保存完成后的订单刷新结果。 + result := waitOrderRefreshJob(t, h, cookie, start.JobID) + if !strings.Contains(result.Message, "订单列表同步完成") { + t.Fatalf("refresh result=%+v", result) + } } // TestRefreshOrdersDiscoversNewOrdersWithoutBrowser 负责TestRefresh订单列表DiscoversNew订单列表Without浏览器相关处理。 @@ -65,9 +112,20 @@ func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) { // rec 保存rec,供当前处理流程使用 rec := httptest.NewRecorder() h.ServeHTTP(rec, req) - if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"discovered":1`) { + if rec.Code != http.StatusAccepted { t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) } + // start 保存后台任务创建响应。 + var start orderRefreshJobStartResponse + // err 表示任务创建响应 JSON 解析错误。 + if err := json.Unmarshal(rec.Body.Bytes(), &start); err != nil { + t.Fatal(err) + } + // result 保存完成后的订单刷新结果。 + result := waitOrderRefreshJob(t, h, cookie, start.JobID) + if result.Summary.Discovered != 1 { + t.Fatalf("refresh result=%+v", result) + } // order、err 保存order、err,供当前处理流程使用 order, err := store.Orders.Get(context.Background(), "sold-new-1") if err != nil { @@ -168,9 +226,20 @@ func TestRefreshOrdersSoftDeletesOrdersMissingFromSellerList(t *testing.T) { // rec 保存rec,供当前处理流程使用 rec := httptest.NewRecorder() h.ServeHTTP(rec, req) - if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"soft_deleted":1`) { + if rec.Code != http.StatusAccepted { t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) } + // start 保存后台任务创建响应。 + var start orderRefreshJobStartResponse + // err 表示任务创建响应 JSON 解析错误。 + if err := json.Unmarshal(rec.Body.Bytes(), &start); err != nil { + t.Fatal(err) + } + // result 保存完成后的订单刷新结果。 + result := waitOrderRefreshJob(t, h, cookie, start.JobID) + if result.Summary.SoftDeleted != 1 { + t.Fatalf("refresh result=%+v", result) + } // deletedAt 保存deletedAt,供当前处理流程使用 var deletedAt string if // err 保存err,供当前处理流程使用 diff --git a/internal/server/order_refresh_job_handlers.go b/internal/server/order_refresh_job_handlers.go new file mode 100644 index 0000000..926ab34 --- /dev/null +++ b/internal/server/order_refresh_job_handlers.go @@ -0,0 +1,204 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "time" + + "github.com/go-chi/chi/v5" + orderapp "xianyu-go/internal/application/orders" + + "xianyu-go/internal/auth" +) + +// orderRefreshJobTimeout 限制单个订单刷新后台任务的最长执行时间。 +const orderRefreshJobTimeout = 30 * time.Minute + +// orderRefreshJobLease 为运行中的订单刷新任务提供可恢复租约。 +const orderRefreshJobLease = orderRefreshJobTimeout + time.Minute + +// orderRefreshJobStartResponse 是创建订单刷新任务后的响应 DTO。 +type orderRefreshJobStartResponse struct { + // Success 表示任务是否成功创建。 + Success bool `json:"success"` + // JobID 是后台任务标识。 + JobID string `json:"job_id"` + // Status 是任务初始状态。 + Status string `json:"status"` +} + +// orderRefreshJobStatusResponse 是订单刷新任务查询响应 DTO。 +type orderRefreshJobStatusResponse struct { + // Success 表示查询是否成功。 + Success bool `json:"success"` + // JobID 是后台任务标识。 + JobID string `json:"job_id"` + // Status 是 queued/running/succeeded/failed 任务状态。 + Status string `json:"status"` + // ErrorMessage 是任务失败原因。 + ErrorMessage string `json:"error_message,omitempty"` + // Result 是任务成功后的订单刷新结果。 + Result *orderRefreshResponse `json:"result,omitempty"` +} + +// mountOrderRefreshJobRoutes 挂载订单刷新后台任务端点。 +func (s *Server) mountOrderRefreshJobRoutes(r chi.Router, prefix string) { + r.Post(prefix+"/orders/refresh", s.startOrderRefreshJob) + r.Get(prefix+"/orders/refresh/{job_id}", s.getOrderRefreshJob) +} + +// startOrderRefreshJob 创建订单刷新任务并立即返回任务标识。 +func (s *Server) startOrderRefreshJob(w http.ResponseWriter, r *http.Request) { + // sess 保存当前认证会话。 + sess := auth.SessionFromContext(r.Context()) + // cookieID、filterStatus 保存订单刷新筛选条件。 + cookieID, filterStatus := r.FormValue("cookie_id"), r.FormValue("status") + if cookieID != "" && !s.orders().orderOwnedByUser(r.Context(), sess.UserID, cookieID) { + writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问") + return + } + // job 保存待持久化的订单刷新任务。 + job := &orderapp.RefreshJob{ + ID: "order-refresh-" + randomHex(16), UserID: sess.UserID, + CookieID: cookieID, FilterStatus: filterStatus, + } + // err 表示创建任务的数据库错误。 + if err := s.orders().refreshJobs.Create(r.Context(), job); err != nil { + writeErr(w, http.StatusInternalServerError, "创建订单刷新任务失败") + return + } + // token 保存本次执行者的租约令牌。 + token := randomHex(16) + // claimed、claimErr 保存任务抢占结果及错误。 + claimed, claimErr := s.orders().refreshJobs.Claim(r.Context(), job.ID, token, time.Now().Add(orderRefreshJobLease).Unix()) + if claimErr != nil || !claimed { + writeErr(w, http.StatusInternalServerError, "启动订单刷新任务失败") + return + } + s.startOrderRefreshWorker(job, token) + writeJSON(w, http.StatusAccepted, orderRefreshJobStartResponse{Success: true, JobID: job.ID, Status: "running"}) +} + +// getOrderRefreshJob 返回当前用户拥有的订单刷新任务状态和结果。 +func (s *Server) getOrderRefreshJob(w http.ResponseWriter, r *http.Request) { + // sess 保存当前认证会话。 + sess := auth.SessionFromContext(r.Context()) + // jobID 保存路径中的订单刷新任务标识。 + jobID := chi.URLParam(r, "job_id") + // job、err 保存任务读取结果及错误。 + job, err := s.orders().refreshJobs.Get(r.Context(), sess.UserID, jobID) + if errors.Is(err, orderapp.ErrRefreshJobNotFound) { + writeErr(w, http.StatusNotFound, "订单刷新任务不存在") + return + } + if err != nil { + writeErr(w, http.StatusInternalServerError, "读取订单刷新任务失败") + return + } + // response 保存任务状态响应 DTO。 + response := orderRefreshJobStatusResponse{Success: true, JobID: job.ID, Status: job.Status, ErrorMessage: job.ErrorMessage} + if job.ResultJSON != "" && job.ResultJSON != "{}" { + // result 保存成功任务的具名刷新结果。 + var result orderRefreshResponse + // err 表示任务结果 JSON 解析错误。 + if err := json.Unmarshal([]byte(job.ResultJSON), &result); err != nil { + if s.Logger != nil { + s.Logger.Error("解析订单刷新任务结果失败", "job_id", job.ID, "err", err) + } + writeErr(w, http.StatusInternalServerError, "读取订单刷新结果失败") + return + } + response.Result = &result + } + writeJSON(w, http.StatusOK, response) +} + +// startOrderRefreshWorker 启动受 Server 生命周期管理的订单刷新 worker。 +func (s *Server) startOrderRefreshWorker(job *orderapp.RefreshJob, token string) { + if job == nil { + return + } + s.startBackgroundTask("订单刷新任务", func() { + // parent 保存 Server 生命周期上下文,避免 HTTP 请求结束取消后台任务。 + parent := s.lifecycleContext() + // jobCtx、cancel 限制后台任务执行时间。 + jobCtx, cancel := context.WithTimeout(parent, orderRefreshJobTimeout) + defer cancel() + s.runOrderRefreshJob(jobCtx, job, token) + }) +} + +// runOrderRefreshJob 执行订单刷新并以租约令牌写入成功或失败终态。 +func (s *Server) runOrderRefreshJob(ctx context.Context, job *orderapp.RefreshJob, token string) { + // result、err 保存订单刷新业务结果及错误。 + result, err := s.orders().Refresh(ctx, job.UserID, job.CookieID, job.FilterStatus) + if err != nil { + // completeErr 表示失败终态写入错误。 + if _, completeErr := s.orders().refreshJobs.Complete(context.Background(), job.ID, token, "failed", "{}", err.Error()); completeErr != nil && s.Logger != nil { + s.Logger.Warn("写入订单刷新失败终态失败", "job_id", job.ID, "err", completeErr) + } + return + } + // resultJSON、marshalErr 保存具名刷新结果 JSON 及序列化错误。 + resultJSON, marshalErr := json.Marshal(result) + if marshalErr != nil { + _, _ = s.orders().refreshJobs.Complete(context.Background(), job.ID, token, "failed", "{}", marshalErr.Error()) + return + } + // completeErr 表示成功终态写入错误。 + if _, completeErr := s.orders().refreshJobs.Complete(context.Background(), job.ID, token, "succeeded", string(resultJSON), ""); completeErr != nil && s.Logger != nil { + s.Logger.Warn("写入订单刷新成功终态失败", "job_id", job.ID, "err", completeErr) + } +} + +// RunOrderRefreshRecovery 扫描并重新执行租约过期的订单刷新任务。 +func (s *Server) RunOrderRefreshRecovery(ctx context.Context) { + s.recoverOrderRefreshJobsOnce(ctx) + // ticker 保存恢复扫描间隔计时器。 + ticker := time.NewTicker(time.Minute) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + s.recoverOrderRefreshJobsOnce(ctx) + } + } +} + +// StartOrderRefreshRecovery 启动受 Server 生命周期管理的订单刷新恢复扫描器。 +func (s *Server) StartOrderRefreshRecovery(ctx context.Context) { + s.startBackgroundTask("订单刷新恢复扫描器", func() { + s.RunOrderRefreshRecovery(ctx) + }) +} + +// recoverOrderRefreshJobsOnce 将过期任务重新入队并启动新的 worker。 +func (s *Server) recoverOrderRefreshJobsOnce(ctx context.Context) { + // jobs、err 保存可恢复任务及扫描错误。 + jobs, err := s.orders().refreshJobs.Recoverable(ctx, time.Now().Unix(), 20) + if err != nil { + if s.Logger != nil { + s.Logger.Warn("扫描订单刷新恢复任务失败", "err", err) + } + return + } + // job 表示当前待恢复的订单刷新任务。 + for _, job := range jobs { + // requeued、requeueErr 保存重新入队结果及错误。 + requeued, requeueErr := s.orders().refreshJobs.RequeueExpired(ctx, job.ID, time.Now().Unix()) + if requeueErr != nil || !requeued { + continue + } + // token 保存恢复 worker 的新租约令牌。 + token := randomHex(16) + // claimed、claimErr 保存恢复任务抢占结果及错误。 + claimed, claimErr := s.orders().refreshJobs.Claim(ctx, job.ID, token, time.Now().Add(orderRefreshJobLease).Unix()) + if claimErr == nil && claimed { + s.startOrderRefreshWorker(&job, token) + } + } +} diff --git a/internal/server/order_repository.go b/internal/server/order_repository.go index 5890200..9eb19cc 100644 --- a/internal/server/order_repository.go +++ b/internal/server/order_repository.go @@ -3,6 +3,7 @@ package server import ( "context" "database/sql" + "errors" orderapp "xianyu-go/internal/application/orders" "xianyu-go/internal/db" ) @@ -234,6 +235,78 @@ func (r storeOrderRepository) ListOrdersByCookieCursor(ctx context.Context, cook return orderRowsFromDB(rows), nil } +// Create 创建订单刷新后台任务并同步应用层模型默认值。 +func (r storeOrderRepository) Create(ctx context.Context, job *orderapp.RefreshJob) error { + // dbJob 保存待写入的数据库任务模型。 + dbJob := &db.OrderRefreshJob{ + ID: job.ID, UserID: job.UserID, CookieID: job.CookieID, FilterStatus: job.FilterStatus, + Status: job.Status, ResultJSON: job.ResultJSON, ErrorMessage: job.ErrorMessage, + WorkerToken: job.WorkerToken, LeaseExpiresAt: job.LeaseExpiresAt, + } + // err 表示数据库任务创建错误。 + if err := r.store.OrderRefreshJobs.Create(ctx, dbJob); err != nil { + return err + } + job.Status, job.ResultJSON = dbJob.Status, dbJob.ResultJSON + return nil +} + +// Get 按用户读取订单刷新后台任务并转换为应用层模型。 +func (r storeOrderRepository) Get(ctx context.Context, userID int64, id string) (*orderapp.RefreshJob, error) { + // job、err 保存数据库任务读取结果及错误。 + job, err := r.store.OrderRefreshJobs.Get(ctx, userID, id) + if errors.Is(err, db.ErrNotFound) { + return nil, orderapp.ErrRefreshJobNotFound + } + if err != nil { + return nil, err + } + return refreshJobFromDB(job), nil +} + +// Claim 原子抢占订单刷新后台任务。 +func (r storeOrderRepository) Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error) { + return r.store.OrderRefreshJobs.Claim(ctx, id, token, leaseExpiresAt) +} + +// Complete 以租约令牌安全写入订单刷新后台任务终态。 +func (r storeOrderRepository) Complete(ctx context.Context, id, token, status, resultJSON, errorMessage string) (bool, error) { + return r.store.OrderRefreshJobs.Complete(ctx, id, token, status, resultJSON, errorMessage) +} + +// Recoverable 查询租约过期的订单刷新后台任务。 +func (r storeOrderRepository) Recoverable(ctx context.Context, now int64, limit int) ([]orderapp.RefreshJob, error) { + // jobs、err 保存数据库层可恢复任务及查询错误。 + jobs, err := r.store.OrderRefreshJobs.Recoverable(ctx, now, limit) + if err != nil { + return nil, err + } + // converted 保存转换后的应用层任务列表。 + converted := make([]orderapp.RefreshJob, 0, len(jobs)) + for _, job := range jobs { // job 表示当前待转换的数据库任务。 + converted = append(converted, *refreshJobFromDB(&job)) + } + return converted, nil +} + +// RequeueExpired 将过期订单刷新后台任务恢复为 queued。 +func (r storeOrderRepository) RequeueExpired(ctx context.Context, id string, now int64) (bool, error) { + return r.store.OrderRefreshJobs.RequeueExpired(ctx, id, now) +} + +// refreshJobFromDB 将数据库任务模型转换为应用层任务模型。 +func refreshJobFromDB(job *db.OrderRefreshJob) *orderapp.RefreshJob { + if job == nil { + return nil + } + return &orderapp.RefreshJob{ + ID: job.ID, UserID: job.UserID, CookieID: job.CookieID, FilterStatus: job.FilterStatus, + Status: job.Status, ResultJSON: job.ResultJSON, ErrorMessage: job.ErrorMessage, + WorkerToken: job.WorkerToken, LeaseExpiresAt: job.LeaseExpiresAt, + CreatedAt: job.CreatedAt, UpdatedAt: job.UpdatedAt, + } +} + // newStoreOrderRepository 从完整 Store 构造订单应用服务窄 repository。 func newStoreOrderRepository(store *db.Store) orderapp.Repository { if store == nil || store.Cookies == nil || store.Orders == nil || store.Items == nil { @@ -242,7 +315,16 @@ func newStoreOrderRepository(store *db.Store) orderapp.Repository { return storeOrderRepository{store: store} } +// newStoreOrderRefreshJobRepository 构造订单刷新任务持久化适配器。 +func newStoreOrderRefreshJobRepository(store *db.Store) orderapp.RefreshJobRepository { + if store == nil || store.OrderRefreshJobs == nil { + return nil + } + return storeOrderRepository{store: store} +} + // 确保 Store 适配器始终覆盖订单应用服务所需的全部能力。 var _ orderapp.Repository = storeOrderRepository{} var _ orderapp.UnitOfWork = storeOrderRepository{} var _ orderapp.Writer = storeOrderWriter{} +var _ orderapp.RefreshJobRepository = storeOrderRepository{} diff --git a/internal/server/order_service.go b/internal/server/order_service.go index a86d46d..92ab37c 100644 --- a/internal/server/order_service.go +++ b/internal/server/order_service.go @@ -146,6 +146,8 @@ type orderApplicationService struct { server orderRuntimePort // repository 提供订单用例所需的应用层持久化与凭证锁 Port。 repository orderapp.Repository + // refreshJobs 提供订单刷新后台任务的持久化 Port。 + refreshJobs orderapp.RefreshJobRepository } // orderRefreshWrite 保存已从平台成功获取、等待同一事务批量写入的订单详情。 diff --git a/internal/server/versioned_order_contract_test.go b/internal/server/versioned_order_contract_test.go index 5f3393b..af8a818 100644 --- a/internal/server/versioned_order_contract_test.go +++ b/internal/server/versioned_order_contract_test.go @@ -124,15 +124,17 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T // refreshRecorder 是捕获版本化刷新响应的记录器。 refreshRecorder := httptest.NewRecorder() handler.ServeHTTP(refreshRecorder, refreshReq) - if refreshRecorder.Code != http.StatusOK { + if refreshRecorder.Code != http.StatusAccepted { t.Fatalf("versioned order refresh status=%d body=%s", refreshRecorder.Code, refreshRecorder.Body.String()) } - // refreshValue 是版本化刷新响应 DTO。 - var refreshValue orderRefreshResponse - // refreshDecodeErr 是刷新响应反序列化失败的原因。 - if refreshDecodeErr := json.Unmarshal(refreshRecorder.Body.Bytes(), &refreshValue); refreshDecodeErr != nil { + // refreshStart 是版本化刷新任务创建响应 DTO。 + var refreshStart orderRefreshJobStartResponse + // refreshDecodeErr 是刷新任务创建响应反序列化失败的原因。 + if refreshDecodeErr := json.Unmarshal(refreshRecorder.Body.Bytes(), &refreshStart); refreshDecodeErr != nil { t.Fatalf("decode versioned order refresh: %v", refreshDecodeErr) } + // refreshValue 是版本化刷新任务完成后的具名结果。 + refreshValue := waitOrderRefreshJob(t, handler, sessionCookie, refreshStart.JobID) if refreshValue.Message == "" { t.Fatalf("versioned order refresh should preserve a named success response: %+v", refreshValue) } @@ -143,9 +145,16 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T // legacyRefreshRecorder 是捕获旧刷新响应的记录器。 legacyRefreshRecorder := httptest.NewRecorder() handler.ServeHTTP(legacyRefreshRecorder, legacyRefreshReq) - if legacyRefreshRecorder.Code != http.StatusOK { + if legacyRefreshRecorder.Code != http.StatusAccepted { t.Fatalf("legacy order refresh status=%d body=%s", legacyRefreshRecorder.Code, legacyRefreshRecorder.Body.String()) } + // legacyRefreshStart 是旧路径刷新任务创建响应 DTO。 + var legacyRefreshStart orderRefreshJobStartResponse + // err 表示旧路径任务创建响应解析错误。 + if err := json.Unmarshal(legacyRefreshRecorder.Body.Bytes(), &legacyRefreshStart); err != nil { + t.Fatalf("decode legacy order refresh: %v", err) + } + waitOrderRefreshJob(t, handler, sessionCookie, legacyRefreshStart.JobID) // singleInsertErr 是单订单刷新夹具写入失败的原因。 _, singleInsertErr := store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id) VALUES ('order-single-v1','item-v1','buyer-v1','pending_ship','acc1')`) diff --git a/internal/server/versioned_order_routes.go b/internal/server/versioned_order_routes.go index bb53152..4f18aa0 100644 --- a/internal/server/versioned_order_routes.go +++ b/internal/server/versioned_order_routes.go @@ -15,7 +15,7 @@ func (s *Server) mountVersionedOrders(r chi.Router) { r.Get("/api/v1/orders/{order_id}", s.getOrder) r.Put("/api/v1/orders/{order_id}", s.updateOrder) r.Delete("/api/v1/orders/{order_id}", s.deleteOrder) - r.Post("/api/v1/orders/refresh", s.refreshOrders) + s.mountOrderRefreshJobRoutes(r, "/api/v1") r.Post("/api/v1/orders/manual-ship", s.manualShipOrders) r.Post("/api/v1/orders/import", s.importOrders) r.Post("/api/v1/orders/{order_id}/refresh", s.refreshSingleOrder) diff --git a/internal/webui/static/assets/index-C70ijd-m.js b/internal/webui/static/assets/index-B7YpmDTE.js similarity index 67% rename from internal/webui/static/assets/index-C70ijd-m.js rename to internal/webui/static/assets/index-B7YpmDTE.js index f69ae4c..09bc879 100644 --- a/internal/webui/static/assets/index-C70ijd-m.js +++ b/internal/webui/static/assets/index-B7YpmDTE.js @@ -1,20 +1,20 @@ -import{j as e,r,c as Is,b as Oe,d as ir}from"./react-vendor-C_od1ZSF.js";import{L as or,U as va,M as ys,C as Os,B as Na,S as _a,Z as js,a as Rt,b as Ps,G as Bs,c as Ts,d as Es,e as cr,f as wa,g as ut,A as Fs,D as dr,P as ka,h as Bt,E as Ca,T as xr,i as mr,j as _e,X as ke,k as ur,l as pr,m as Ds,n as Sa,o as lt,p as Ye,q as La,K as hr,r as bt,s as mt,Q as rs,t as yt,u as wt,v as $t,R as We,w as Ra,x as gr,y as Ze,z as St,F as Mt,H as nt,I as zs,J as kt,N as br,O as fr,V as yr,W as Aa,Y as Ia,_ as Oa,$ as jr,a0 as vr,a1 as ls,a2 as Wt,a3 as vs,a4 as Nr,a5 as _r,a6 as Ns,a7 as Us,a8 as wr,a9 as kr,aa as qt,ab as Ws,ac as Zt,ad as Pa,ae as Cr,af as Sr,ag as ss,ah as Ta,ai as Lr,aj as Rr,ak as Ar,al as Ir,am as Or,an as Pr,ao as Js}from"./icons-vendor-i_74xDZy.js";import{R as Yt,B as Tr,X as Gs,Y as Ks,T as Xt,a as Er,C as _s,A as Dr,b as $r,c as Mr,P as Vs,d as Qs,L as qr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const c of n)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(n){const c={};return n.integrity&&(c.integrity=n.integrity),n.referrerPolicy&&(c.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?c.credentials="include":n.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function l(n){if(n.ep)return;n.ep=!0;const c=a(n);fetch(n.href,c)}})();const Br=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ws=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),e.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:e.jsx(Br,{className:s})})]})]}),Fr=3e4,zr=10*6e4;let ns=!1;const Ea=()=>{ns||typeof window>"u"||(ns=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{ns=!1}))},Ur=t=>{if(!t)return"";const s=new URLSearchParams;for(const[l,n]of Object.entries(t))n!=null&&s.set(l,String(n));const a=s.toString();return a?`?${a}`:""},as=async(t,s,a={})=>{var j;const l=Ur(a.params),n=`${s}${l}`,c=Da(a.signal,a.timeoutMs??Fr);let u;try{u=await fetch(n,{method:t,credentials:"include",signal:c.signal,headers:{...a.body===void 0?{}:{"Content-Type":"application/json"}},body:a.body===void 0?void 0:JSON.stringify(a.body)})}catch(x){throw c.signal.aborted?new Error((j=a.signal)!=null&&j.aborted?"请求已取消":"请求超时,请稍后重试"):x}finally{c.cleanup()}const m=(u.headers.get("content-type")||"").includes("application/json");if(!u.ok){u.status===401&&!a.skipAuthLogout&&Ea();const x=m?await u.json().catch(()=>{}):await u.text().catch(()=>{}),p=$a(x,u.status);throw new Error(p)}return m?await u.json():await u.text()},ye=async(t,s,a)=>as("GET",t,{params:s,...a}),je=async(t,s,a)=>as("POST",t,{body:s,...a}),ze=async(t,s,a)=>as("PUT",t,{body:s,...a}),et=async(t,s,a)=>as("DELETE",t,{params:s,...a}),At=async(t,s,a={})=>{var m;const l=Da(a.signal,a.timeoutMs??zr);let n;try{n=await fetch(t,{method:"POST",credentials:"include",signal:l.signal,body:s})}catch(j){throw l.signal.aborted?new Error((m=a.signal)!=null&&m.aborted?"请求已取消":"上传超时,请稍后重试"):j}finally{l.cleanup()}const h=(n.headers.get("content-type")||"").includes("application/json")?await n.json().catch(()=>{}):await n.text().catch(()=>{});if(!n.ok){n.status===401&&Ea();const j=$a(h,n.status),x=new Error(j);throw x.payload=h,x}return h},Da=(t,s)=>{const a=new AbortController,l=()=>a.abort(t==null?void 0:t.reason);t!=null&&t.aborted?l():t==null||t.addEventListener("abort",l,{once:!0});const n=globalThis.setTimeout(()=>a.abort(new DOMException("timeout","TimeoutError")),Math.max(1,s));return{signal:a.signal,cleanup:()=>{globalThis.clearTimeout(n),t==null||t.removeEventListener("abort",l)}}},Wr=t=>{if(typeof t!="object"||t===null)return!1;const s=t;return typeof s.code=="string"&&typeof s.message=="string"},$a=(t,s)=>typeof t=="string"?t:Wr(t)?t.message:`请求失败: ${s}`,es=t=>{const s=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${s}-${a}-${l}`},$s=(t,s)=>{const a=new Date(t);return a.setHours(12,0,0,0),a.setDate(a.getDate()+s),a},ks=(t,s)=>({startDate:es($s(t,-(s-1))),endDate:es(t)}),Ma=(t,s=new Date,a="",l="")=>{if(t==="custom"&&a&&l){if(a>l)throw new Error("开始日期不能晚于结束日期");return{startDate:a,endDate:l}}return t==="yesterday"?ks($s(s,-1),1):ks(s,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Jr=t=>{const s=new Date(`${t.startDate}T12:00:00`),a=new Date(`${t.endDate}T12:00:00`),l=Math.round((a.getTime()-s.getTime())/864e5)+1,n=$s(s,-1);return ks(n,l)},Gr=t=>{const s={...t},a=["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"];for(const l of a){const n=`${l}_configured`;n in s&&(s[n]=s[n]===!0||s[n]==="true")}if("renewal_log_retention_days"in s){const l=Number(s.renewal_log_retention_days);s.renewal_log_retention_days=Number.isFinite(l)?l:10}return s},Kr=async t=>je("/api/v1/session/login",t,{skipAuthLogout:!0}),Vr=async t=>je("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),qa=async t=>ye("/api/v1/session",void 0,t),Qr=async t=>ye("/health",void 0,t),Hr=async()=>je("/api/v1/session/logout",{}),Zr=async(t,s)=>ze("/api/v1/session/credentials",t,s),Yr=(t,s)=>{const a=t.avatar_url||"";if(!a)return"";try{const l=new URL(a,window.location.origin);return l.hostname.endsWith("alicdn.com")&&l.searchParams.set("_v",s),l.toString()}catch{return a}},Ft=async t=>{const s=await ye("/api/v1/accounts/details",void 0,t),a=Date.now().toString();return s.map(l=>({id:l.id,value:"",enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password:"",show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:Yr(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},Hs=async(t,s)=>ye(`/api/v1/account-tasks/${t}`,void 0,s),Zs=async(t,s,a)=>ze(`/api/v1/account-tasks/${t}`,s,a),Xr=async(t,s,a)=>je(`/api/v1/account-tasks/${t}/run`,{task_type:s},{timeoutMs:12e4,...a}),is=async(t,s,a,l=!1)=>{const n=await ye("/api/v1/chat/sessions",{account_id:t,cursor:s,refresh:l?1:void 0},l?{timeoutMs:6e4,...a}:a);return{sessions:n.sessions||[],has_more:n.has_more===!0,next_cursor:n.next_cursor}},Ys=async(t,s,a,l,n)=>{const c=await ye("/api/v1/chat/messages",{account_id:t,chat_id:s,cursor:a,before_id:l},n);return{messages:c.messages||[],has_more:c.has_more===!0,next_cursor:c.next_cursor,session:c.session}},el=async(t,s)=>je("/api/v1/chat/messages",t,s),tl=async(t,s)=>{const a=new FormData;return Object.entries(t).forEach(([l,n])=>a.append(l,n)),At("/api/v1/chat/images",a,{timeoutMs:12e4,...s})},Xs=async(t,s,a)=>je("/api/v1/chat/read",{account_id:t,chat_id:s},a),Cs=async t=>ye("/api/v1/accounts/runtime-status",void 0,t),sl=async t=>je("/api/v1/qr-login/generate",void 0,{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),al=async(t,s)=>ye(`/api/v1/qr-login/check/${t}`,void 0,{signal:s,timeoutMs:1e4}),rl=async(t,s)=>je(`/api/v1/qr-login/complete-verification/${t}`,{target_account_id:s||""}),ll=async(t,s)=>ze(`/api/v1/accounts/${t}/status`,{enabled:s}),nl=async t=>et(`/api/v1/accounts/${t}`),il=async(t,s,a)=>ze(`/api/v1/accounts/${t}/pause-duration`,{pause_duration:s},a),ol=async(t,s,a)=>ze(`/api/v1/accounts/${t}/settings`,s,a),cl=async(t,s)=>ye(`/api/v1/accounts/${t}/long-login`,void 0,s),dl=async(t,s,a)=>ze(`/api/v1/accounts/${t}/long-login`,{enabled:s},a),xl=async(t,s)=>je("/api/v1/password-login",t,s),ml=async(t,s)=>ye(`/api/v1/password-login/check/${t}`,void 0,{signal:s,timeoutMs:1e4}),ul=async(t,s)=>et(`/api/v1/password-login/cancel/${t}`,void 0,s),pl=async t=>je(`/api/v1/accounts/${t}/refresh-profile`,{}),hl=async t=>ye("/api/v1/settings/ai-reply",void 0,t),Ba=t=>{const s=String(t||"");return s==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(s)?s:"unknown"},gl=async(t,s,a=1,l=20,n,c)=>{const u={page:a,page_size:l};t&&(u.cookie_id=t),s&&s!=="all"&&(u.status=s),n!=null&&n.trim()&&(u.search=n.trim());const h=await ye("/api/v1/orders",u,c),j=(h.orders||h.data||[]).map(x=>({...x,id:x.id||x.order_id,status:Ba(x.status||x.order_status),quantity:Number(x.quantity||1)}));return{success:!0,data:j,total:h.total||j.length,page:h.page||a,page_size:h.page_size||l,total_pages:h.total_pages||1}},bl=async(t,s)=>ze(`/api/v1/orders/${t}`,s),fl=async t=>et(`/api/v1/orders/${t}`),yl=async(t,s)=>{const a=new FormData;return t&&a.append("cookie_id",t),s&&a.append("status",s),At("/api/v1/orders/refresh",a)},jl=async t=>je(`/api/v1/orders/${t}/refresh`),vl=async(t,s)=>je("/api/v1/orders/manual-ship",{order_ids:t,ship_mode:s}),Nl=async(t,s)=>t instanceof FormData?At("/api/v1/orders/import",t,s):je("/api/v1/orders/import",t,s),_l=async t=>ye("/api/v1/analytics/dashboard",void 0,t),ea=async(t=7,s)=>{let a;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),a={start_date:es(n),end_date:es(l)}}else a=t;return ye("/api/v1/analytics/orders",{...a,timezone_offset_minutes:-new Date().getTimezoneOffset()},s)},wl=async(t,s)=>{const a=await ye("/api/v1/analytics/orders/valid",{start_date:t.start_date,end_date:t.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()},s),n=(Array.isArray(a)?a:a.orders||[]).map(c=>({...c,id:c.id||c.order_id,status:Ba(c.status||c.order_status),quantity:Number(c.quantity||1)}));return{orders:n,total:Array.isArray(a)?n.length:Number(a.total??n.length),truncated:Array.isArray(a)?!1:a.truncated===!0}},kl=t=>{let s=t.api_config;if(typeof s=="string"&&s.trim())try{s=JSON.parse(s)}catch{s=void 0}return{...t,api_config:s||void 0}},Fa=t=>({...t,api_config:t.api_config?JSON.stringify(t.api_config):""}),Ms=async t=>{const s=await ye("/api/v1/cards",void 0,t);return(Array.isArray(s)?s:s.cards||[]).map(kl)},Cl=async t=>je("/api/v1/cards",Fa(t)),ta=async(t,s)=>ze(`/api/v1/cards/${t}`,Fa(s)),Sl=async t=>et(`/api/v1/cards/${t}`),Ll=async(t,s)=>{const a=new FormData;return a.append("file",t),At("/api/v1/cards/batch",a,s)},Rl=async(t,s,a)=>je(`/api/v1/cards/${t}/append-data`,{content:s},a),os=t=>t===!0||t===1||t==="1",Lt=async(t,s)=>{const a=await ye("/api/v1/items",void 0,s);return(Array.isArray(a)?a:a.items||[]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:os(n.is_multi_spec),is_multi_qty_ship:os(n.is_multi_qty_ship??n.multi_quantity_delivery),multi_quantity_delivery:os(n.multi_quantity_delivery??n.is_multi_qty_ship)}))},Al=async t=>je("/api/v1/items/get-all-from-account",{cookie_id:t}),Il=async(t,s)=>et(`/api/v1/items/${t}/${s}`),Ol=async(t,s)=>je(`/api/v1/items/${t}`,s),Pl=async t=>{const s=new FormData;s.set("cookie_id",t.cookie_id),s.set("title",t.title),s.set("description",t.description),s.set("price",t.price),s.set("original_price",t.original_price||""),s.set("quantity",String(t.quantity)),s.set("postage_mode",t.postage_mode),s.set("postage",t.postage||""),t.location&&s.set("location",JSON.stringify(t.location));for(const a of t.images)s.append("images",a);return At("/api/v1/items/publish",s)},Tl=async(t,s)=>je("/api/v1/items/publish-categories/recommend",{cookie_id:t,keyword:s}),El=async t=>{const s=new FormData;return s.set("file",t.file),t.imagesZip&&s.set("images_zip",t.imagesZip),t.defaultCookieId&&s.set("default_cookie_id",t.defaultCookieId),s.set("fallback_category_id",t.fallbackCategory.catId),s.set("fallback_category_name",t.fallbackCategory.catName),s.set("fallback_channel_category_id",t.fallbackCategory.channelCatId||""),s.set("fallback_tb_category_id",t.fallbackCategory.tbCatId||""),t.location&&s.set("location",JSON.stringify(t.location)),At("/api/v1/items/publish-batches/preview",s)},Dl=async t=>je("/api/v1/items/publish-batches",{preview_id:t}),vt=async t=>ye(`/api/v1/items/publish-batches/${t}`),za=async(t=20)=>{const s=await ye("/api/v1/items/publish-batches",{limit:t});return Array.isArray(s)?s:s.batches||[]},$l=async t=>et(`/api/v1/items/publish-batches/${t}`),Ml=async t=>je(`/api/v1/items/publish-batches/${t}/cancel`,{}),ql=async t=>je(`/api/v1/items/publish-batches/${t}/retry-failed`,{}),Bl=async(t,s,a)=>ze(`/api/v1/items/${t}/${s}`,a),Ua=t=>t.map(s=>{var a,l;return{id:String(s.id),name:s.name||"",trigger_type:s.trigger_type||"order_paid",item_keyword:s.item_title||s.item_id||"",cookie_id:s.cookie_id||"",item_id:s.item_id||"",item_title:s.item_title||"",card_group_id:Number(((a=(s.actions||[]).find(n=>n.action_type==="send_card"))==null?void 0:a.card_id)||0),card_group_name:((l=(s.actions||[]).find(n=>n.action_type==="send_card"))==null?void 0:l.card_name)||"",priority:s.priority||100,enabled:s.enabled||!1,config_json:s.config_json||"{}",actions:(s.actions||[]).map(n=>({id:n.id?String(n.id):void 0,action_type:n.action_type,card_id:Number(n.card_id||0),card_name:n.card_name||"",delivery_count:Number(n.delivery_count||1),message_template:n.message_template||"",delay_seconds:Number(n.delay_seconds||0),config_json:n.config_json||"{}",enabled:n.enabled!==!1,sort_order:Number(n.sort_order||0)})),variants:(s.actions||[]).filter(n=>n.action_type==="send_card").map(n=>{let c={};try{c=JSON.parse(n.config_json||"{}")}catch{}return{id:n.id?String(n.id):void 0,spec_name:c.spec_name||"",spec_value:c.spec_value||"",card_id:Number(n.card_id||0),card_name:n.card_name||"",delivery_count:Number(n.delivery_count||1),enabled:n.enabled!==!1,delay_override:c.delay_override===!0,delay_seconds:Number(n.delay_seconds||0),config_json:n.config_json||"{}"}})}}),Ss=async()=>{const t=await ye("/api/v1/automation-rules"),s=Array.isArray(t)?t:t.data||[];return Ua(s)},Fl=async({cookieId:t,triggerType:s,enabled:a,search:l,page:n=1,pageSize:c=10}={})=>{const u=await ye("/api/v1/automation-rules",{page:n,page_size:c,cookie_id:t||void 0,trigger_type:s||void 0,enabled:a,search:(l==null?void 0:l.trim())||void 0}),h=Ua(Array.isArray(u)?u:u.data||[]);return{success:!0,data:h,total:Number(Array.isArray(u)?h.length:u.total??h.length),page:Number(Array.isArray(u)?n:u.page??n),page_size:Number(Array.isArray(u)?c:u.page_size??c),total_pages:Number(Array.isArray(u)?h.length?1:0:u.total_pages??(h.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(Array.isArray(u)?{}:u.trigger_counts||{}).map(([m,j])=>[m,Number(j)]))}},zl=(t,s)=>{if(t!=="order_paid")return s.map((n,c)=>({...n,sort_order:n.sort_order||c+1}));const a=s.filter(n=>n.action_type==="send_card").map((n,c)=>({...n,sort_order:c+1})),l=s.filter(n=>n.action_type!=="send_card"&&n.action_type!=="confirm_shipment");return[...a,...l.map((n,c)=>({...n,sort_order:a.length+c+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:a.length+l.length+1}]},sa=async t=>{const s=t.trigger_type||"order_paid",l=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[s]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),n=(t.actions||[]).filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment"),c=t.variants&&t.variants.length>0?[...t.variants.map((m,j)=>({action_type:"send_card",card_id:m.card_id,delivery_count:m.delivery_count||1,enabled:m.enabled!==!1,sort_order:j+1,delay_seconds:m.delay_seconds||0,config_json:JSON.stringify({spec_name:m.spec_name||"",spec_value:m.spec_value||"",delay_override:m.delay_override===!0})})),...n]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],u=zl(s,c),h={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||l||"自动化规则",trigger_type:s,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:u.map((m,j)=>({action_type:m.action_type,card_id:m.card_id||0,delivery_count:m.delivery_count||1,message_template:m.message_template||"",delay_seconds:m.delay_seconds||0,config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:m.sort_order||j+1}))};return t.id?ze(`/api/v1/automation-rules/${t.id}`,h):je("/api/v1/automation-rules",h)},Ul=async t=>et(`/api/v1/automation-rules/${t}`),Wl=async()=>{const t=await ye("/api/v1/automation-issues");return{runs:Array.isArray(t==null?void 0:t.runs)?t.runs:[],pending_tasks:Array.isArray(t==null?void 0:t.pending_tasks)?t.pending_tasks:[]}},Jl=async(t,s)=>je(`/api/v1/automation-runs/${t}/resolve`,{resolution:s}),Gl=async(t,s)=>je(`/api/v1/automation-pending-tasks/${t}/resolve`,{resolution:s}),Kl=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Vl=async t=>{const s=await ye(`/api/v1/reply-rules/${t}/typed`);return Array.isArray(s)?s.map(Kl):[]},Ql=async t=>t?(await Vl(t)).map(a=>({id:a.id,keyword:a.keyword||"",reply_content:a.reply||"",match_type:"fuzzy",enabled:!0,item_id:a.item_id||"",type:a.type==="image"?"image":"text",image_url:a.image_url||""})):[],Hl=async(t,s)=>{const a=t.type||"text",l={keyword:t.keyword||"",reply:a==="text"&&t.reply_content||"",item_id:t.item_id||"",type:a,image_url:a==="image"&&t.image_url||""};return t.id?ze(`/api/v1/reply-rules/${s}/typed/${t.id}`,l):je(`/api/v1/reply-rules/${s}/items`,l)},Zl=async(t,s)=>et(`/api/v1/reply-rules/${s}/typed/${t}`),Yl=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),Xl=t=>{if("values"in t||"secrets"in t)return t;const s={},a={};for(const l of Object.entries(t)){const[n,c]=l;c!=null&&(Yl.has(n)?a[n]=c===""?{action:"clear"}:{action:"replace",value:String(c)}:s[n]=c)}return Object.keys(a).length>0?{values:s,secrets:a}:s},Wa=async t=>{const s=await ye("/api/v1/settings/system",void 0,t);return Gr(s.data||s)},Ja=async(t,s)=>{const a=Xl(t);return ze("/api/v1/settings/system",a,s)},en=async(t,s)=>ye(`/api/v1/settings/ai-reply/${t}`,void 0,s),tn=async(t,s,a)=>{const l={ai_enabled:s.ai_enabled??!1,max_discount_percent:s.max_discount_percent??10,max_discount_amount:s.max_discount_amount??100,max_bargain_rounds:s.max_bargain_rounds??3,custom_prompts:s.custom_prompts??""};return ze(`/api/v1/settings/ai-reply/${t}`,l,a)},sn=async(t,s="",a)=>(await je("/api/v1/settings/ai-models",{base_url:t,api_key:s},a)).models||[],an=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const s=JSON.parse(t);if(Array.isArray(s))return s.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},Ga=t=>{const s=Array.from(new Set((t||[]).filter(Boolean)));return s.length>0?JSON.stringify(s):""},Ka=async t=>({success:!0,data:(await ye("/api/v1/notifications/channels",void 0,t)||[]).map(l=>{let n;try{n=typeof l.config=="string"?JSON.parse(l.config):l.config}catch{n={}}return{id:String(l.id),name:l.name,type:l.type==="ding_talk"?"dingtalk":l.type==="lark"?"feishu":l.type,config:n,event_types:an(l.event_types),enabled:l.enabled,created_at:l.created_at,updated_at:l.updated_at}})}),rn=async(t,s)=>je("/api/v1/notifications/channels",{...t,config:JSON.stringify(t.config),event_types:Ga(t.event_types)},s),aa=async(t,s,a)=>{const l={...s};return"config"in s&&(l.config=JSON.stringify(s.config)),"event_types"in s&&(l.event_types=Ga(s.event_types)),ze(`/api/v1/notifications/channels/${t}`,l,a)},ln=async(t,s)=>et(`/api/v1/notifications/channels/${t}`,void 0,s),nn=async(t,s)=>{const a=await ye(`/api/v1/notifications/accounts/${t}/bindings`,void 0,s);return(a==null?void 0:a.channel_ids)||[]},on=async(t,s)=>je(`/api/v1/notifications/channels/${t}/test`,{},s),ra=async()=>ye("/api/v1/default-replies"),cn=async t=>{const s=await ye(`/api/v1/default-replies/${t}`);return{cookie_id:t,enabled:s.enabled||!1,reply_content:s.reply_content||"",reply_once:s.reply_once||!1,reply_image_url:s.reply_image_url||""}},dn=async(t,s)=>ze(`/api/v1/default-replies/${t}`,{enabled:s.enabled??!1,reply_content:s.reply_content||"",reply_once:s.reply_once??!1,reply_image_url:s.reply_image_url||""}),xn=async t=>et(`/api/v1/default-replies/${t}`),mn=async t=>je(`/api/v1/default-replies/${t}/clear-records`,{}),un=({activeTab:t,isAdmin:s=!1,collapsed:a,onToggleCollapsed:l,onNavigate:n,onLogout:c})=>{const[u,h]=r.useState({version:"dev",commit:"unknown"});r.useEffect(()=>{const x=new AbortController;return Qr({signal:x.signal}).then(p=>h({version:String(p.version||"dev"),commit:String(p.commit||"unknown")})).catch(p=>{p instanceof DOMException&&p.name}),(()=>x.abort())},[]);const m=[{id:"dashboard",icon:or,label:"仪表盘"},{id:"accounts",icon:va,label:"账号管理"},{id:"chat",icon:ys,label:"在线聊天"},{id:"cards",icon:Os,label:"卡密库存"},{id:"items",icon:Na,label:"商品列表"},{id:"orders",icon:_a,label:"订单管理"},{id:"rules",icon:js,label:"自动化规则"},{id:"notifications",icon:Rt,label:"通知设置"},...s?[{id:"settings",icon:Ps,label:"系统与AI"}]:[]],j=/^\d+\.\d+\.\d+$/.test(u.version)?`v${u.version}`:u.version;return e.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${a?"w-16":"w-64"}`,children:[e.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${a?"justify-center px-2":"gap-3 px-5"}`,children:[e.jsx(ws,{sizeClass:"h-10 w-10"}),!a&&e.jsxs("div",{className:"min-w-0 leading-tight",children:[e.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),e.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),e.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${a?"px-2":"px-3"}`,"aria-label":"主导航",children:m.map(x=>{const p=x.icon,_=t===x.id;return e.jsx(Is.Fragment,{children:e.jsxs("button",{type:"button",title:a?x.label:void 0,"aria-label":x.label,"aria-current":_?"page":void 0,onClick:(()=>n(x.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${a?"justify-center":"gap-3 px-3.5"} ${_?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(p,{className:`h-[19px] w-[19px] shrink-0 ${_?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!a&&e.jsx("span",{className:"truncate text-sm font-bold",children:x.label}),_&&!a&&e.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},x.id)})}),e.jsxs("div",{children:[e.jsx("div",{title:a?`版本 ${u.version} · ${u.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${a?"flex justify-center px-1":"px-6"}`,children:a?e.jsx(Bs,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${u.version}`}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[e.jsx(Bs,{className:"h-3.5 w-3.5"}),"运行版本"]}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[e.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:j}),e.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:u.commit})]})]})}),e.jsxs("div",{className:`space-y-2 p-2 ${a?"":"p-3"}`,children:[e.jsxs("button",{type:"button",onClick:l,title:a?"展开侧边栏":"收起侧边栏","aria-label":a?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${a?"justify-center":"gap-3 px-3"}`,children:[a?e.jsx(Ts,{className:"h-5 w-5"}):e.jsx(Es,{className:"h-5 w-5"}),!a&&e.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),e.jsxs("button",{type:"button",onClick:c,title:a?"退出登录":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 ${a?"justify-center":"gap-3 px-3"}`,children:[e.jsx(cr,{className:"h-5 w-5"}),!a&&e.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},It=t=>String(t).padStart(2,"0"),Ls=t=>{if(t==null||t==="")return"-";const s=t instanceof Date?t:new Date(t);return Number.isNaN(s.getTime())?"-":[s.getFullYear(),It(s.getMonth()+1),It(s.getDate())].join("-")+" "+[It(s.getHours()),It(s.getMinutes()),It(s.getSeconds())].join(":")},pn=t=>{const s={};return t.forEach(a=>{s[a.item_id]=a.item_title||a.item_id}),s},hn=t=>{var s;return((s=t.daily_stats)==null?void 0:s.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})))||[]},gn=(t,s)=>(t.item_stats||[]).map(a=>{const l=s[a.item_id]||a.item_id;return{name:l.length>12?`${l.substring(0,12)}...`:l,sales:a.order_count}}).sort((a,l)=>l.sales-a.sales).slice(0,10),bn=(t,s,a)=>{const l=t.revenue_stats.total_orders||0;return(t.item_stats||[]).map(n=>{const c=s[n.item_id]||n.item_id;return{name:c.length>10?`${c.substring(0,10)}...`:c,value:n.order_count,percent:l>0?n.order_count/l*100:0}}).sort((n,c)=>c.value-n.value).slice(0,6).map((n,c)=>({...n,color:a[c%a.length]}))},fn=(t,s,a)=>{const l=t.revenue_stats.total_amount||0;return(t.item_stats||[]).map(n=>{const c=s[n.item_id]||n.item_id;return{name:c.length>12?`${c.substring(0,12)}...`:c,value:n.total_amount,orderCount:n.order_count,percentage:l>0?n.total_amount/l*100:0}}).sort((n,c)=>c.value-n.value).slice(0,5).map((n,c)=>({...n,color:a[c%a.length],percentage:n.percentage.toFixed(1)}))},yn=(t,s)=>{if(!t||!s)return null;const a=t.revenue_stats.total_amount,l=s.revenue_stats.total_amount;if(l===0)return a>0?"+100%":"0%";const n=(a-l)/l*100;return`${n>=0?"+":""}${n.toFixed(1)}%`},jn=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",vn=t=>Math.max(...t.map(s=>s.sales),1),la=(t,s,a)=>t===s&&!a.aborted,na=t=>t instanceof Error&&t.message==="请求已取消",cs=(t,s)=>t instanceof Error?t.message:s,Nn=t=>{const{range:s,customStartDate:a,customEndDate:l,customRangeVersion:n}=t,[c,u]=r.useState(null),[h,m]=r.useState(null),[j,x]=r.useState({overview:"idle",range:"idle",error:""}),[p,_]=r.useState(0),S=r.useRef(0),q=r.useMemo(()=>({range:s,customStartDate:a,customEndDate:l}),[l,a,s]),w=r.useCallback(()=>_(F=>F+1),[]);r.useEffect(()=>{const F=new AbortController;return x(d=>({...d,overview:"loading",error:""})),Promise.all([_l({signal:F.signal}),Lt(void 0,{signal:F.signal})]).then(([d,B])=>{F.signal.aborted||(u({stats:d,items:B,itemNames:pn(B)}),x(Z=>({...Z,overview:"success"})))}).catch(d=>{F.signal.aborted||na(d)||x(B=>({...B,overview:"error",error:cs(d,"概览加载失败")}))}),(()=>F.abort())},[p]),r.useEffect(()=>{let F;try{F=Ma(s,new Date,a,l)}catch(M){x(b=>({...b,range:"error",error:cs(M,"日期范围无效")}));return}const d=Jr(F),B=++S.current,Z=new AbortController;return x(M=>({...M,range:"loading",error:""})),Promise.all([ea({start_date:F.startDate,end_date:F.endDate},{signal:Z.signal}),ea({start_date:d.startDate,end_date:d.endDate},{signal:Z.signal}),wl({start_date:F.startDate,end_date:F.endDate},{signal:Z.signal})]).then(([M,b,k])=>{la(S.current,B,Z.signal)&&(m({analytics:M,previousAnalytics:b,validOrders:k,dateRange:F}),x(D=>({...D,range:"success"})))}).catch(M=>{!la(S.current,B,Z.signal)||na(M)||x(b=>({...b,range:"error",error:cs(M,"经营数据加载失败")}))}),(()=>Z.abort())},[n,s,p]);const O=r.useMemo(()=>c&&h?{...c,...h}:null,[c,h]),P=(c==null?void 0:c.itemNames)||{},G=(h==null?void 0:h.analytics)||null,H=r.useMemo(()=>G?hn(G):[],[G]),X=r.useMemo(()=>G?gn(G,P):[],[G,P]),f=r.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))"],[]),y=r.useMemo(()=>G?bn(G,P,f):[],[G,f,P]),z=r.useMemo(()=>G?fn(G,P,f):[],[G,f,P]),I=r.useMemo(()=>vn(X),[X]);return{data:O,status:j,chartData:H,productSalesData:X,sourceData:y,categoryData:z,maxProductSales:I,trendPercent:yn(G,(O==null?void 0:O.previousAnalytics)||null),selectedRangeLabel:jn(q),refresh:w}},Ce=(t,s)=>s===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${s})`,_n=({chartData:t,selectedRangeLabel:s,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:[s,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||a===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(wa,{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:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(Yt,{width:"100%",height:"100%",children:e.jsxs(Tr,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Gs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:Ce("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(Ks,{axisLine:!1,tickLine:!1,tick:{fill:Ce("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(Xt,{contentStyle:{backgroundColor:Ce("white"),borderRadius:"8px",border:`1px solid ${Ce("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:Ce("neutral-500"),fontWeight:500},itemStyle:{color:Ce("brand"),fontWeight:600},cursor:{fill:Ce("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(Er,{dataKey:"amount",fill:Ce("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(_s,{fill:Ce("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(Yt,{width:"100%",height:"100%",children:e.jsxs(Dr,{data:t,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:Ce("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:Ce("brand"),stopOpacity:0})]})}),e.jsx(Gs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:Ce("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(Ks,{axisLine:!1,tickLine:!1,tick:{fill:Ce("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx($r,{vertical:!1,stroke:Ce("neutral-100"),strokeDasharray:"3 3"}),e.jsx(Xt,{contentStyle:{backgroundColor:Ce("white"),borderRadius:"8px",border:`1px solid ${Ce("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:Ce("neutral-500"),fontWeight:500},itemStyle:{color:Ce("brand"),fontWeight:600},cursor:{stroke:Ce("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Mr,{type:"monotone",dataKey:"amount",stroke:Ce("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:Ce("white"),stroke:Ce("brand"),strokeWidth:2}})]})})})]}),Xe=(t,s)=>`rgb(var(--color-${t}))`,wn=({status:t})=>{const s={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 ${s[t]||s.cancelled}`,children:a[t]||t})},Jt=({title:t,value:s,icon:a,colorClass:l,trend:n})=>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 ${l} 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 ${l} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(a,{className:`w-6 h-6 ${l.replace("bg-","text-")}`})}),n&&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(xr,{className:"w-3 h-3"})," ",n]})]}),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:s}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),ds=()=>{const[t,s]=r.useState("7days"),[a,l]=r.useState(""),[n,c]=r.useState(""),[u,h]=r.useState(""),[m,j]=r.useState(0),x=Nn({range:t,customStartDate:a,customEndDate:n,customRangeVersion:m}),{data:p,status:_,chartData:S,productSalesData:q,sourceData:w,categoryData:O,maxProductSales:P,trendPercent:G,selectedRangeLabel:H,refresh:X}=x,f=(p==null?void 0:p.stats)||null,y=(p==null?void 0:p.analytics)||null;p!=null&&p.previousAnalytics;const z=(p==null?void 0:p.validOrders.orders)||[],I=(p==null?void 0:p.validOrders.total)||0,F=(p==null?void 0:p.validOrders.truncated)||!1,d=_.range==="loading",B=_.error,Z=[Xe("brand"),Xe("brand-highlight"),Xe("success-500"),Xe("warning-500"),Xe("accent-500")],M=N=>`¥${Number(N||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(B&&(!f||!y))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(ut,{className:"w-8 h-8"}),e.jsx("span",{children:B}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:X,children:"重新加载"})]});if(!f||!y)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(Fs,{className:"w-8 h-8 animate-spin text-brand"})});const b=y.revenue_stats.total_orders||0,k=y.revenue_stats.total_amount||0,D=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let C;try{C=Ma(t,new Date,a,n)}catch{C={startDate:a,endDate:n}}const W=u.trim().toLowerCase(),K=z.filter(N=>{var ee,be,U,re;return((ee=N.order_id)==null?void 0:ee.toLowerCase().includes(W))||((be=N.item_id)==null?void 0:be.toLowerCase().includes(W))||((U=N.item_title)==null?void 0:U.toLowerCase().includes(W))||((re=N.buyer_id)==null?void 0:re.toLowerCase().includes(W))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[B&&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:B}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:X,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:[D.map(N=>e.jsx("button",{onClick:(()=>s(N.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${t===N.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:N.label},N.key)),t==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:a,onChange:(N=>l(N.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:n,onChange:(N=>c(N.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:(()=>j(N=>N+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(Jt,{title:"累计营收 (CNY)",value:`¥${y.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:dr,colorClass:"bg-blue-400",trend:G||void 0}),e.jsx(Jt,{title:"活跃账号 / 总数",value:`${f.active_cookies} / ${f.total_cookies}`,icon:va,colorClass:"bg-blue-500"}),e.jsx(Jt,{title:"订单数",value:y.revenue_stats.total_orders.toLocaleString(),icon:wa,colorClass:"bg-blue-500"}),e.jsx(Jt,{title:"库存卡密余量",value:f.available_card_stock,icon:ka,colorClass:"bg-purple-500"})]}),e.jsx(_n,{chartData:S,selectedRangeLabel:H,totalAmount:k}),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:q.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:q.map((N,ee)=>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 ${ee<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:ee+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:N.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[N.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,N.sales/P*100)}%`}})})]},`${N.name}-${ee}`))})})]}),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":`商品下单占比,共 ${b} 单`,children:w.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(Yt,{width:"100%",height:"100%",children:e.jsxs(Vs,{accessibilityLayer:!1,children:[e.jsx(Qs,{data:w,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:w.map((N,ee)=>e.jsx(_s,{fill:N.color},`cell-${ee}`))}),e.jsx(Xt,{formatter:(N=>`${Number(N||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:Xe("white"),border:`1px solid ${Xe("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(qr,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(N=>e.jsx("span",{style:{color:Xe("neutral-500"),fontWeight:500},children:N}))})]})}),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:b}),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:"参与统计的订单"}),F&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",z.length," / ",I," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:u,onChange:(N=>h(N.target.value)),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:d?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(Fs,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):K.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(Bt,{className:"w-7 h-7 text-gray-300"})}),W?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:["当前共有 ",z.length," 单参与统计,但没有订单号、商品、买家匹配“",u,"”。"]})]}):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:["日期范围:",C.startDate," 至 ",C.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",y.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:K.map(N=>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(Bt,{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:N.item_title||N.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:N.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",N.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:N.buyer_id}),N.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:Ls(N.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",N.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(wn,{status:N.status||N.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=${N.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(Ca,{className:"w-4 h-4"})})})]},N.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)"}),O.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":`商品金额分析,总金额 ${M(k)}`,children:[e.jsx(Yt,{width:"100%",height:"100%",children:e.jsxs(Vs,{accessibilityLayer:!1,children:[e.jsx(Qs,{data:O,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:O.map((N,ee)=>e.jsx(_s,{fill:N.color||Z[ee%Z.length]},`cell-${ee}`))}),e.jsx(Xt,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:Xe("white"),border:`1px solid ${Xe("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(N=>`¥${Number(N||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:M(k)}),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:O.map(N=>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:N.color||Z[O.indexOf(N)%Z.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:N.name,children:N.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:["¥",N.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[N.percentage,"%"]})]})]},N.name))})]})]})]})]})},kn=new Set(["expired","cancelled","error","not_found"]),Cn=()=>{let t=0;return{next:(()=>(t+=1,t)),cancel:(()=>{t+=1}),isCurrent:(s=>s===t)}},Sn=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let s=null,a=null,l=-1,n=0;const c=()=>{n+=1,a==null||a.abort(),a=null,s!==null&&(t.clearInterval(s),s=null)};return{start:(h,m,j,x=2e3)=>{c();const p=n;a=new AbortController;const _=a.signal;s=t.setInterval(()=>{l===p||p!==n||(l=p,(async()=>{var S,q;try{const w=await m(h,_);if(w.status==="success"){c(),await j.onSuccess(w);return}if(w.status==="scanned"){(S=j.onScanned)==null||S.call(j,w);return}if(w.status==="verification_required"){(q=j.onVerificationRequired)==null||q.call(j,w);return}w.status&&kn.has(w.status)&&(c(),j.onTerminalError(w))}catch(w){if(_.aborted||p!==n)return;c(),j.onPollError(w)}finally{l===p&&(l=-1)}})())},x)},stop:c,isActive:(()=>s!==null)}},Ln=({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(mr,{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(_e,{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:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),Va=({src:t,alt:s,className:a=""})=>e.jsx("img",{src:t,alt:s,className:`block aspect-square h-auto w-full object-contain ${a}`.trim()}),ia=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}),at=(t,s,a)=>t===s&&!a.aborted,xs=(t,s)=>t instanceof Error?t.message:s,ms=t=>t instanceof Error&&t.message==="请求已取消",oa=(t,s)=>!t&&s==="",Rn=({account:t,onSaved:s})=>{const[a,l]=r.useState(()=>ia(t)),[n,c]=r.useState(!0),[u,h]=r.useState(!1),[m,j]=r.useState(""),[x,p]=r.useState(""),[_,S]=r.useState(null),[q,w]=r.useState(null),O=r.useRef(0),P=r.useRef(null);r.useEffect(()=>{var z;const f=++O.current;(z=P.current)==null||z.abort();const y=new AbortController;return P.current=y,l(ia(t)),S(null),p(""),h(!1),j(""),w(null),c(!0),Hs(t.id,{signal:y.signal}).then(I=>{at(O.current,f,y.signal)&&l(I)}).catch(I=>{at(O.current,f,y.signal)&&!ms(I)&&p(xs(I,"加载任务设置失败"))}).finally(()=>{at(O.current,f,y.signal)&&c(!1)}),(()=>y.abort())},[t.id]),r.useEffect(()=>(()=>{var f;return(f=P.current)==null?void 0:f.abort()}),[]);const G=r.useCallback(async()=>{var z;if(!oa(u,m))return;const f=++O.current;(z=P.current)==null||z.abort();const y=new AbortController;P.current=y,h(!0),p(""),w(null);try{const I=await Zs(t.id,a,{signal:y.signal});if(!at(O.current,f,y.signal))return;l(I),s(I)}catch(I){at(O.current,f,y.signal)&&!ms(I)&&(p(xs(I,"保存失败")),w(()=>G))}finally{at(O.current,f,y.signal)&&h(!1)}},[t.id,a,s,m,u]),H=r.useCallback(async f=>{var I;if(!oa(u,m)||!t.enabled)return;const y=++O.current;(I=P.current)==null||I.abort();const z=new AbortController;P.current=z,j(f),p(""),S(null),w(null);try{await Zs(t.id,a,{signal:z.signal});const F=await Xr(t.id,f,{signal:z.signal}),d=await Hs(t.id,{signal:z.signal});if(!at(O.current,y,z.signal))return;S(F.summary),l(d),s(d)}catch(F){at(O.current,y,z.signal)&&!ms(F)&&(p(xs(F,"任务执行失败")),w(()=>(()=>H(f))))}finally{at(O.current,y,z.signal)&&j("")}},[t.enabled,t.id,a,s,m,u]),X=r.useCallback(async()=>{q&&await q()},[q]);return{form:a,loading:n,saving:u,running:m,summary:_,error:x,retryAvailable:q!==null,setForm:l,save:G,run:H,retry:X}},ca=({checked:t,onChange:s,label:a})=>e.jsx("button",{type:"button","aria-label":a,"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":""}`})}),An=({account:t,onClose:s,onSaved:a})=>{const{form:l,loading:n,saving:c,running:u,error:h,summary:m,retryAvailable:j,setForm:x,save:p,run:_,retry:S}=Rn({account:t,onSaved:a});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(ke,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[n&&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(ur,{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(ca,{checked:l.auto_rate_enabled,onChange:(()=>x(q=>({...q,auto_rate_enabled:!q.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:l.rate_content,maxLength:500,onChange:(q=>x(w=>({...w,rate_content:q.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:["最近扫描:",l.last_rate_scan_at?new Date(l.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:u!==""||!t.enabled,onClick:(()=>void _("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:[u==="auto_rate"?e.jsx(_e,{className:"h-4 w-4 animate-spin"}):e.jsx(pr,{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(Ds,{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(ca,{checked:l.auto_polish_enabled,onChange:(()=>x(q=>({...q,auto_polish_enabled:!q.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:l.polish_time,onChange:(q=>x(w=>({...w,polish_time:q.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:u!==""||!t.enabled,onClick:(()=>void _("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:[u==="auto_polish"?e.jsx(_e,{className:"h-4 w-4 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",l.last_polish_at?new Date(l.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),m&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",m.found," 项,成功 ",m.success,",失败 ",m.failed,",跳过 ",m.skipped,"。",m.message||""]}),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 font-medium text-red-700",children:[e.jsx("span",{children:h}),j&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void S()),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:c||u!=="",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 p()),disabled:c||u!==""||l.auto_rate_enabled&&!l.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:[c?e.jsx(_e,{className:"h-4 w-4 animate-spin"}):e.jsx(lt,{className:"h-4 w-4"}),"保存"]})]})})]})})},In=({account:t,editForm:s,setEditForm:a,saving:l,onClose:n,onSave:c,onRestartPause:u,longLogin:h,onToggleLongLogin:m,passwordLoginView:j,onPasswordLogin:x,onCancelPasswordLogin:p,notifChannels:_,selectedChannelIds:S,bindingsLoaded:q,bindingsLoading:w,bindingsLoadError:O,onRetryBindings:P,onToggleChannel:G,onSettingsDirty:H})=>{const X=(U,re)=>{a(ge=>({...ge,[U]:re}))},f=()=>void n(),y=()=>void c(),z=U=>X("remark",U.target.value),I=U=>X("cookie",U.target.value),F=()=>X("auto_confirm",!s.auto_confirm),d=U=>X("pause_duration",parseInt(U.target.value,10)||0),B=()=>void u(),Z=()=>void m(),M=U=>X("username",U.target.value),b=U=>a(re=>({...re,login_password:U.target.value,clear_password:!1})),k=()=>X("showLoginPassword",!s.showLoginPassword),D=U=>a(re=>({...re,clear_password:U.target.checked,login_password:U.target.checked?"":re.login_password})),C=()=>X("show_browser",!s.show_browser),W=()=>void p(),K=()=>void x(),N=()=>void P(),ee=U=>{q&&(G(U),H())},be=U=>{const re=S.includes(Number(U.id)),ge=()=>ee(Number(U.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:ge,disabled:!q,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${re?"bg-brand border-brand":"bg-white border-gray-300"}`,children:re&&e.jsx(Ye,{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:U.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[U.type,U.enabled?"":" · 已停用"]})]})]},U.id)};return Oe.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:f,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(ke,{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:z,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:I,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(Ye,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:F,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(La,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:s.pause_duration,onChange:d,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:l,onClick:B,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(hr,{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:"状态直接读取并修改闲鱼官方长登录设置"}),h.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:h.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:h.loading||h.saving||!h.canOpen,onClick:Z,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${h.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 ${h.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:M,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:b,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:k,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:s.showLoginPassword?e.jsx(bt,{className:"w-5 h-5"}):e.jsx(mt,{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:D,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:C,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 和保存的登录信息。"})]}),j.status==="processing"||j.status==="verification_required"?e.jsx("button",{type:"button",onClick:W,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:K,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),j.message&&e.jsx("div",{className:`text-sm font-medium ${j.status==="failed"?"text-red-700":j.status==="success"?"text-green-700":"text-blue-800"}`,children:j.message}),j.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 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),j.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(Va,{src:j.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(_.length>0||w||O)&&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(Rt,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),w&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(_e,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),O&&!w&&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:O}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:N,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:_.map(be)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:f,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:l,children:"取消"}),e.jsxs("button",{onClick:y,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:l,children:[l?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Ye,{className:"w-4 h-4"}),l?"保存中...":"保存"]})]})})]})}),document.body)},On=(t,s)=>{if(!t||!s)return!1;const a=Date.parse(t),l=Date.parse(s);return Number.isFinite(a)&&Number.isFinite(l)&&lt.map(a=>{const l=s[a.id];return!l||On(a.runtime_updated_at,l.updated_at)?a:{...a,runtime_state:l.state,runtime_message:l.message||"",runtime_connected:l.connected,runtime_updated_at:l.updated_at}}),Tn=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"}}},En=(t,s)=>t.map(a=>{var l,n,c,u,h;return{...a,ai_enabled:((l=s[a.id])==null?void 0:l.ai_enabled)??!1,max_discount_percent:((n=s[a.id])==null?void 0:n.max_discount_percent)??10,max_discount_amount:((c=s[a.id])==null?void 0:c.max_discount_amount)??100,max_bargain_rounds:((u=s[a.id])==null?void 0:u.max_bargain_rounds)??3,custom_prompts:((h=s[a.id])==null?void 0:h.custom_prompts)??""}}),Dn=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),c=r.useRef(null),u=r.useCallback(async()=>{var j;const h=++n.current;(j=c.current)==null||j.abort();const m=new AbortController;c.current=m,l(!0);try{const x={signal:m.signal},[p,_]=await Promise.allSettled([Ft(x),hl(x)]);if(h!==n.current)return;if(p.status==="rejected")throw p.reason;const S=_.status==="fulfilled"?_.value:{};_.status==="rejected"&&console.error("加载 AI 设置失败:",_.reason),s(En(p.value,S))}catch(x){h===n.current&&!m.signal.aborted&&console.error("加载账号失败:",x)}finally{h===n.current&&l(!1)}},[]);return r.useEffect(()=>{let h=!1,m=null;const j=new AbortController,x=async()=>{try{const _=await Cs({signal:j.signal,timeoutMs:1e4});h||s(S=>Pn(S,_))}catch(_){h||console.error("加载账号运行状态失败:",_)}finally{h||(m=window.setTimeout(()=>void x(),2e3))}};return u().finally(()=>{h||x()}),()=>{var _;h=!0,j.abort(),n.current+=1,(_=c.current)==null||_.abort(),m!==null&&window.clearTimeout(m)}},[u]),{accounts:t,setAccounts:s,loading:a,loadAccounts:u}},$n=(t,s)=>t!==(s.pause_duration||0),Mn=(t,s)=>{const a=s.username!==(t.username||""),l=s.show_browser!==(t.show_browser||!1),n=s.login_password!=="",c=s.clear_password===!0;if(!a&&!l&&!n&&!c)return null;const u={username:s.username,show_browser:s.show_browser};return c?u.clear_password=!0:n&&(u.login_password=s.login_password),u},dt=(t,s,a,l)=>t===s&&a===l,qn=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:""},Bn=(t,s)=>t&&s,Fn=({editingAccount:t,setEditingAccount:s,setActiveModal:a,editForm:l,setEditForm:n,loadAccounts:c})=>{const[u,h]=r.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[m,j]=r.useState([]),[x,p]=r.useState([]),[_,S]=r.useState(!1),[q,w]=r.useState(!1),[O,P]=r.useState(!1),[G,H]=r.useState(""),[X,f]=r.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[y,z]=r.useState(!1),[I,F]=r.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),d=r.useRef(0),B=r.useRef(null),Z=r.useRef(0),M=r.useRef(null),b=r.useRef(0),k=r.useRef(null),D=r.useRef(0),C=r.useRef(""),W=r.useRef(null),K=r.useRef(null),N=r.useCallback(()=>{K.current!==null&&(window.clearTimeout(K.current),K.current=null)},[]),ee=r.useCallback(async T=>{var de;const g=++d.current;(de=B.current)==null||de.abort();const le=new AbortController;B.current=le,w(!0),S(!1),P(!1),H("");const[oe,ne]=await Promise.allSettled([Ka({signal:le.signal}),nn(T,{signal:le.signal})]);dt(g,d.current,T,T)&&(oe.status==="fulfilled"?j(oe.value.data||[]):(j([]),H("通知渠道列表加载失败,请重试")),ne.status==="fulfilled"?(p(ne.value||[]),S(!0)):(p([]),H("通知绑定加载失败;本次保存不会修改现有绑定")),w(!1))},[]),be=r.useCallback(T=>{p(g=>g.includes(T)?g.filter(le=>le!==T):[...g,T]),P(!0)},[]),U=r.useCallback(async T=>{var ne,de;const g=++Z.current;(ne=M.current)==null||ne.abort();const le=new AbortController;M.current=le,D.current+=1,C.current=T.id,(de=W.current)==null||de.abort(),N(),F({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),s(T),n({remark:T.remark||"",cookie:T.value||"",auto_confirm:T.auto_confirm||!1,pause_duration:T.pause_duration||0,username:T.username||"",login_password:T.login_password||"",show_browser:T.show_browser||!1,showLoginPassword:!1,clear_password:!1}),a("edit"),h({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,oe]=await Promise.allSettled([ee(T.id),cl(T.id,{signal:le.signal})]);g===Z.current&&(oe.status==="fulfilled"?h({loading:!1,saving:!1,canOpen:oe.value.can_open_long_login,enabled:oe.value.enabled,error:""}):h({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"}))},[N,ee,a,n,s]),re=r.useCallback(async()=>{if(!t||u.loading||u.saving||!u.canOpen)return;const T=!u.enabled;h(g=>({...g,saving:!0,error:""}));try{const g=await dl(t.id,T);h({loading:!1,saving:!1,canOpen:g.can_open_long_login,enabled:g.enabled,error:""})}catch(g){h(le=>({...le,saving:!1,error:g instanceof Error?g.message:"保存登录信息设置失败"}))}},[t,u]),ge=r.useCallback(async T=>{var oe;const g=++b.current;(oe=k.current)==null||oe.abort();const le=new AbortController;k.current=le,s(T),a("ai-settings"),z(!0);try{const ne=await en(T.id,{signal:le.signal});if(!dt(g,b.current,T.id,T.id))return;f({ai_enabled:ne.ai_enabled??!1,max_discount_percent:ne.max_discount_percent??10,max_discount_amount:ne.max_discount_amount??100,max_bargain_rounds:ne.max_bargain_rounds??3,custom_prompts:ne.custom_prompts??""})}catch(ne){dt(g,b.current,T.id,T.id)&&console.error("加载 AI 设置失败:",ne)}finally{dt(g,b.current,T.id,T.id)&&z(!1)}},[a,s]),$=r.useCallback(async()=>{if(!(!t||y)){z(!0);try{await tn(t.id,X),a(null),await c()}catch(T){console.error("更新 AI 设置失败:",T)}finally{z(!1)}}},[X,t,c,y,a]),L=r.useCallback(async()=>{if(!(!t||y)){z(!0);try{const T={};l.remark!==(t.remark||"")&&(T.remark=l.remark),l.cookie&&l.cookie!==(t.value||"")&&(T.cookie=l.cookie),l.auto_confirm!==t.auto_confirm&&(T.auto_confirm=l.auto_confirm),$n(l.pause_duration,t)&&(T.pause_duration=l.pause_duration);const g=Mn(t,l);g&&Object.assign(T,g),Bn(_,O)&&(T.channel_ids=x),Object.keys(T).length>0&&await ol(t.id,T),a(null),await c()}catch(T){console.error("更新账号失败:",T)}finally{z(!1)}}},[O,_,l,t,c,x,y,a]),V=r.useCallback(async()=>{if(!(!t||l.pause_duration<=0||y)){z(!0);try{const T=await il(t.id,l.pause_duration);s(g=>g&&{...g,pause_duration:l.pause_duration,paused:(T==null?void 0:T.paused)===!0,paused_until:Number((T==null?void 0:T.paused_until)||0)}),await c()}catch(T){console.error("重新暂停失败:",T)}finally{z(!1)}}},[l.pause_duration,t,c,y,s]),Y=r.useCallback(async(T,g,le)=>{var ne;(ne=W.current)==null||ne.abort();const oe=new AbortController;W.current=oe;try{const de=await ml(T,oe.signal);if(!dt(g,D.current,le,C.current))return;const Se={...qn(de),sessionId:T};if(de.status==="success"){N(),F(Se),n(Ee=>({...Ee,login_password:"",showLoginPassword:!1})),await c();return}if(de.status==="processing"||de.status==="verification_required"){F(Se),N(),K.current=window.setTimeout(()=>void Y(T,g,le),1500);return}N(),F(Se)}catch(de){if(!dt(g,D.current,le,C.current))return;N(),F({sessionId:T,status:"failed",message:de instanceof Error?de.message:"查询密码登录状态失败",qrCodeUrl:""})}},[N,c,n]),se=r.useCallback(async()=>{var oe;if(!t)return;const T=l.username.trim();if(!T||!l.login_password)return;N(),(oe=W.current)==null||oe.abort();const g=++D.current;C.current=t.id;const le=new AbortController;W.current=le,F({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const ne=await xl({account_id:t.id,account:T,password:l.login_password,show_browser:l.show_browser},{signal:le.signal});if(!dt(g,D.current,t.id,C.current))return;if(!ne.success||!ne.session_id)throw new Error(ne.message||"无法启动密码登录");F({sessionId:ne.session_id,status:"processing",message:ne.message||"登录处理中",qrCodeUrl:""}),await Y(ne.session_id,g,t.id)}catch(ne){if(!dt(g,D.current,t.id,C.current))return;F({sessionId:"",status:"failed",message:ne instanceof Error?ne.message:"启动密码登录失败",qrCodeUrl:""})}},[N,l.login_password,l.show_browser,l.username,t,Y]),ue=r.useCallback(async()=>{var g;const T=I.sessionId;D.current+=1,C.current="",(g=W.current)==null||g.abort(),N(),T&&await ul(T).catch(()=>{}),F({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},[N,I.sessionId]),ve=r.useCallback(async()=>{var T,g,le;(T=B.current)==null||T.abort(),Z.current+=1,(g=M.current)==null||g.abort(),(le=k.current)==null||le.abort(),(I.status==="processing"||I.status==="verification_required")&&await ue(),a(null)},[ue,I.status,a]),R=r.useCallback(()=>{var T;b.current+=1,(T=k.current)==null||T.abort(),a(null)},[a]);return r.useEffect(()=>(()=>{var T,g,le,oe;(T=B.current)==null||T.abort(),(g=M.current)==null||g.abort(),(le=k.current)==null||le.abort(),(oe=W.current)==null||oe.abort(),N()}),[N]),{longLogin:u,notifChannels:m,selectedChannelIds:x,bindingsLoaded:_,bindingsLoading:q,bindingsDirty:O,bindingsLoadError:G,aiSettings:X,saving:y,passwordLoginView:I,setAiSettings:f,setBindingsDirty:P,setEditForm:n,openEditModal:U,closeEditModal:ve,openAIModal:ge,closeAIModal:R,loadNotificationBindings:ee,toggleNotificationChannel:be,handleLongLoginToggle:re,handleSaveAISettings:$,handleSaveEdit:L,handleRestartPause:V,handlePasswordLogin:se,handleCancelPasswordLogin:ue}},zn=()=>{const{accounts:t,setAccounts:s,loading:a,loadAccounts:l}=Dn(),[n,c]=r.useState(""),[u,h]=r.useState(""),[m,j]=r.useState(""),[x,p]=r.useState(null),[_,S]=r.useState(""),[q,w]=r.useState(!1),[O,P]=r.useState(""),[G,H]=r.useState("pending"),[X,f]=r.useState(""),[y,z]=r.useState(""),[I,F]=r.useState(""),[d,B]=r.useState(null),[Z,M]=r.useState(null),[b,k]=r.useState(null),[D,C]=r.useState(null),[W,K]=r.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),N=Fn({editingAccount:b,setEditingAccount:k,setActiveModal:M,editForm:W,setEditForm:K,loadAccounts:l}),{longLogin:ee,notifChannels:be,selectedChannelIds:U,bindingsLoaded:re,bindingsLoading:ge,bindingsLoadError:$,aiSettings:L,saving:V,passwordLoginView:Y,setAiSettings:se,setBindingsDirty:ue,openEditModal:ve,closeEditModal:R,openAIModal:T,closeAIModal:g,loadNotificationBindings:le,toggleNotificationChannel:oe,handleLongLoginToggle:ne,handleSaveAISettings:de,handleSaveEdit:Se,handleRestartPause:Ee,handlePasswordLogin:Te,handleCancelPasswordLogin:Ue}=N,Me=r.useRef(null),Be=r.useRef(null),Je=r.useRef(null),He=r.useRef(null);Me.current===null&&(Me.current=Sn()),Be.current===null&&(Be.current=Cn());const we=()=>{He.current!==null&&(window.clearTimeout(He.current),He.current=null)},pe=()=>{var v;(v=Me.current)==null||v.stop()},Ke=()=>{var v,E;(v=Je.current)==null||v.abort(),(E=Be.current)==null||E.cancel(),pe(),we(),w(!1)},it=()=>{we(),He.current=window.setTimeout(()=>{He.current=null,w(!1),l()},1e3)};r.useEffect(()=>(()=>{var v,E;pe(),(v=Be.current)==null||v.cancel(),(E=Je.current)==null||E.abort(),we()}),[]);const tt=async(v,E)=>{await ll(v,!E),l()},Ve=v=>{m||(S(""),p(v))},Ge=()=>{m||(S(""),p(null))},ot=async()=>{const v=x;if(!(!v||m)){j(v.id),S("");try{await nl(v.id),s(E=>E.filter(ae=>ae.id!==v.id)),p(null)}catch(E){console.error("删除账号失败:",E),S((E==null?void 0:E.message)||"删除账号失败,请稍后重试")}finally{j("")}}},pt=async v=>{h(v.id);try{const E=await pl(v.id);E!=null&&E.profile_error&&alert("资料刷新失败:"+E.profile_error),await l()}catch(E){console.error("刷新账号资料失败:",E),alert((E==null?void 0:E.message)||"刷新账号资料失败,请先重新授权该账号")}finally{h("")}},ht=async(v,E)=>{const ae=await rl(v,E==null?void 0:E.id);if(!ae.success||!ae.account_id)throw new Error(ae.message||"保存扫码授权失败");return ae.account_id},J=async v=>{var fe,De,Ne,Pe;pe(),(fe=Je.current)==null||fe.abort();const E=new AbortController;Je.current=E;const ae=Be.current.next();we();const ce=v||null;B(ce),w(!0),H("loading"),f(""),P(""),z(""),F("");try{const me=await sl({signal:E.signal});if(!((De=Be.current)!=null&&De.isCurrent(ae)))return;if(!me.success||!me.qr_code_url||!me.session_id)throw new Error(me.message||"闲鱼未返回可用的登录二维码");if(me.success&&me.qr_code_url&&me.session_id){const o=me.session_id;P(me.qr_code_url),H("waiting"),(Ne=Me.current)==null||Ne.start(o,al,{onSuccess:(async()=>{try{if(!await ht(o,ce)){H("error");return}}catch(Q){console.error("保存扫码授权失败",Q),H("error");return}H("success"),it()}),onScanned:(()=>{H("waiting")}),onTerminalError:(()=>{H("error")}),onPollError:(Q=>{console.error("轮询扫码状态失败",Q),H("error")}),onVerificationRequired:(Q=>{H("verification"),Q.face_qr_url&&F(Q.face_qr_url),Q.verification_screenshot&&z(Q.verification_screenshot)})})}}catch(me){if(!((Pe=Be.current)!=null&&Pe.isCurrent(ae)))return;f(me instanceof Error?me.message:"二维码获取失败,请稍后重试"),H("error")}finally{Je.current===E&&(Je.current=null)}};if(a)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(_e,{className:"w-8 h-8 text-brand animate-spin"})});const ie=t.filter(v=>{const E=n.trim().toLowerCase();return E?[v.id,v.nickname,v.remark,v.username,v.runtime_message].some(ae=>(ae||"").toLowerCase().includes(E)):!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:n,onChange:(v=>c(v.target.value)),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:(()=>J()),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(rs,{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:["当前显示 ",ie.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[ie.map(v=>{const E=Tn(v),ae=v.runtime_state==="auth_expired"||v.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:[v.avatar_url?e.jsx("img",{src:v.avatar_url,alt:v.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(yt,{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 ${E.dot}`,children:v.runtime_state==="online"&&e.jsx(Ye,{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:v.nickname||v.remark||`账号 ${v.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${E.badge}`,children:E.label}),v.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(wt,{className:"w-3 h-3"})," AI"]}),v.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($t,{className:"h-3 w-3"})," 自动评价"]}),v.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(Ds,{className:"h-3 w-3"})," 每日擦亮"]}),v.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(Ye,{className:"h-3 w-3"})," 自动确认发货"]}),v.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:v.profile_error,children:[e.jsx(ut,{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:v.remark||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",v.id]})]}),v.runtime_message&&v.runtime_state!=="online"&&v.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${ae?"text-red-700":"text-amber-700"}`,children:[e.jsx(ut,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:v.runtime_message}),ae&&e.jsxs("button",{type:"button",onClick:(()=>J(v)),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(rs,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),v.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(La,{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:(()=>pt(v)),disabled:u===v.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(We,{className:`w-5 h-5 ${u===v.id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>J(v)),className:`p-3 rounded-xl transition-colors ${ae?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(rs,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>ve(v)),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Ra,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>T(v)),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(wt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>C(v)),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(Sa,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>tt(v.id,v.enabled)),className:`p-3 rounded-xl transition-colors ${v.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:v.enabled?"停用账号":"启用账号",children:e.jsx(gr,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>Ve(v)),disabled:m!=="",className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:m===v.id?"删除中…":`删除账号 ${v.nickname||v.remark||v.id}`,children:m===v.id?e.jsx(_e,{className:"w-5 h-5 animate-spin"}):e.jsx(Ze,{className:"w-5 h-5"})})]})]})]})]})},v.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(yt,{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&&ie.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。"})]})]}),D&&Oe.createPortal(e.jsx(An,{account:D,onClose:(()=>C(null)),onSaved:(v=>{s(E=>E.map(ae=>ae.id===D.id?{...ae,auto_rate_enabled:v.auto_rate_enabled,rate_content:v.rate_content,auto_polish_enabled:v.auto_polish_enabled,polish_time:v.polish_time,last_rate_scan_at:v.last_rate_scan_at,last_polish_date:v.last_polish_date,last_polish_at:v.last_polish_at}:ae))})}),document.body),x&&Oe.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(Ze,{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:Ge,disabled:m!=="",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(ke,{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:x.nickname||x.remark||"未命名账号"}),x.remark&&x.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",x.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",x.id]})]}),m===x.id&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(_e,{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:"正在清理关联数据,请保持页面打开…"})]})]}),_&&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(ut,{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:_})]})]})]}),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:Ge,disabled:m!=="",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 ot()),disabled:m!=="",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:m===x.id?e.jsxs(e.Fragment,{children:[e.jsx(_e,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),q&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:Ke,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:e.jsx(ke,{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:d?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:d?`请用闲鱼APP扫码,为「${d.nickname||d.remark||d.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 ${G==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[G==="loading"&&e.jsx(_e,{className:"w-10 h-10 text-brand animate-spin"}),G==="waiting"&&e.jsx(Va,{src:O,alt:"闲鱼登录二维码",className:"p-2"}),G==="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(Ye,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),G==="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:X||"请关闭窗口后重新发起扫码登录。"})]}),G==="verification"&&e.jsx(Ln,{faceQrUrl:I,verificationScreenshot:y})]}),G!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),Z==="edit"&&b&&e.jsx(In,{account:b,editForm:W,setEditForm:K,saving:V,onClose:R,onSave:Se,onRestartPause:Ee,longLogin:ee,onToggleLongLogin:ne,passwordLoginView:Y,onPasswordLogin:Te,onCancelPasswordLogin:Ue,notifChannels:be,selectedChannelIds:U,bindingsLoaded:re,bindingsLoading:ge,bindingsLoadError:$,onRetryBindings:(()=>le(b.id)),onToggleChannel:oe,onSettingsDirty:(()=>ue(!0))}),Z==="ai-settings"&&b&&Oe.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(wt,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:b.nickname||b.remark||b.id})]}),e.jsx("button",{onClick:g,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(ke,{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(wt,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:(()=>se({...L,ai_enabled:!L.ai_enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${L.ai_enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${L.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:L.max_discount_percent,onChange:(v=>se({...L,max_discount_percent:parseInt(v.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:L.max_discount_amount,onChange:(v=>se({...L,max_discount_amount:parseInt(v.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:L.max_bargain_rounds,onChange:(v=>se({...L,max_bargain_rounds:parseInt(v.target.value)||1})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:L.custom_prompts,onChange:(v=>se({...L,custom_prompts:v.target.value})),placeholder:`输入自定义的AI回复规则或风格指引... +import{j as e,r,c as As,b as Oe,d as ir}from"./react-vendor-C_od1ZSF.js";import{L as or,U as va,M as ys,C as Os,B as Na,S as _a,Z as js,a as Rt,b as Ps,G as Bs,c as Ts,d as Es,e as cr,f as wa,g as ut,A as Fs,D as dr,P as ka,h as Bt,E as Ca,T as xr,i as mr,j as _e,X as ke,k as ur,l as pr,m as Ds,n as Sa,o as lt,p as Ye,q as La,K as hr,r as bt,s as mt,Q as rs,t as yt,u as wt,v as $t,R as We,w as Ra,x as gr,y as Ze,z as St,F as Mt,H as nt,I as zs,J as kt,N as br,O as fr,V as yr,W as Ia,Y as Aa,_ as Oa,$ as jr,a0 as vr,a1 as ls,a2 as Wt,a3 as vs,a4 as Nr,a5 as _r,a6 as Ns,a7 as Us,a8 as wr,a9 as kr,aa as qt,ab as Ws,ac as Zt,ad as Pa,ae as Cr,af as Sr,ag as ss,ah as Ta,ai as Lr,aj as Rr,ak as Ir,al as Ar,am as Or,an as Pr,ao as Js}from"./icons-vendor-i_74xDZy.js";import{R as Yt,B as Tr,X as Gs,Y as Ks,T as Xt,a as Er,C as _s,A as Dr,b as $r,c as Mr,P as Vs,d as Qs,L as qr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const c of n)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(n){const c={};return n.integrity&&(c.integrity=n.integrity),n.referrerPolicy&&(c.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?c.credentials="include":n.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function l(n){if(n.ep)return;n.ep=!0;const c=a(n);fetch(n.href,c)}})();const Br=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ws=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),e.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:e.jsx(Br,{className:s})})]})]}),Fr=3e4,zr=10*6e4;let ns=!1;const Ea=()=>{ns||typeof window>"u"||(ns=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{ns=!1}))},Ur=t=>{if(!t)return"";const s=new URLSearchParams;for(const[l,n]of Object.entries(t))n!=null&&s.set(l,String(n));const a=s.toString();return a?`?${a}`:""},as=async(t,s,a={})=>{var f;const l=Ur(a.params),n=`${s}${l}`,c=Da(a.signal,a.timeoutMs??Fr);let u;try{u=await fetch(n,{method:t,credentials:"include",signal:c.signal,headers:{...a.body===void 0?{}:{"Content-Type":"application/json"}},body:a.body===void 0?void 0:JSON.stringify(a.body)})}catch(x){throw c.signal.aborted?new Error((f=a.signal)!=null&&f.aborted?"请求已取消":"请求超时,请稍后重试"):x}finally{c.cleanup()}const m=(u.headers.get("content-type")||"").includes("application/json");if(!u.ok){u.status===401&&!a.skipAuthLogout&&Ea();const x=m?await u.json().catch(()=>{}):await u.text().catch(()=>{}),h=$a(x,u.status);throw new Error(h)}return m?await u.json():await u.text()},ye=async(t,s,a)=>as("GET",t,{params:s,...a}),je=async(t,s,a)=>as("POST",t,{body:s,...a}),ze=async(t,s,a)=>as("PUT",t,{body:s,...a}),et=async(t,s,a)=>as("DELETE",t,{params:s,...a}),It=async(t,s,a={})=>{var m;const l=Da(a.signal,a.timeoutMs??zr);let n;try{n=await fetch(t,{method:"POST",credentials:"include",signal:l.signal,body:s})}catch(f){throw l.signal.aborted?new Error((m=a.signal)!=null&&m.aborted?"请求已取消":"上传超时,请稍后重试"):f}finally{l.cleanup()}const p=(n.headers.get("content-type")||"").includes("application/json")?await n.json().catch(()=>{}):await n.text().catch(()=>{});if(!n.ok){n.status===401&&Ea();const f=$a(p,n.status),x=new Error(f);throw x.payload=p,x}return p},Da=(t,s)=>{const a=new AbortController,l=()=>a.abort(t==null?void 0:t.reason);t!=null&&t.aborted?l():t==null||t.addEventListener("abort",l,{once:!0});const n=globalThis.setTimeout(()=>a.abort(new DOMException("timeout","TimeoutError")),Math.max(1,s));return{signal:a.signal,cleanup:()=>{globalThis.clearTimeout(n),t==null||t.removeEventListener("abort",l)}}},Wr=t=>{if(typeof t!="object"||t===null)return!1;const s=t;return typeof s.code=="string"&&typeof s.message=="string"},$a=(t,s)=>typeof t=="string"?t:Wr(t)?t.message:`请求失败: ${s}`,es=t=>{const s=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${s}-${a}-${l}`},$s=(t,s)=>{const a=new Date(t);return a.setHours(12,0,0,0),a.setDate(a.getDate()+s),a},ks=(t,s)=>({startDate:es($s(t,-(s-1))),endDate:es(t)}),Ma=(t,s=new Date,a="",l="")=>{if(t==="custom"&&a&&l){if(a>l)throw new Error("开始日期不能晚于结束日期");return{startDate:a,endDate:l}}return t==="yesterday"?ks($s(s,-1),1):ks(s,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Jr=t=>{const s=new Date(`${t.startDate}T12:00:00`),a=new Date(`${t.endDate}T12:00:00`),l=Math.round((a.getTime()-s.getTime())/864e5)+1,n=$s(s,-1);return ks(n,l)},Gr=t=>{const s={...t},a=["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"];for(const l of a){const n=`${l}_configured`;n in s&&(s[n]=s[n]===!0||s[n]==="true")}if("renewal_log_retention_days"in s){const l=Number(s.renewal_log_retention_days);s.renewal_log_retention_days=Number.isFinite(l)?l:10}return s},Kr=async t=>je("/api/v1/session/login",t,{skipAuthLogout:!0}),Vr=async t=>je("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),qa=async t=>ye("/api/v1/session",void 0,t),Qr=async t=>ye("/health",void 0,t),Hr=async()=>je("/api/v1/session/logout",{}),Zr=async(t,s)=>ze("/api/v1/session/credentials",t,s),Yr=(t,s)=>{const a=t.avatar_url||"";if(!a)return"";try{const l=new URL(a,window.location.origin);return l.hostname.endsWith("alicdn.com")&&l.searchParams.set("_v",s),l.toString()}catch{return a}},Ft=async t=>{const s=await ye("/api/v1/accounts/details",void 0,t),a=Date.now().toString();return s.map(l=>({id:l.id,value:"",enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password:"",show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:Yr(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},Hs=async(t,s)=>ye(`/api/v1/account-tasks/${t}`,void 0,s),Zs=async(t,s,a)=>ze(`/api/v1/account-tasks/${t}`,s,a),Xr=async(t,s,a)=>je(`/api/v1/account-tasks/${t}/run`,{task_type:s},{timeoutMs:12e4,...a}),is=async(t,s,a,l=!1)=>{const n=await ye("/api/v1/chat/sessions",{account_id:t,cursor:s,refresh:l?1:void 0},l?{timeoutMs:6e4,...a}:a);return{sessions:n.sessions||[],has_more:n.has_more===!0,next_cursor:n.next_cursor}},Ys=async(t,s,a,l,n)=>{const c=await ye("/api/v1/chat/messages",{account_id:t,chat_id:s,cursor:a,before_id:l},n);return{messages:c.messages||[],has_more:c.has_more===!0,next_cursor:c.next_cursor,session:c.session}},el=async(t,s)=>je("/api/v1/chat/messages",t,s),tl=async(t,s)=>{const a=new FormData;return Object.entries(t).forEach(([l,n])=>a.append(l,n)),It("/api/v1/chat/images",a,{timeoutMs:12e4,...s})},Xs=async(t,s,a)=>je("/api/v1/chat/read",{account_id:t,chat_id:s},a),Cs=async t=>ye("/api/v1/accounts/runtime-status",void 0,t),sl=async t=>je("/api/v1/qr-login/generate",void 0,{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),al=async(t,s)=>ye(`/api/v1/qr-login/check/${t}`,void 0,{signal:s,timeoutMs:1e4}),rl=async(t,s)=>je(`/api/v1/qr-login/complete-verification/${t}`,{target_account_id:s||""}),ll=async(t,s)=>ze(`/api/v1/accounts/${t}/status`,{enabled:s}),nl=async t=>et(`/api/v1/accounts/${t}`),il=async(t,s,a)=>ze(`/api/v1/accounts/${t}/pause-duration`,{pause_duration:s},a),ol=async(t,s,a)=>ze(`/api/v1/accounts/${t}/settings`,s,a),cl=async(t,s)=>ye(`/api/v1/accounts/${t}/long-login`,void 0,s),dl=async(t,s,a)=>ze(`/api/v1/accounts/${t}/long-login`,{enabled:s},a),xl=async(t,s)=>je("/api/v1/password-login",t,s),ml=async(t,s)=>ye(`/api/v1/password-login/check/${t}`,void 0,{signal:s,timeoutMs:1e4}),ul=async(t,s)=>et(`/api/v1/password-login/cancel/${t}`,void 0,s),pl=async t=>je(`/api/v1/accounts/${t}/refresh-profile`,{}),hl=async t=>ye("/api/v1/settings/ai-reply",void 0,t),Ba=t=>{const s=String(t||"");return s==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(s)?s:"unknown"},gl=async(t,s,a=1,l=20,n,c)=>{const u={page:a,page_size:l};t&&(u.cookie_id=t),s&&s!=="all"&&(u.status=s),n!=null&&n.trim()&&(u.search=n.trim());const p=await ye("/api/v1/orders",u,c),f=(p.orders||p.data||[]).map(x=>({...x,id:x.id||x.order_id,status:Ba(x.status||x.order_status),quantity:Number(x.quantity||1)}));return{success:!0,data:f,total:p.total||f.length,page:p.page||a,page_size:p.page_size||l,total_pages:p.total_pages||1}},bl=async(t,s)=>ze(`/api/v1/orders/${t}`,s),fl=async t=>et(`/api/v1/orders/${t}`),yl=async(t,s,a)=>{const l=new FormData;t&&l.append("cookie_id",t),s&&l.append("status",s);const n=await It("/api/v1/orders/refresh",l,a),c=180;let u=0;for(;u{globalThis.setTimeout(()=>{f()},m)}),u+=1}throw new Error("订单刷新任务等待超时")},jl=async t=>je(`/api/v1/orders/${t}/refresh`),vl=async(t,s)=>je("/api/v1/orders/manual-ship",{order_ids:t,ship_mode:s}),Nl=async(t,s)=>t instanceof FormData?It("/api/v1/orders/import",t,s):je("/api/v1/orders/import",t,s),_l=async t=>ye("/api/v1/analytics/dashboard",void 0,t),ea=async(t=7,s)=>{let a;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),a={start_date:es(n),end_date:es(l)}}else a=t;return ye("/api/v1/analytics/orders",{...a,timezone_offset_minutes:-new Date().getTimezoneOffset()},s)},wl=async(t,s)=>{const a=await ye("/api/v1/analytics/orders/valid",{start_date:t.start_date,end_date:t.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()},s),n=(Array.isArray(a)?a:a.orders||[]).map(c=>({...c,id:c.id||c.order_id,status:Ba(c.status||c.order_status),quantity:Number(c.quantity||1)}));return{orders:n,total:Array.isArray(a)?n.length:Number(a.total??n.length),truncated:Array.isArray(a)?!1:a.truncated===!0}},kl=t=>{let s=t.api_config;if(typeof s=="string"&&s.trim())try{s=JSON.parse(s)}catch{s=void 0}return{...t,api_config:s||void 0}},Fa=t=>({...t,api_config:t.api_config?JSON.stringify(t.api_config):""}),Ms=async t=>{const s=await ye("/api/v1/cards",void 0,t);return(Array.isArray(s)?s:s.cards||[]).map(kl)},Cl=async t=>je("/api/v1/cards",Fa(t)),ta=async(t,s)=>ze(`/api/v1/cards/${t}`,Fa(s)),Sl=async t=>et(`/api/v1/cards/${t}`),Ll=async(t,s)=>{const a=new FormData;return a.append("file",t),It("/api/v1/cards/batch",a,s)},Rl=async(t,s,a)=>je(`/api/v1/cards/${t}/append-data`,{content:s},a),os=t=>t===!0||t===1||t==="1",Lt=async(t,s)=>{const a=await ye("/api/v1/items",void 0,s);return(Array.isArray(a)?a:a.items||[]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:os(n.is_multi_spec),is_multi_qty_ship:os(n.is_multi_qty_ship??n.multi_quantity_delivery),multi_quantity_delivery:os(n.multi_quantity_delivery??n.is_multi_qty_ship)}))},Il=async t=>je("/api/v1/items/get-all-from-account",{cookie_id:t}),Al=async(t,s)=>et(`/api/v1/items/${t}/${s}`),Ol=async(t,s)=>je(`/api/v1/items/${t}`,s),Pl=async t=>{const s=new FormData;s.set("cookie_id",t.cookie_id),s.set("title",t.title),s.set("description",t.description),s.set("price",t.price),s.set("original_price",t.original_price||""),s.set("quantity",String(t.quantity)),s.set("postage_mode",t.postage_mode),s.set("postage",t.postage||""),t.location&&s.set("location",JSON.stringify(t.location));for(const a of t.images)s.append("images",a);return It("/api/v1/items/publish",s)},Tl=async(t,s)=>je("/api/v1/items/publish-categories/recommend",{cookie_id:t,keyword:s}),El=async t=>{const s=new FormData;return s.set("file",t.file),t.imagesZip&&s.set("images_zip",t.imagesZip),t.defaultCookieId&&s.set("default_cookie_id",t.defaultCookieId),s.set("fallback_category_id",t.fallbackCategory.catId),s.set("fallback_category_name",t.fallbackCategory.catName),s.set("fallback_channel_category_id",t.fallbackCategory.channelCatId||""),s.set("fallback_tb_category_id",t.fallbackCategory.tbCatId||""),t.location&&s.set("location",JSON.stringify(t.location)),It("/api/v1/items/publish-batches/preview",s)},Dl=async t=>je("/api/v1/items/publish-batches",{preview_id:t}),vt=async t=>ye(`/api/v1/items/publish-batches/${t}`),za=async(t=20)=>{const s=await ye("/api/v1/items/publish-batches",{limit:t});return Array.isArray(s)?s:s.batches||[]},$l=async t=>et(`/api/v1/items/publish-batches/${t}`),Ml=async t=>je(`/api/v1/items/publish-batches/${t}/cancel`,{}),ql=async t=>je(`/api/v1/items/publish-batches/${t}/retry-failed`,{}),Bl=async(t,s,a)=>ze(`/api/v1/items/${t}/${s}`,a),Ua=t=>t.map(s=>{var a,l;return{id:String(s.id),name:s.name||"",trigger_type:s.trigger_type||"order_paid",item_keyword:s.item_title||s.item_id||"",cookie_id:s.cookie_id||"",item_id:s.item_id||"",item_title:s.item_title||"",card_group_id:Number(((a=(s.actions||[]).find(n=>n.action_type==="send_card"))==null?void 0:a.card_id)||0),card_group_name:((l=(s.actions||[]).find(n=>n.action_type==="send_card"))==null?void 0:l.card_name)||"",priority:s.priority||100,enabled:s.enabled||!1,config_json:s.config_json||"{}",actions:(s.actions||[]).map(n=>({id:n.id?String(n.id):void 0,action_type:n.action_type,card_id:Number(n.card_id||0),card_name:n.card_name||"",delivery_count:Number(n.delivery_count||1),message_template:n.message_template||"",delay_seconds:Number(n.delay_seconds||0),config_json:n.config_json||"{}",enabled:n.enabled!==!1,sort_order:Number(n.sort_order||0)})),variants:(s.actions||[]).filter(n=>n.action_type==="send_card").map(n=>{let c={};try{c=JSON.parse(n.config_json||"{}")}catch{}return{id:n.id?String(n.id):void 0,spec_name:c.spec_name||"",spec_value:c.spec_value||"",card_id:Number(n.card_id||0),card_name:n.card_name||"",delivery_count:Number(n.delivery_count||1),enabled:n.enabled!==!1,delay_override:c.delay_override===!0,delay_seconds:Number(n.delay_seconds||0),config_json:n.config_json||"{}"}})}}),Ss=async()=>{const t=await ye("/api/v1/automation-rules"),s=Array.isArray(t)?t:t.data||[];return Ua(s)},Fl=async({cookieId:t,triggerType:s,enabled:a,search:l,page:n=1,pageSize:c=10}={})=>{const u=await ye("/api/v1/automation-rules",{page:n,page_size:c,cookie_id:t||void 0,trigger_type:s||void 0,enabled:a,search:(l==null?void 0:l.trim())||void 0}),p=Ua(Array.isArray(u)?u:u.data||[]);return{success:!0,data:p,total:Number(Array.isArray(u)?p.length:u.total??p.length),page:Number(Array.isArray(u)?n:u.page??n),page_size:Number(Array.isArray(u)?c:u.page_size??c),total_pages:Number(Array.isArray(u)?p.length?1:0:u.total_pages??(p.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(Array.isArray(u)?{}:u.trigger_counts||{}).map(([m,f])=>[m,Number(f)]))}},zl=(t,s)=>{if(t!=="order_paid")return s.map((n,c)=>({...n,sort_order:n.sort_order||c+1}));const a=s.filter(n=>n.action_type==="send_card").map((n,c)=>({...n,sort_order:c+1})),l=s.filter(n=>n.action_type!=="send_card"&&n.action_type!=="confirm_shipment");return[...a,...l.map((n,c)=>({...n,sort_order:a.length+c+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:a.length+l.length+1}]},sa=async t=>{const s=t.trigger_type||"order_paid",l=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[s]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),n=(t.actions||[]).filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment"),c=t.variants&&t.variants.length>0?[...t.variants.map((m,f)=>({action_type:"send_card",card_id:m.card_id,delivery_count:m.delivery_count||1,enabled:m.enabled!==!1,sort_order:f+1,delay_seconds:m.delay_seconds||0,config_json:JSON.stringify({spec_name:m.spec_name||"",spec_value:m.spec_value||"",delay_override:m.delay_override===!0})})),...n]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],u=zl(s,c),p={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||l||"自动化规则",trigger_type:s,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:u.map((m,f)=>({action_type:m.action_type,card_id:m.card_id||0,delivery_count:m.delivery_count||1,message_template:m.message_template||"",delay_seconds:m.delay_seconds||0,config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:m.sort_order||f+1}))};return t.id?ze(`/api/v1/automation-rules/${t.id}`,p):je("/api/v1/automation-rules",p)},Ul=async t=>et(`/api/v1/automation-rules/${t}`),Wl=async()=>{const t=await ye("/api/v1/automation-issues");return{runs:Array.isArray(t==null?void 0:t.runs)?t.runs:[],pending_tasks:Array.isArray(t==null?void 0:t.pending_tasks)?t.pending_tasks:[]}},Jl=async(t,s)=>je(`/api/v1/automation-runs/${t}/resolve`,{resolution:s}),Gl=async(t,s)=>je(`/api/v1/automation-pending-tasks/${t}/resolve`,{resolution:s}),Kl=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Vl=async t=>{const s=await ye(`/api/v1/reply-rules/${t}/typed`);return Array.isArray(s)?s.map(Kl):[]},Ql=async t=>t?(await Vl(t)).map(a=>({id:a.id,keyword:a.keyword||"",reply_content:a.reply||"",match_type:"fuzzy",enabled:!0,item_id:a.item_id||"",type:a.type==="image"?"image":"text",image_url:a.image_url||""})):[],Hl=async(t,s)=>{const a=t.type||"text",l={keyword:t.keyword||"",reply:a==="text"&&t.reply_content||"",item_id:t.item_id||"",type:a,image_url:a==="image"&&t.image_url||""};return t.id?ze(`/api/v1/reply-rules/${s}/typed/${t.id}`,l):je(`/api/v1/reply-rules/${s}/items`,l)},Zl=async(t,s)=>et(`/api/v1/reply-rules/${s}/typed/${t}`),Yl=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),Xl=t=>{if("values"in t||"secrets"in t)return t;const s={},a={};for(const l of Object.entries(t)){const[n,c]=l;c!=null&&(Yl.has(n)?a[n]=c===""?{action:"clear"}:{action:"replace",value:String(c)}:s[n]=c)}return Object.keys(a).length>0?{values:s,secrets:a}:s},Wa=async t=>{const s=await ye("/api/v1/settings/system",void 0,t);return Gr(s.data||s)},Ja=async(t,s)=>{const a=Xl(t);return ze("/api/v1/settings/system",a,s)},en=async(t,s)=>ye(`/api/v1/settings/ai-reply/${t}`,void 0,s),tn=async(t,s,a)=>{const l={ai_enabled:s.ai_enabled??!1,max_discount_percent:s.max_discount_percent??10,max_discount_amount:s.max_discount_amount??100,max_bargain_rounds:s.max_bargain_rounds??3,custom_prompts:s.custom_prompts??""};return ze(`/api/v1/settings/ai-reply/${t}`,l,a)},sn=async(t,s="",a)=>(await je("/api/v1/settings/ai-models",{base_url:t,api_key:s},a)).models||[],an=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const s=JSON.parse(t);if(Array.isArray(s))return s.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},Ga=t=>{const s=Array.from(new Set((t||[]).filter(Boolean)));return s.length>0?JSON.stringify(s):""},Ka=async t=>({success:!0,data:(await ye("/api/v1/notifications/channels",void 0,t)||[]).map(l=>{let n;try{n=typeof l.config=="string"?JSON.parse(l.config):l.config}catch{n={}}return{id:String(l.id),name:l.name,type:l.type==="ding_talk"?"dingtalk":l.type==="lark"?"feishu":l.type,config:n,event_types:an(l.event_types),enabled:l.enabled,created_at:l.created_at,updated_at:l.updated_at}})}),rn=async(t,s)=>je("/api/v1/notifications/channels",{...t,config:JSON.stringify(t.config),event_types:Ga(t.event_types)},s),aa=async(t,s,a)=>{const l={...s};return"config"in s&&(l.config=JSON.stringify(s.config)),"event_types"in s&&(l.event_types=Ga(s.event_types)),ze(`/api/v1/notifications/channels/${t}`,l,a)},ln=async(t,s)=>et(`/api/v1/notifications/channels/${t}`,void 0,s),nn=async(t,s)=>{const a=await ye(`/api/v1/notifications/accounts/${t}/bindings`,void 0,s);return(a==null?void 0:a.channel_ids)||[]},on=async(t,s)=>je(`/api/v1/notifications/channels/${t}/test`,{},s),ra=async()=>ye("/api/v1/default-replies"),cn=async t=>{const s=await ye(`/api/v1/default-replies/${t}`);return{cookie_id:t,enabled:s.enabled||!1,reply_content:s.reply_content||"",reply_once:s.reply_once||!1,reply_image_url:s.reply_image_url||""}},dn=async(t,s)=>ze(`/api/v1/default-replies/${t}`,{enabled:s.enabled??!1,reply_content:s.reply_content||"",reply_once:s.reply_once??!1,reply_image_url:s.reply_image_url||""}),xn=async t=>et(`/api/v1/default-replies/${t}`),mn=async t=>je(`/api/v1/default-replies/${t}/clear-records`,{}),un=({activeTab:t,isAdmin:s=!1,collapsed:a,onToggleCollapsed:l,onNavigate:n,onLogout:c})=>{const[u,p]=r.useState({version:"dev",commit:"unknown"});r.useEffect(()=>{const x=new AbortController;return Qr({signal:x.signal}).then(h=>p({version:String(h.version||"dev"),commit:String(h.commit||"unknown")})).catch(h=>{h instanceof DOMException&&h.name}),(()=>x.abort())},[]);const m=[{id:"dashboard",icon:or,label:"仪表盘"},{id:"accounts",icon:va,label:"账号管理"},{id:"chat",icon:ys,label:"在线聊天"},{id:"cards",icon:Os,label:"卡密库存"},{id:"items",icon:Na,label:"商品列表"},{id:"orders",icon:_a,label:"订单管理"},{id:"rules",icon:js,label:"自动化规则"},{id:"notifications",icon:Rt,label:"通知设置"},...s?[{id:"settings",icon:Ps,label:"系统与AI"}]:[]],f=/^\d+\.\d+\.\d+$/.test(u.version)?`v${u.version}`:u.version;return e.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${a?"w-16":"w-64"}`,children:[e.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${a?"justify-center px-2":"gap-3 px-5"}`,children:[e.jsx(ws,{sizeClass:"h-10 w-10"}),!a&&e.jsxs("div",{className:"min-w-0 leading-tight",children:[e.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),e.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),e.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${a?"px-2":"px-3"}`,"aria-label":"主导航",children:m.map(x=>{const h=x.icon,_=t===x.id;return e.jsx(As.Fragment,{children:e.jsxs("button",{type:"button",title:a?x.label:void 0,"aria-label":x.label,"aria-current":_?"page":void 0,onClick:(()=>n(x.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${a?"justify-center":"gap-3 px-3.5"} ${_?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(h,{className:`h-[19px] w-[19px] shrink-0 ${_?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!a&&e.jsx("span",{className:"truncate text-sm font-bold",children:x.label}),_&&!a&&e.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},x.id)})}),e.jsxs("div",{children:[e.jsx("div",{title:a?`版本 ${u.version} · ${u.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${a?"flex justify-center px-1":"px-6"}`,children:a?e.jsx(Bs,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${u.version}`}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[e.jsx(Bs,{className:"h-3.5 w-3.5"}),"运行版本"]}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[e.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:f}),e.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:u.commit})]})]})}),e.jsxs("div",{className:`space-y-2 p-2 ${a?"":"p-3"}`,children:[e.jsxs("button",{type:"button",onClick:l,title:a?"展开侧边栏":"收起侧边栏","aria-label":a?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${a?"justify-center":"gap-3 px-3"}`,children:[a?e.jsx(Ts,{className:"h-5 w-5"}):e.jsx(Es,{className:"h-5 w-5"}),!a&&e.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),e.jsxs("button",{type:"button",onClick:c,title:a?"退出登录":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 ${a?"justify-center":"gap-3 px-3"}`,children:[e.jsx(cr,{className:"h-5 w-5"}),!a&&e.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},At=t=>String(t).padStart(2,"0"),Ls=t=>{if(t==null||t==="")return"-";const s=t instanceof Date?t:new Date(t);return Number.isNaN(s.getTime())?"-":[s.getFullYear(),At(s.getMonth()+1),At(s.getDate())].join("-")+" "+[At(s.getHours()),At(s.getMinutes()),At(s.getSeconds())].join(":")},pn=t=>{const s={};return t.forEach(a=>{s[a.item_id]=a.item_title||a.item_id}),s},hn=t=>{var s;return((s=t.daily_stats)==null?void 0:s.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})))||[]},gn=(t,s)=>(t.item_stats||[]).map(a=>{const l=s[a.item_id]||a.item_id;return{name:l.length>12?`${l.substring(0,12)}...`:l,sales:a.order_count}}).sort((a,l)=>l.sales-a.sales).slice(0,10),bn=(t,s,a)=>{const l=t.revenue_stats.total_orders||0;return(t.item_stats||[]).map(n=>{const c=s[n.item_id]||n.item_id;return{name:c.length>10?`${c.substring(0,10)}...`:c,value:n.order_count,percent:l>0?n.order_count/l*100:0}}).sort((n,c)=>c.value-n.value).slice(0,6).map((n,c)=>({...n,color:a[c%a.length]}))},fn=(t,s,a)=>{const l=t.revenue_stats.total_amount||0;return(t.item_stats||[]).map(n=>{const c=s[n.item_id]||n.item_id;return{name:c.length>12?`${c.substring(0,12)}...`:c,value:n.total_amount,orderCount:n.order_count,percentage:l>0?n.total_amount/l*100:0}}).sort((n,c)=>c.value-n.value).slice(0,5).map((n,c)=>({...n,color:a[c%a.length],percentage:n.percentage.toFixed(1)}))},yn=(t,s)=>{if(!t||!s)return null;const a=t.revenue_stats.total_amount,l=s.revenue_stats.total_amount;if(l===0)return a>0?"+100%":"0%";const n=(a-l)/l*100;return`${n>=0?"+":""}${n.toFixed(1)}%`},jn=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",vn=t=>Math.max(...t.map(s=>s.sales),1),la=(t,s,a)=>t===s&&!a.aborted,na=t=>t instanceof Error&&t.message==="请求已取消",cs=(t,s)=>t instanceof Error?t.message:s,Nn=t=>{const{range:s,customStartDate:a,customEndDate:l,customRangeVersion:n}=t,[c,u]=r.useState(null),[p,m]=r.useState(null),[f,x]=r.useState({overview:"idle",range:"idle",error:""}),[h,_]=r.useState(0),S=r.useRef(0),q=r.useMemo(()=>({range:s,customStartDate:a,customEndDate:l}),[l,a,s]),w=r.useCallback(()=>_(F=>F+1),[]);r.useEffect(()=>{const F=new AbortController;return x(d=>({...d,overview:"loading",error:""})),Promise.all([_l({signal:F.signal}),Lt(void 0,{signal:F.signal})]).then(([d,B])=>{F.signal.aborted||(u({stats:d,items:B,itemNames:pn(B)}),x(Z=>({...Z,overview:"success"})))}).catch(d=>{F.signal.aborted||na(d)||x(B=>({...B,overview:"error",error:cs(d,"概览加载失败")}))}),(()=>F.abort())},[h]),r.useEffect(()=>{let F;try{F=Ma(s,new Date,a,l)}catch(M){x(b=>({...b,range:"error",error:cs(M,"日期范围无效")}));return}const d=Jr(F),B=++S.current,Z=new AbortController;return x(M=>({...M,range:"loading",error:""})),Promise.all([ea({start_date:F.startDate,end_date:F.endDate},{signal:Z.signal}),ea({start_date:d.startDate,end_date:d.endDate},{signal:Z.signal}),wl({start_date:F.startDate,end_date:F.endDate},{signal:Z.signal})]).then(([M,b,k])=>{la(S.current,B,Z.signal)&&(m({analytics:M,previousAnalytics:b,validOrders:k,dateRange:F}),x(D=>({...D,range:"success"})))}).catch(M=>{!la(S.current,B,Z.signal)||na(M)||x(b=>({...b,range:"error",error:cs(M,"经营数据加载失败")}))}),(()=>Z.abort())},[n,s,h]);const O=r.useMemo(()=>c&&p?{...c,...p}:null,[c,p]),P=(c==null?void 0:c.itemNames)||{},G=(p==null?void 0:p.analytics)||null,H=r.useMemo(()=>G?hn(G):[],[G]),X=r.useMemo(()=>G?gn(G,P):[],[G,P]),y=r.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))"],[]),j=r.useMemo(()=>G?bn(G,P,y):[],[G,y,P]),z=r.useMemo(()=>G?fn(G,P,y):[],[G,y,P]),A=r.useMemo(()=>vn(X),[X]);return{data:O,status:f,chartData:H,productSalesData:X,sourceData:j,categoryData:z,maxProductSales:A,trendPercent:yn(G,(O==null?void 0:O.previousAnalytics)||null),selectedRangeLabel:jn(q),refresh:w}},Ce=(t,s)=>s===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${s})`,_n=({chartData:t,selectedRangeLabel:s,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:[s,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||a===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(wa,{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:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(Yt,{width:"100%",height:"100%",children:e.jsxs(Tr,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Gs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:Ce("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(Ks,{axisLine:!1,tickLine:!1,tick:{fill:Ce("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(Xt,{contentStyle:{backgroundColor:Ce("white"),borderRadius:"8px",border:`1px solid ${Ce("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:Ce("neutral-500"),fontWeight:500},itemStyle:{color:Ce("brand"),fontWeight:600},cursor:{fill:Ce("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(Er,{dataKey:"amount",fill:Ce("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(_s,{fill:Ce("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(Yt,{width:"100%",height:"100%",children:e.jsxs(Dr,{data:t,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:Ce("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:Ce("brand"),stopOpacity:0})]})}),e.jsx(Gs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:Ce("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(Ks,{axisLine:!1,tickLine:!1,tick:{fill:Ce("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx($r,{vertical:!1,stroke:Ce("neutral-100"),strokeDasharray:"3 3"}),e.jsx(Xt,{contentStyle:{backgroundColor:Ce("white"),borderRadius:"8px",border:`1px solid ${Ce("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:Ce("neutral-500"),fontWeight:500},itemStyle:{color:Ce("brand"),fontWeight:600},cursor:{stroke:Ce("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Mr,{type:"monotone",dataKey:"amount",stroke:Ce("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:Ce("white"),stroke:Ce("brand"),strokeWidth:2}})]})})})]}),Xe=(t,s)=>`rgb(var(--color-${t}))`,wn=({status:t})=>{const s={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 ${s[t]||s.cancelled}`,children:a[t]||t})},Jt=({title:t,value:s,icon:a,colorClass:l,trend:n})=>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 ${l} 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 ${l} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(a,{className:`w-6 h-6 ${l.replace("bg-","text-")}`})}),n&&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(xr,{className:"w-3 h-3"})," ",n]})]}),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:s}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),ds=()=>{const[t,s]=r.useState("7days"),[a,l]=r.useState(""),[n,c]=r.useState(""),[u,p]=r.useState(""),[m,f]=r.useState(0),x=Nn({range:t,customStartDate:a,customEndDate:n,customRangeVersion:m}),{data:h,status:_,chartData:S,productSalesData:q,sourceData:w,categoryData:O,maxProductSales:P,trendPercent:G,selectedRangeLabel:H,refresh:X}=x,y=(h==null?void 0:h.stats)||null,j=(h==null?void 0:h.analytics)||null;h!=null&&h.previousAnalytics;const z=(h==null?void 0:h.validOrders.orders)||[],A=(h==null?void 0:h.validOrders.total)||0,F=(h==null?void 0:h.validOrders.truncated)||!1,d=_.range==="loading",B=_.error,Z=[Xe("brand"),Xe("brand-highlight"),Xe("success-500"),Xe("warning-500"),Xe("accent-500")],M=N=>`¥${Number(N||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(B&&(!y||!j))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(ut,{className:"w-8 h-8"}),e.jsx("span",{children:B}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:X,children:"重新加载"})]});if(!y||!j)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(Fs,{className:"w-8 h-8 animate-spin text-brand"})});const b=j.revenue_stats.total_orders||0,k=j.revenue_stats.total_amount||0,D=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let C;try{C=Ma(t,new Date,a,n)}catch{C={startDate:a,endDate:n}}const W=u.trim().toLowerCase(),K=z.filter(N=>{var ee,be,U,re;return((ee=N.order_id)==null?void 0:ee.toLowerCase().includes(W))||((be=N.item_id)==null?void 0:be.toLowerCase().includes(W))||((U=N.item_title)==null?void 0:U.toLowerCase().includes(W))||((re=N.buyer_id)==null?void 0:re.toLowerCase().includes(W))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[B&&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:B}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:X,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:[D.map(N=>e.jsx("button",{onClick:(()=>s(N.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${t===N.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:N.label},N.key)),t==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:a,onChange:(N=>l(N.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:n,onChange:(N=>c(N.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(N=>N+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(Jt,{title:"累计营收 (CNY)",value:`¥${j.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:dr,colorClass:"bg-blue-400",trend:G||void 0}),e.jsx(Jt,{title:"活跃账号 / 总数",value:`${y.active_cookies} / ${y.total_cookies}`,icon:va,colorClass:"bg-blue-500"}),e.jsx(Jt,{title:"订单数",value:j.revenue_stats.total_orders.toLocaleString(),icon:wa,colorClass:"bg-blue-500"}),e.jsx(Jt,{title:"库存卡密余量",value:y.available_card_stock,icon:ka,colorClass:"bg-purple-500"})]}),e.jsx(_n,{chartData:S,selectedRangeLabel:H,totalAmount:k}),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:q.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:q.map((N,ee)=>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 ${ee<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:ee+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:N.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[N.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,N.sales/P*100)}%`}})})]},`${N.name}-${ee}`))})})]}),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":`商品下单占比,共 ${b} 单`,children:w.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(Yt,{width:"100%",height:"100%",children:e.jsxs(Vs,{accessibilityLayer:!1,children:[e.jsx(Qs,{data:w,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:w.map((N,ee)=>e.jsx(_s,{fill:N.color},`cell-${ee}`))}),e.jsx(Xt,{formatter:(N=>`${Number(N||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:Xe("white"),border:`1px solid ${Xe("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(qr,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(N=>e.jsx("span",{style:{color:Xe("neutral-500"),fontWeight:500},children:N}))})]})}),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:b}),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:"参与统计的订单"}),F&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",z.length," / ",A," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:u,onChange:(N=>p(N.target.value)),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:d?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(Fs,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):K.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(Bt,{className:"w-7 h-7 text-gray-300"})}),W?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:["当前共有 ",z.length," 单参与统计,但没有订单号、商品、买家匹配“",u,"”。"]})]}):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:["日期范围:",C.startDate," 至 ",C.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",j.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:K.map(N=>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(Bt,{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:N.item_title||N.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:N.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",N.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:N.buyer_id}),N.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:Ls(N.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",N.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(wn,{status:N.status||N.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=${N.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(Ca,{className:"w-4 h-4"})})})]},N.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)"}),O.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":`商品金额分析,总金额 ${M(k)}`,children:[e.jsx(Yt,{width:"100%",height:"100%",children:e.jsxs(Vs,{accessibilityLayer:!1,children:[e.jsx(Qs,{data:O,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:O.map((N,ee)=>e.jsx(_s,{fill:N.color||Z[ee%Z.length]},`cell-${ee}`))}),e.jsx(Xt,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:Xe("white"),border:`1px solid ${Xe("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(N=>`¥${Number(N||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:M(k)}),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:O.map(N=>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:N.color||Z[O.indexOf(N)%Z.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:N.name,children:N.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:["¥",N.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[N.percentage,"%"]})]})]},N.name))})]})]})]})]})},kn=new Set(["expired","cancelled","error","not_found"]),Cn=()=>{let t=0;return{next:(()=>(t+=1,t)),cancel:(()=>{t+=1}),isCurrent:(s=>s===t)}},Sn=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let s=null,a=null,l=-1,n=0;const c=()=>{n+=1,a==null||a.abort(),a=null,s!==null&&(t.clearInterval(s),s=null)};return{start:(p,m,f,x=2e3)=>{c();const h=n;a=new AbortController;const _=a.signal;s=t.setInterval(()=>{l===h||h!==n||(l=h,(async()=>{var S,q;try{const w=await m(p,_);if(w.status==="success"){c(),await f.onSuccess(w);return}if(w.status==="scanned"){(S=f.onScanned)==null||S.call(f,w);return}if(w.status==="verification_required"){(q=f.onVerificationRequired)==null||q.call(f,w);return}w.status&&kn.has(w.status)&&(c(),f.onTerminalError(w))}catch(w){if(_.aborted||h!==n)return;c(),f.onPollError(w)}finally{l===h&&(l=-1)}})())},x)},stop:c,isActive:(()=>s!==null)}},Ln=({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(mr,{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(_e,{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:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),Va=({src:t,alt:s,className:a=""})=>e.jsx("img",{src:t,alt:s,className:`block aspect-square h-auto w-full object-contain ${a}`.trim()}),ia=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}),at=(t,s,a)=>t===s&&!a.aborted,xs=(t,s)=>t instanceof Error?t.message:s,ms=t=>t instanceof Error&&t.message==="请求已取消",oa=(t,s)=>!t&&s==="",Rn=({account:t,onSaved:s})=>{const[a,l]=r.useState(()=>ia(t)),[n,c]=r.useState(!0),[u,p]=r.useState(!1),[m,f]=r.useState(""),[x,h]=r.useState(""),[_,S]=r.useState(null),[q,w]=r.useState(null),O=r.useRef(0),P=r.useRef(null);r.useEffect(()=>{var z;const y=++O.current;(z=P.current)==null||z.abort();const j=new AbortController;return P.current=j,l(ia(t)),S(null),h(""),p(!1),f(""),w(null),c(!0),Hs(t.id,{signal:j.signal}).then(A=>{at(O.current,y,j.signal)&&l(A)}).catch(A=>{at(O.current,y,j.signal)&&!ms(A)&&h(xs(A,"加载任务设置失败"))}).finally(()=>{at(O.current,y,j.signal)&&c(!1)}),(()=>j.abort())},[t.id]),r.useEffect(()=>(()=>{var y;return(y=P.current)==null?void 0:y.abort()}),[]);const G=r.useCallback(async()=>{var z;if(!oa(u,m))return;const y=++O.current;(z=P.current)==null||z.abort();const j=new AbortController;P.current=j,p(!0),h(""),w(null);try{const A=await Zs(t.id,a,{signal:j.signal});if(!at(O.current,y,j.signal))return;l(A),s(A)}catch(A){at(O.current,y,j.signal)&&!ms(A)&&(h(xs(A,"保存失败")),w(()=>G))}finally{at(O.current,y,j.signal)&&p(!1)}},[t.id,a,s,m,u]),H=r.useCallback(async y=>{var A;if(!oa(u,m)||!t.enabled)return;const j=++O.current;(A=P.current)==null||A.abort();const z=new AbortController;P.current=z,f(y),h(""),S(null),w(null);try{await Zs(t.id,a,{signal:z.signal});const F=await Xr(t.id,y,{signal:z.signal}),d=await Hs(t.id,{signal:z.signal});if(!at(O.current,j,z.signal))return;S(F.summary),l(d),s(d)}catch(F){at(O.current,j,z.signal)&&!ms(F)&&(h(xs(F,"任务执行失败")),w(()=>(()=>H(y))))}finally{at(O.current,j,z.signal)&&f("")}},[t.enabled,t.id,a,s,m,u]),X=r.useCallback(async()=>{q&&await q()},[q]);return{form:a,loading:n,saving:u,running:m,summary:_,error:x,retryAvailable:q!==null,setForm:l,save:G,run:H,retry:X}},ca=({checked:t,onChange:s,label:a})=>e.jsx("button",{type:"button","aria-label":a,"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":""}`})}),In=({account:t,onClose:s,onSaved:a})=>{const{form:l,loading:n,saving:c,running:u,error:p,summary:m,retryAvailable:f,setForm:x,save:h,run:_,retry:S}=Rn({account:t,onSaved:a});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(ke,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[n&&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(ur,{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(ca,{checked:l.auto_rate_enabled,onChange:(()=>x(q=>({...q,auto_rate_enabled:!q.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:l.rate_content,maxLength:500,onChange:(q=>x(w=>({...w,rate_content:q.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:["最近扫描:",l.last_rate_scan_at?new Date(l.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:u!==""||!t.enabled,onClick:(()=>void _("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:[u==="auto_rate"?e.jsx(_e,{className:"h-4 w-4 animate-spin"}):e.jsx(pr,{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(Ds,{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(ca,{checked:l.auto_polish_enabled,onChange:(()=>x(q=>({...q,auto_polish_enabled:!q.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:l.polish_time,onChange:(q=>x(w=>({...w,polish_time:q.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:u!==""||!t.enabled,onClick:(()=>void _("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:[u==="auto_polish"?e.jsx(_e,{className:"h-4 w-4 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",l.last_polish_at?new Date(l.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),m&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",m.found," 项,成功 ",m.success,",失败 ",m.failed,",跳过 ",m.skipped,"。",m.message||""]}),p&&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:p}),f&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void S()),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:c||u!=="",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:c||u!==""||l.auto_rate_enabled&&!l.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:[c?e.jsx(_e,{className:"h-4 w-4 animate-spin"}):e.jsx(lt,{className:"h-4 w-4"}),"保存"]})]})})]})})},An=({account:t,editForm:s,setEditForm:a,saving:l,onClose:n,onSave:c,onRestartPause:u,longLogin:p,onToggleLongLogin:m,passwordLoginView:f,onPasswordLogin:x,onCancelPasswordLogin:h,notifChannels:_,selectedChannelIds:S,bindingsLoaded:q,bindingsLoading:w,bindingsLoadError:O,onRetryBindings:P,onToggleChannel:G,onSettingsDirty:H})=>{const X=(U,re)=>{a(ge=>({...ge,[U]:re}))},y=()=>void n(),j=()=>void c(),z=U=>X("remark",U.target.value),A=U=>X("cookie",U.target.value),F=()=>X("auto_confirm",!s.auto_confirm),d=U=>X("pause_duration",parseInt(U.target.value,10)||0),B=()=>void u(),Z=()=>void m(),M=U=>X("username",U.target.value),b=U=>a(re=>({...re,login_password:U.target.value,clear_password:!1})),k=()=>X("showLoginPassword",!s.showLoginPassword),D=U=>a(re=>({...re,clear_password:U.target.checked,login_password:U.target.checked?"":re.login_password})),C=()=>X("show_browser",!s.show_browser),W=()=>void h(),K=()=>void x(),N=()=>void P(),ee=U=>{q&&(G(U),H())},be=U=>{const re=S.includes(Number(U.id)),ge=()=>ee(Number(U.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:ge,disabled:!q,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${re?"bg-brand border-brand":"bg-white border-gray-300"}`,children:re&&e.jsx(Ye,{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:U.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[U.type,U.enabled?"":" · 已停用"]})]})]},U.id)};return Oe.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:y,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(ke,{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:z,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:A,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(Ye,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:F,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(La,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:s.pause_duration,onChange:d,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:l,onClick:B,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(hr,{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:"状态直接读取并修改闲鱼官方长登录设置"}),p.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:p.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:p.loading||p.saving||!p.canOpen,onClick:Z,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${p.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 ${p.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:M,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:b,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:k,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:s.showLoginPassword?e.jsx(bt,{className:"w-5 h-5"}):e.jsx(mt,{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:D,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:C,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 和保存的登录信息。"})]}),f.status==="processing"||f.status==="verification_required"?e.jsx("button",{type:"button",onClick:W,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:K,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),f.message&&e.jsx("div",{className:`text-sm font-medium ${f.status==="failed"?"text-red-700":f.status==="success"?"text-green-700":"text-blue-800"}`,children:f.message}),f.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 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),f.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(Va,{src:f.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(_.length>0||w||O)&&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(Rt,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),w&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(_e,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),O&&!w&&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:O}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:N,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:_.map(be)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:y,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:l,children:"取消"}),e.jsxs("button",{onClick:j,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:l,children:[l?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Ye,{className:"w-4 h-4"}),l?"保存中...":"保存"]})]})})]})}),document.body)},On=(t,s)=>{if(!t||!s)return!1;const a=Date.parse(t),l=Date.parse(s);return Number.isFinite(a)&&Number.isFinite(l)&&lt.map(a=>{const l=s[a.id];return!l||On(a.runtime_updated_at,l.updated_at)?a:{...a,runtime_state:l.state,runtime_message:l.message||"",runtime_connected:l.connected,runtime_updated_at:l.updated_at}}),Tn=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"}}},En=(t,s)=>t.map(a=>{var l,n,c,u,p;return{...a,ai_enabled:((l=s[a.id])==null?void 0:l.ai_enabled)??!1,max_discount_percent:((n=s[a.id])==null?void 0:n.max_discount_percent)??10,max_discount_amount:((c=s[a.id])==null?void 0:c.max_discount_amount)??100,max_bargain_rounds:((u=s[a.id])==null?void 0:u.max_bargain_rounds)??3,custom_prompts:((p=s[a.id])==null?void 0:p.custom_prompts)??""}}),Dn=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),c=r.useRef(null),u=r.useCallback(async()=>{var f;const p=++n.current;(f=c.current)==null||f.abort();const m=new AbortController;c.current=m,l(!0);try{const x={signal:m.signal},[h,_]=await Promise.allSettled([Ft(x),hl(x)]);if(p!==n.current)return;if(h.status==="rejected")throw h.reason;const S=_.status==="fulfilled"?_.value:{};_.status==="rejected"&&console.error("加载 AI 设置失败:",_.reason),s(En(h.value,S))}catch(x){p===n.current&&!m.signal.aborted&&console.error("加载账号失败:",x)}finally{p===n.current&&l(!1)}},[]);return r.useEffect(()=>{let p=!1,m=null;const f=new AbortController,x=async()=>{try{const _=await Cs({signal:f.signal,timeoutMs:1e4});p||s(S=>Pn(S,_))}catch(_){p||console.error("加载账号运行状态失败:",_)}finally{p||(m=window.setTimeout(()=>void x(),2e3))}};return u().finally(()=>{p||x()}),()=>{var _;p=!0,f.abort(),n.current+=1,(_=c.current)==null||_.abort(),m!==null&&window.clearTimeout(m)}},[u]),{accounts:t,setAccounts:s,loading:a,loadAccounts:u}},$n=(t,s)=>t!==(s.pause_duration||0),Mn=(t,s)=>{const a=s.username!==(t.username||""),l=s.show_browser!==(t.show_browser||!1),n=s.login_password!=="",c=s.clear_password===!0;if(!a&&!l&&!n&&!c)return null;const u={username:s.username,show_browser:s.show_browser};return c?u.clear_password=!0:n&&(u.login_password=s.login_password),u},dt=(t,s,a,l)=>t===s&&a===l,qn=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:""},Bn=(t,s)=>t&&s,Fn=({editingAccount:t,setEditingAccount:s,setActiveModal:a,editForm:l,setEditForm:n,loadAccounts:c})=>{const[u,p]=r.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[m,f]=r.useState([]),[x,h]=r.useState([]),[_,S]=r.useState(!1),[q,w]=r.useState(!1),[O,P]=r.useState(!1),[G,H]=r.useState(""),[X,y]=r.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[j,z]=r.useState(!1),[A,F]=r.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),d=r.useRef(0),B=r.useRef(null),Z=r.useRef(0),M=r.useRef(null),b=r.useRef(0),k=r.useRef(null),D=r.useRef(0),C=r.useRef(""),W=r.useRef(null),K=r.useRef(null),N=r.useCallback(()=>{K.current!==null&&(window.clearTimeout(K.current),K.current=null)},[]),ee=r.useCallback(async T=>{var de;const g=++d.current;(de=B.current)==null||de.abort();const le=new AbortController;B.current=le,w(!0),S(!1),P(!1),H("");const[oe,ne]=await Promise.allSettled([Ka({signal:le.signal}),nn(T,{signal:le.signal})]);dt(g,d.current,T,T)&&(oe.status==="fulfilled"?f(oe.value.data||[]):(f([]),H("通知渠道列表加载失败,请重试")),ne.status==="fulfilled"?(h(ne.value||[]),S(!0)):(h([]),H("通知绑定加载失败;本次保存不会修改现有绑定")),w(!1))},[]),be=r.useCallback(T=>{h(g=>g.includes(T)?g.filter(le=>le!==T):[...g,T]),P(!0)},[]),U=r.useCallback(async T=>{var ne,de;const g=++Z.current;(ne=M.current)==null||ne.abort();const le=new AbortController;M.current=le,D.current+=1,C.current=T.id,(de=W.current)==null||de.abort(),N(),F({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),s(T),n({remark:T.remark||"",cookie:T.value||"",auto_confirm:T.auto_confirm||!1,pause_duration:T.pause_duration||0,username:T.username||"",login_password:T.login_password||"",show_browser:T.show_browser||!1,showLoginPassword:!1,clear_password:!1}),a("edit"),p({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,oe]=await Promise.allSettled([ee(T.id),cl(T.id,{signal:le.signal})]);g===Z.current&&(oe.status==="fulfilled"?p({loading:!1,saving:!1,canOpen:oe.value.can_open_long_login,enabled:oe.value.enabled,error:""}):p({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"}))},[N,ee,a,n,s]),re=r.useCallback(async()=>{if(!t||u.loading||u.saving||!u.canOpen)return;const T=!u.enabled;p(g=>({...g,saving:!0,error:""}));try{const g=await dl(t.id,T);p({loading:!1,saving:!1,canOpen:g.can_open_long_login,enabled:g.enabled,error:""})}catch(g){p(le=>({...le,saving:!1,error:g instanceof Error?g.message:"保存登录信息设置失败"}))}},[t,u]),ge=r.useCallback(async T=>{var oe;const g=++b.current;(oe=k.current)==null||oe.abort();const le=new AbortController;k.current=le,s(T),a("ai-settings"),z(!0);try{const ne=await en(T.id,{signal:le.signal});if(!dt(g,b.current,T.id,T.id))return;y({ai_enabled:ne.ai_enabled??!1,max_discount_percent:ne.max_discount_percent??10,max_discount_amount:ne.max_discount_amount??100,max_bargain_rounds:ne.max_bargain_rounds??3,custom_prompts:ne.custom_prompts??""})}catch(ne){dt(g,b.current,T.id,T.id)&&console.error("加载 AI 设置失败:",ne)}finally{dt(g,b.current,T.id,T.id)&&z(!1)}},[a,s]),$=r.useCallback(async()=>{if(!(!t||j)){z(!0);try{await tn(t.id,X),a(null),await c()}catch(T){console.error("更新 AI 设置失败:",T)}finally{z(!1)}}},[X,t,c,j,a]),L=r.useCallback(async()=>{if(!(!t||j)){z(!0);try{const T={};l.remark!==(t.remark||"")&&(T.remark=l.remark),l.cookie&&l.cookie!==(t.value||"")&&(T.cookie=l.cookie),l.auto_confirm!==t.auto_confirm&&(T.auto_confirm=l.auto_confirm),$n(l.pause_duration,t)&&(T.pause_duration=l.pause_duration);const g=Mn(t,l);g&&Object.assign(T,g),Bn(_,O)&&(T.channel_ids=x),Object.keys(T).length>0&&await ol(t.id,T),a(null),await c()}catch(T){console.error("更新账号失败:",T)}finally{z(!1)}}},[O,_,l,t,c,x,j,a]),V=r.useCallback(async()=>{if(!(!t||l.pause_duration<=0||j)){z(!0);try{const T=await il(t.id,l.pause_duration);s(g=>g&&{...g,pause_duration:l.pause_duration,paused:(T==null?void 0:T.paused)===!0,paused_until:Number((T==null?void 0:T.paused_until)||0)}),await c()}catch(T){console.error("重新暂停失败:",T)}finally{z(!1)}}},[l.pause_duration,t,c,j,s]),Y=r.useCallback(async(T,g,le)=>{var ne;(ne=W.current)==null||ne.abort();const oe=new AbortController;W.current=oe;try{const de=await ml(T,oe.signal);if(!dt(g,D.current,le,C.current))return;const Se={...qn(de),sessionId:T};if(de.status==="success"){N(),F(Se),n(Ee=>({...Ee,login_password:"",showLoginPassword:!1})),await c();return}if(de.status==="processing"||de.status==="verification_required"){F(Se),N(),K.current=window.setTimeout(()=>void Y(T,g,le),1500);return}N(),F(Se)}catch(de){if(!dt(g,D.current,le,C.current))return;N(),F({sessionId:T,status:"failed",message:de instanceof Error?de.message:"查询密码登录状态失败",qrCodeUrl:""})}},[N,c,n]),se=r.useCallback(async()=>{var oe;if(!t)return;const T=l.username.trim();if(!T||!l.login_password)return;N(),(oe=W.current)==null||oe.abort();const g=++D.current;C.current=t.id;const le=new AbortController;W.current=le,F({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const ne=await xl({account_id:t.id,account:T,password:l.login_password,show_browser:l.show_browser},{signal:le.signal});if(!dt(g,D.current,t.id,C.current))return;if(!ne.success||!ne.session_id)throw new Error(ne.message||"无法启动密码登录");F({sessionId:ne.session_id,status:"processing",message:ne.message||"登录处理中",qrCodeUrl:""}),await Y(ne.session_id,g,t.id)}catch(ne){if(!dt(g,D.current,t.id,C.current))return;F({sessionId:"",status:"failed",message:ne instanceof Error?ne.message:"启动密码登录失败",qrCodeUrl:""})}},[N,l.login_password,l.show_browser,l.username,t,Y]),ue=r.useCallback(async()=>{var g;const T=A.sessionId;D.current+=1,C.current="",(g=W.current)==null||g.abort(),N(),T&&await ul(T).catch(()=>{}),F({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},[N,A.sessionId]),ve=r.useCallback(async()=>{var T,g,le;(T=B.current)==null||T.abort(),Z.current+=1,(g=M.current)==null||g.abort(),(le=k.current)==null||le.abort(),(A.status==="processing"||A.status==="verification_required")&&await ue(),a(null)},[ue,A.status,a]),R=r.useCallback(()=>{var T;b.current+=1,(T=k.current)==null||T.abort(),a(null)},[a]);return r.useEffect(()=>(()=>{var T,g,le,oe;(T=B.current)==null||T.abort(),(g=M.current)==null||g.abort(),(le=k.current)==null||le.abort(),(oe=W.current)==null||oe.abort(),N()}),[N]),{longLogin:u,notifChannels:m,selectedChannelIds:x,bindingsLoaded:_,bindingsLoading:q,bindingsDirty:O,bindingsLoadError:G,aiSettings:X,saving:j,passwordLoginView:A,setAiSettings:y,setBindingsDirty:P,setEditForm:n,openEditModal:U,closeEditModal:ve,openAIModal:ge,closeAIModal:R,loadNotificationBindings:ee,toggleNotificationChannel:be,handleLongLoginToggle:re,handleSaveAISettings:$,handleSaveEdit:L,handleRestartPause:V,handlePasswordLogin:se,handleCancelPasswordLogin:ue}},zn=()=>{const{accounts:t,setAccounts:s,loading:a,loadAccounts:l}=Dn(),[n,c]=r.useState(""),[u,p]=r.useState(""),[m,f]=r.useState(""),[x,h]=r.useState(null),[_,S]=r.useState(""),[q,w]=r.useState(!1),[O,P]=r.useState(""),[G,H]=r.useState("pending"),[X,y]=r.useState(""),[j,z]=r.useState(""),[A,F]=r.useState(""),[d,B]=r.useState(null),[Z,M]=r.useState(null),[b,k]=r.useState(null),[D,C]=r.useState(null),[W,K]=r.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),N=Fn({editingAccount:b,setEditingAccount:k,setActiveModal:M,editForm:W,setEditForm:K,loadAccounts:l}),{longLogin:ee,notifChannels:be,selectedChannelIds:U,bindingsLoaded:re,bindingsLoading:ge,bindingsLoadError:$,aiSettings:L,saving:V,passwordLoginView:Y,setAiSettings:se,setBindingsDirty:ue,openEditModal:ve,closeEditModal:R,openAIModal:T,closeAIModal:g,loadNotificationBindings:le,toggleNotificationChannel:oe,handleLongLoginToggle:ne,handleSaveAISettings:de,handleSaveEdit:Se,handleRestartPause:Ee,handlePasswordLogin:Te,handleCancelPasswordLogin:Ue}=N,Me=r.useRef(null),Be=r.useRef(null),Je=r.useRef(null),He=r.useRef(null);Me.current===null&&(Me.current=Sn()),Be.current===null&&(Be.current=Cn());const we=()=>{He.current!==null&&(window.clearTimeout(He.current),He.current=null)},pe=()=>{var v;(v=Me.current)==null||v.stop()},Ke=()=>{var v,E;(v=Je.current)==null||v.abort(),(E=Be.current)==null||E.cancel(),pe(),we(),w(!1)},it=()=>{we(),He.current=window.setTimeout(()=>{He.current=null,w(!1),l()},1e3)};r.useEffect(()=>(()=>{var v,E;pe(),(v=Be.current)==null||v.cancel(),(E=Je.current)==null||E.abort(),we()}),[]);const tt=async(v,E)=>{await ll(v,!E),l()},Ve=v=>{m||(S(""),h(v))},Ge=()=>{m||(S(""),h(null))},ot=async()=>{const v=x;if(!(!v||m)){f(v.id),S("");try{await nl(v.id),s(E=>E.filter(ae=>ae.id!==v.id)),h(null)}catch(E){console.error("删除账号失败:",E),S((E==null?void 0:E.message)||"删除账号失败,请稍后重试")}finally{f("")}}},pt=async v=>{p(v.id);try{const E=await pl(v.id);E!=null&&E.profile_error&&alert("资料刷新失败:"+E.profile_error),await l()}catch(E){console.error("刷新账号资料失败:",E),alert((E==null?void 0:E.message)||"刷新账号资料失败,请先重新授权该账号")}finally{p("")}},ht=async(v,E)=>{const ae=await rl(v,E==null?void 0:E.id);if(!ae.success||!ae.account_id)throw new Error(ae.message||"保存扫码授权失败");return ae.account_id},J=async v=>{var fe,De,Ne,Pe;pe(),(fe=Je.current)==null||fe.abort();const E=new AbortController;Je.current=E;const ae=Be.current.next();we();const ce=v||null;B(ce),w(!0),H("loading"),y(""),P(""),z(""),F("");try{const me=await sl({signal:E.signal});if(!((De=Be.current)!=null&&De.isCurrent(ae)))return;if(!me.success||!me.qr_code_url||!me.session_id)throw new Error(me.message||"闲鱼未返回可用的登录二维码");if(me.success&&me.qr_code_url&&me.session_id){const o=me.session_id;P(me.qr_code_url),H("waiting"),(Ne=Me.current)==null||Ne.start(o,al,{onSuccess:(async()=>{try{if(!await ht(o,ce)){H("error");return}}catch(Q){console.error("保存扫码授权失败",Q),H("error");return}H("success"),it()}),onScanned:(()=>{H("waiting")}),onTerminalError:(()=>{H("error")}),onPollError:(Q=>{console.error("轮询扫码状态失败",Q),H("error")}),onVerificationRequired:(Q=>{H("verification"),Q.face_qr_url&&F(Q.face_qr_url),Q.verification_screenshot&&z(Q.verification_screenshot)})})}}catch(me){if(!((Pe=Be.current)!=null&&Pe.isCurrent(ae)))return;y(me instanceof Error?me.message:"二维码获取失败,请稍后重试"),H("error")}finally{Je.current===E&&(Je.current=null)}};if(a)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(_e,{className:"w-8 h-8 text-brand animate-spin"})});const ie=t.filter(v=>{const E=n.trim().toLowerCase();return E?[v.id,v.nickname,v.remark,v.username,v.runtime_message].some(ae=>(ae||"").toLowerCase().includes(E)):!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:n,onChange:(v=>c(v.target.value)),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:(()=>J()),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(rs,{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:["当前显示 ",ie.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[ie.map(v=>{const E=Tn(v),ae=v.runtime_state==="auth_expired"||v.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:[v.avatar_url?e.jsx("img",{src:v.avatar_url,alt:v.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(yt,{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 ${E.dot}`,children:v.runtime_state==="online"&&e.jsx(Ye,{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:v.nickname||v.remark||`账号 ${v.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${E.badge}`,children:E.label}),v.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(wt,{className:"w-3 h-3"})," AI"]}),v.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($t,{className:"h-3 w-3"})," 自动评价"]}),v.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(Ds,{className:"h-3 w-3"})," 每日擦亮"]}),v.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(Ye,{className:"h-3 w-3"})," 自动确认发货"]}),v.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:v.profile_error,children:[e.jsx(ut,{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:v.remark||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",v.id]})]}),v.runtime_message&&v.runtime_state!=="online"&&v.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${ae?"text-red-700":"text-amber-700"}`,children:[e.jsx(ut,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:v.runtime_message}),ae&&e.jsxs("button",{type:"button",onClick:(()=>J(v)),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(rs,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),v.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(La,{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:(()=>pt(v)),disabled:u===v.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(We,{className:`w-5 h-5 ${u===v.id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>J(v)),className:`p-3 rounded-xl transition-colors ${ae?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(rs,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>ve(v)),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Ra,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>T(v)),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(wt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>C(v)),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(Sa,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>tt(v.id,v.enabled)),className:`p-3 rounded-xl transition-colors ${v.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:v.enabled?"停用账号":"启用账号",children:e.jsx(gr,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>Ve(v)),disabled:m!=="",className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:m===v.id?"删除中…":`删除账号 ${v.nickname||v.remark||v.id}`,children:m===v.id?e.jsx(_e,{className:"w-5 h-5 animate-spin"}):e.jsx(Ze,{className:"w-5 h-5"})})]})]})]})]})},v.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(yt,{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&&ie.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。"})]})]}),D&&Oe.createPortal(e.jsx(In,{account:D,onClose:(()=>C(null)),onSaved:(v=>{s(E=>E.map(ae=>ae.id===D.id?{...ae,auto_rate_enabled:v.auto_rate_enabled,rate_content:v.rate_content,auto_polish_enabled:v.auto_polish_enabled,polish_time:v.polish_time,last_rate_scan_at:v.last_rate_scan_at,last_polish_date:v.last_polish_date,last_polish_at:v.last_polish_at}:ae))})}),document.body),x&&Oe.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(Ze,{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:Ge,disabled:m!=="",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(ke,{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:x.nickname||x.remark||"未命名账号"}),x.remark&&x.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",x.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",x.id]})]}),m===x.id&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(_e,{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:"正在清理关联数据,请保持页面打开…"})]})]}),_&&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(ut,{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:_})]})]})]}),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:Ge,disabled:m!=="",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 ot()),disabled:m!=="",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:m===x.id?e.jsxs(e.Fragment,{children:[e.jsx(_e,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),q&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:Ke,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:e.jsx(ke,{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:d?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:d?`请用闲鱼APP扫码,为「${d.nickname||d.remark||d.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 ${G==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[G==="loading"&&e.jsx(_e,{className:"w-10 h-10 text-brand animate-spin"}),G==="waiting"&&e.jsx(Va,{src:O,alt:"闲鱼登录二维码",className:"p-2"}),G==="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(Ye,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),G==="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:X||"请关闭窗口后重新发起扫码登录。"})]}),G==="verification"&&e.jsx(Ln,{faceQrUrl:A,verificationScreenshot:j})]}),G!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),Z==="edit"&&b&&e.jsx(An,{account:b,editForm:W,setEditForm:K,saving:V,onClose:R,onSave:Se,onRestartPause:Ee,longLogin:ee,onToggleLongLogin:ne,passwordLoginView:Y,onPasswordLogin:Te,onCancelPasswordLogin:Ue,notifChannels:be,selectedChannelIds:U,bindingsLoaded:re,bindingsLoading:ge,bindingsLoadError:$,onRetryBindings:(()=>le(b.id)),onToggleChannel:oe,onSettingsDirty:(()=>ue(!0))}),Z==="ai-settings"&&b&&Oe.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(wt,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:b.nickname||b.remark||b.id})]}),e.jsx("button",{onClick:g,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(ke,{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(wt,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:(()=>se({...L,ai_enabled:!L.ai_enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${L.ai_enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${L.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:L.max_discount_percent,onChange:(v=>se({...L,max_discount_percent:parseInt(v.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:L.max_discount_amount,onChange:(v=>se({...L,max_discount_amount:parseInt(v.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:L.max_bargain_rounds,onChange:(v=>se({...L,max_bargain_rounds:parseInt(v.target.value)||1})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:L.custom_prompts,onChange:(v=>se({...L,custom_prompts:v.target.value})),placeholder:`输入自定义的AI回复规则或风格指引... -例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Ps,{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:g,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:V,children:"取消"}),e.jsxs("button",{onClick:de,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:V,children:[V?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),V?"保存中...":"保存"]})]})})]})}),document.body)]})},Un=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Wn=t=>{const s=typeof t=="object"&&t!==null?t:{},a=Array.isArray(s.results)?s.results:[];return{total:Number(s.total||0),success_count:Number(s.success_count||0),failed_count:Number(s.failed_count||0),results:a.map(Jn)}},Jn=t=>{const s=typeof t=="object"&&t!==null?t:{};return{order_id:String(s.order_id||"unknown"),success:s.success===!0,message:String(s.message||"")}},Gn=t=>(t==null?void 0:t.results.filter(Kn))||[],Kn=t=>!t.success,Vn=(t,s)=>t!==null&&!s,Qn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ft=(t,s)=>t===s,Hn=(t,s)=>t instanceof Error&&t.message?t.message:s,Zn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:c,searchText:u,onSearchChange:h})=>{const m=p=>s(p.currentTarget.dataset.status||"all"),j=p=>l(p.target.value),x=p=>h(p.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:Un.map(p=>e.jsx("button",{"data-status":p.key,onClick:m,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===p.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:p.label},p.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(yt,{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:a,onChange:j,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:"全部账号"}),n.map(p=>e.jsx("option",{value:p.id,children:c(p.id)},p.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(St,{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:u,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Yn=t=>{const s=c=>{var u;t.setImportFile(((u=c.target.files)==null?void 0:u[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Oe.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:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:s,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 格式"})]}),t.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(Mt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:t.importFile.name})]})}),t.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:t.importError}),e.jsx("button",{type:"button",onClick:n,disabled:t.importing||!t.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),t.importResult&&t.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:["导入完成:成功 ",t.importResult.success_count," 条,失败 ",t.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:Gn(t.importResult).map((c,u)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:c.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:c.message||"导入失败"})]},`${c.order_id}-${u}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:a,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:l,disabled:!t.importFile||t.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:t.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Xn=(t={pageSize:20})=>{const[s,a]=r.useState([]),[l,n]=r.useState([]),[c,u]=r.useState([]),[h,m]=r.useState("all"),[j,x]=r.useState(""),[p,_]=r.useState(""),[S,q]=r.useState(""),[w,O]=r.useState(1),[P,G]=r.useState(1),[H,X]=r.useState(!1),f=r.useRef(0),y=r.useRef(null),z=r.useRef(null),I=r.useCallback(async()=>{var D;const b=++f.current;(D=y.current)==null||D.abort();const k=new AbortController;y.current=k,X(!0);try{const C=await gl(j||void 0,h,w,t.pageSize,S,{signal:k.signal});if(!ft(b,f.current))return;a(C.data),G(C.total_pages)}catch(C){ft(b,f.current)&&!k.signal.aborted&&console.error("加载订单失败:",C)}finally{ft(b,f.current)&&X(!1)}},[j,S,h,t.pageSize,w]);r.useEffect(()=>{const b=window.setTimeout(()=>{O(1),q(p.trim())},300);return(()=>window.clearTimeout(b))},[p]),r.useEffect(()=>(I(),(()=>{var b;f.current+=1,(b=y.current)==null||b.abort()})),[I]),r.useEffect(()=>{var k;const b=new AbortController;return(k=z.current)==null||k.abort(),z.current=b,Promise.all([Ft({signal:b.signal}),Lt(void 0,{signal:b.signal})]).then(([D,C])=>{b.signal.aborted||(u(D),n(C))}).catch(D=>{b.signal.aborted||console.error("加载订单辅助数据失败:",D)}),(()=>b.abort())},[]);const F=r.useMemo(()=>new Map(c.map(b=>[b.id,b])),[c]),d=r.useMemo(()=>{const b={};return l.forEach(k=>{k.item_id&&(b[`${k.cookie_id}:${k.item_id}`]=k.item_title||k.item_id)}),b},[l]),B=r.useCallback(b=>{const k=F.get(b),D=(k==null?void 0:k.remark)||(k==null?void 0:k.nickname);return D?`${D} · ${b.slice(0,6)}`:`账号 ${b.slice(0,8)}`},[F]),Z=r.useCallback(b=>{const k=F.get(b);return(k==null?void 0:k.remark)||(k==null?void 0:k.nickname)||"未命名账号"},[F]),M=r.useCallback((b,k,D)=>{if(D!=null&&D.trim())return D;const C=d[`${b}:${k}`];if(C)return C;const W=l.find(K=>{if(!D||!K.item_title)return!1;const N=D.toLowerCase(),ee=K.item_title.toLowerCase();return ee.includes(N)||N.includes(ee)});return(W==null?void 0:W.item_title)||"未知商品"},[d,l]);return{orders:s,items:l,accounts:c,filter:h,setFilter:m,accountFilter:j,setAccountFilter:x,searchText:p,setSearchText:_,page:w,setPage:O,totalPages:P,loading:H,loadOrders:I,accountName:B,accountNickname:Z,getItemNameById:M}},ei=t=>{const[s,a]=r.useState(!1),[l,n]=r.useState(null),[c,u]=r.useState(null),[h,m]=r.useState(!1),[j,x]=r.useState(""),p=r.useRef(0),_=r.useRef(null),S=r.useCallback(()=>{n(null),u(null),x(""),a(!0)},[]),q=r.useCallback(()=>{var P;p.current+=1,(P=_.current)==null||P.abort(),m(!1),a(!1),n(null),u(null),x("")},[]),w=r.useCallback(async()=>{var f;if(!Vn(l,h))return;const P=l;if(!P)return;const G=Qn(P);if(G){x(G);return}const H=++p.current;(f=_.current)==null||f.abort();const X=new AbortController;_.current=X,m(!0),u(null),x("");try{const y=new FormData;y.append("file",P);const z=Wn(await Nl(y,{signal:X.signal}));if(!ft(H,p.current))return;u(z),n(null),await t(),z.failed_count===0&&ft(H,p.current)&&(alert(`订单导入成功,共 ${z.success_count} 条`),a(!1),u(null))}catch(y){ft(H,p.current)&&!X.signal.aborted&&x(Hn(y,"导入失败,请检查文件格式"))}finally{ft(H,p.current)&&m(!1)}},[l,h,t]),O=r.useCallback(async()=>{await w()},[w]);return{showImportModal:s,importFile:l,setImportFile:n,importResult:c,importing:h,importError:j,openImportModal:S,closeImportModal:q,handleImportOrders:w,handleRetryImport:O}},da=({status:t})=>{const s={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:`px-3 py-1.5 rounded-lg text-xs font-bold ${s[t]||s.cancelled}`,children:a[t]||t})},ti=()=>{const t=Xn(),s=ei(t.loadOrders),{orders:a,accounts:l,filter:n,setFilter:c,accountFilter:u,setAccountFilter:h,searchText:m,setSearchText:j,page:x,setPage:p,totalPages:_,loading:S,loadOrders:q,accountName:w,accountNickname:O,getItemNameById:P}=t,[G,H]=r.useState(!1),[X,f]=r.useState(!1),[y,z]=r.useState(null),[I,F]=r.useState(null),[d,B]=r.useState(!1),[Z,M]=r.useState(""),[b,k]=r.useState(!1),[D,C]=r.useState(null),[W,K]=r.useState(null),[N,ee]=r.useState(null),be=R=>{c(R),p(1),j("")},U=R=>{h(R),p(1)},re=R=>{j(R),p(1)},ge=async()=>{try{const R=await yl(u||void 0,n);await q(),R!=null&&R.message&&alert(R.message)}catch(R){console.error("同步订单失败:",R),alert((R==null?void 0:R.message)||"同步失败,请重试")}},$=R=>{M(R),C(null),B(!0)},L=async R=>{var T;k(!0),C(null);try{const g=await vl([Z],R),le=(T=g==null?void 0:g.results)==null?void 0:T[0];le!=null&&le.success?(C({success:!0,message:le.message}),q()):C({success:!1,message:(le==null?void 0:le.message)||"发货失败"})}catch(g){C({success:!1,message:(g==null?void 0:g.message)||"请求失败"})}finally{k(!1)}},V=R=>{z(R),H(!0)},Y=R=>{F({...R}),f(!0)},se=async()=>{if(!(!I||!I.order_id))try{const R={};I.status!==void 0&&(R.order_status=I.status),I.buyer_id!==void 0&&(R.buyer_id=I.buyer_id),I.amount!==void 0&&(R.amount=I.amount),I.receiver_name!==void 0&&(R.receiver_name=I.receiver_name),I.receiver_phone!==void 0&&(R.receiver_phone=I.receiver_phone),I.receiver_address!==void 0&&(R.receiver_address=I.receiver_address),I.item_id!==void 0&&(R.item_id=I.item_id),I.quantity!==void 0&&(R.quantity=I.quantity),I.item_title!==void 0&&(R.item_title=I.item_title),await bl(I.order_id,R),f(!1),F(null),q()}catch(R){console.error("更新订单失败:",R),alert("更新失败,请重试")}},ue=async R=>{K(R);try{const T=await jl(R);T.success?await q():alert(T.message||"同步失败")}catch(T){console.error("同步订单失败:",T),alert((T==null?void 0:T.message)||"同步失败,请重试")}finally{K(null)}},ve=async R=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){ee(R);try{await fl(R),a.length===1&&x>1?p(T=>T-1):await q()}catch(T){console.error("删除订单失败:",T),alert((T==null?void 0:T.message)||"删除失败,请重试"),await q()}finally{ee(null)}}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:q,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(We,{className:`w-5 h-5 ${S?"animate-spin":""}`})}),e.jsxs("button",{onClick:s.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(nt,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:ge,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(zs,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Zn,{filter:n,onFilterChange:be,accountFilter:u,onAccountFilterChange:U,accounts:l,accountName:w,searchText:m,onSearchChange:re}),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:a.map(R=>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:R.item_image?e.jsx("img",{src:R.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(Bt,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:P(R.cookie_id,R.item_id,R.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:O(R.cookie_id),children:[e.jsx(yt,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:O(R.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",R.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",R.quantity," • ",Ls(R.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:R.buyer_id}),R.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:R.receiver_name})]}),R.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:R.receiver_phone})]}),R.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:R.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:R.amount?`¥${R.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(da,{status:R.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[R.status==="pending_ship"&&e.jsx("button",{onClick:(()=>$(R.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=${R.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(Ca,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>V(R)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(mt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>Y(R)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>ue(R.order_id)),disabled:W===R.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(We,{className:`w-4 h-4 ${W===R.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>ve(R.order_id)),disabled:N===R.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(Ze,{className:"w-4 h-4"})})]})]},R.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:["第 ",x," 页 / 共 ",_," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:x<=1,onClick:(()=>p(R=>R-1)),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(Es,{className:"w-5 h-5"})}),e.jsx("button",{disabled:x>=_,onClick:(()=>p(R=>R+1)),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(Ts,{className:"w-5 h-5"})})]})]})]}),G&&y&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:(()=>H(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:y.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:O(y.cookie_id),children:O(y.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(da,{status:y.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:y.amount?`¥${y.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:y.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:Ls(y.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:[y.item_image&&e.jsx("img",{src:y.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:P(y.cookie_id,y.item_id,y.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",y.item_id]}),y.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",y.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:y.buyer_id})]}),y.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:y.receiver_name})]}),y.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:y.receiver_phone})]}),y.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:y.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>H(!1)),className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),y.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{H(!1),$(y.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(Yn,{...s}),d&&Oe.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:(()=>{B(!1),C(null)}),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:(()=>L("status_only")),disabled:b,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(zs,{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:(()=>L("full_delivery")),disabled:b,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(Bt,{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:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),b&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(We,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),D&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${D.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[D.success?"✓ ":"✗ ",D.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:(()=>{B(!1),C(null)}),className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:D!=null&&D.success?"完成":"取消"})})]})}),document.body),X&&I&&Oe.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:(()=>f(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:I.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:I.status,onChange:(R=>F({...I,status:R.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:I.buyer_id,onChange:(R=>F({...I,buyer_id:R.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:I.amount,onChange:(R=>F({...I,amount:R.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:I.receiver_name||"",onChange:(R=>F({...I,receiver_name:R.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:I.receiver_phone||"",onChange:(R=>F({...I,receiver_phone:R.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:I.receiver_address||"",onChange:(R=>F({...I,receiver_address:R.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:I.item_title||"",onChange:(R=>F({...I,item_title:R.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:(()=>f(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:se,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},si=({dataCards:t,downloadCardTemplate:s,...a})=>{var w;const l=O=>{var P;a.setBatchFile(((P=O.target.files)==null?void 0:P[0])||null)},n=O=>{a.setAppendContent(O.target.value)},c=O=>{a.setAppendTargetId(O.target.value)},u=()=>a.closeBatchModal(),h=()=>a.setBatchTab("create"),m=()=>a.setBatchTab("append"),j=()=>void a.handleRetryBatchCreate(),x=()=>void a.handleRetryBatchAppend(),p=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,_=O=>e.jsxs("option",{value:String(O.id),children:[O.name,"(ID: ",O.id,")"]},O.id),S=()=>void a.handleBatchCreate(),q=()=>void a.handleBatchAppend();return a.showBatchModal?Oe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:u,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(ke,{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:h,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(br,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:m,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Mt,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.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:s,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(fr,{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(Mt,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:l})]})]}),((w=a.batchResult)==null?void 0:w.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:a.batchResult.error}),e.jsx("button",{type:"button",onClick:j,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),p&&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:["共 ",p.total," 行 · 成功 ",p.created," · 失败 ",p.failed]}),p.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:p.rows.filter(O=>!O.success).map(O=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",O.row_no," 行「",O.name,"」:",O.error]},O.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:t.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:a.appendTargetId,onChange:c,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:t.map(_)})]}),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:a.appendContent,onChange:n,placeholder:`VIP-001 +例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,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(Ps,{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:g,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:V,children:"取消"}),e.jsxs("button",{onClick:de,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:V,children:[V?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),V?"保存中...":"保存"]})]})})]})}),document.body)]})},Un=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Wn=t=>{const s=typeof t=="object"&&t!==null?t:{},a=Array.isArray(s.results)?s.results:[];return{total:Number(s.total||0),success_count:Number(s.success_count||0),failed_count:Number(s.failed_count||0),results:a.map(Jn)}},Jn=t=>{const s=typeof t=="object"&&t!==null?t:{};return{order_id:String(s.order_id||"unknown"),success:s.success===!0,message:String(s.message||"")}},Gn=t=>(t==null?void 0:t.results.filter(Kn))||[],Kn=t=>!t.success,Vn=(t,s)=>t!==null&&!s,Qn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ft=(t,s)=>t===s,Hn=(t,s)=>t instanceof Error&&t.message?t.message:s,Zn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:c,searchText:u,onSearchChange:p})=>{const m=h=>s(h.currentTarget.dataset.status||"all"),f=h=>l(h.target.value),x=h=>p(h.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:Un.map(h=>e.jsx("button",{"data-status":h.key,onClick:m,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===h.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:h.label},h.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(yt,{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:a,onChange:f,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:"全部账号"}),n.map(h=>e.jsx("option",{value:h.id,children:c(h.id)},h.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(St,{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:u,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Yn=t=>{const s=c=>{var u;t.setImportFile(((u=c.target.files)==null?void 0:u[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Oe.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:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:s,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 格式"})]}),t.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(Mt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:t.importFile.name})]})}),t.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:t.importError}),e.jsx("button",{type:"button",onClick:n,disabled:t.importing||!t.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),t.importResult&&t.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:["导入完成:成功 ",t.importResult.success_count," 条,失败 ",t.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:Gn(t.importResult).map((c,u)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:c.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:c.message||"导入失败"})]},`${c.order_id}-${u}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:a,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:l,disabled:!t.importFile||t.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:t.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Xn=(t={pageSize:20})=>{const[s,a]=r.useState([]),[l,n]=r.useState([]),[c,u]=r.useState([]),[p,m]=r.useState("all"),[f,x]=r.useState(""),[h,_]=r.useState(""),[S,q]=r.useState(""),[w,O]=r.useState(1),[P,G]=r.useState(1),[H,X]=r.useState(!1),y=r.useRef(0),j=r.useRef(null),z=r.useRef(null),A=r.useCallback(async()=>{var D;const b=++y.current;(D=j.current)==null||D.abort();const k=new AbortController;j.current=k,X(!0);try{const C=await gl(f||void 0,p,w,t.pageSize,S,{signal:k.signal});if(!ft(b,y.current))return;a(C.data),G(C.total_pages)}catch(C){ft(b,y.current)&&!k.signal.aborted&&console.error("加载订单失败:",C)}finally{ft(b,y.current)&&X(!1)}},[f,S,p,t.pageSize,w]);r.useEffect(()=>{const b=window.setTimeout(()=>{O(1),q(h.trim())},300);return(()=>window.clearTimeout(b))},[h]),r.useEffect(()=>(A(),(()=>{var b;y.current+=1,(b=j.current)==null||b.abort()})),[A]),r.useEffect(()=>{var k;const b=new AbortController;return(k=z.current)==null||k.abort(),z.current=b,Promise.all([Ft({signal:b.signal}),Lt(void 0,{signal:b.signal})]).then(([D,C])=>{b.signal.aborted||(u(D),n(C))}).catch(D=>{b.signal.aborted||console.error("加载订单辅助数据失败:",D)}),(()=>b.abort())},[]);const F=r.useMemo(()=>new Map(c.map(b=>[b.id,b])),[c]),d=r.useMemo(()=>{const b={};return l.forEach(k=>{k.item_id&&(b[`${k.cookie_id}:${k.item_id}`]=k.item_title||k.item_id)}),b},[l]),B=r.useCallback(b=>{const k=F.get(b),D=(k==null?void 0:k.remark)||(k==null?void 0:k.nickname);return D?`${D} · ${b.slice(0,6)}`:`账号 ${b.slice(0,8)}`},[F]),Z=r.useCallback(b=>{const k=F.get(b);return(k==null?void 0:k.remark)||(k==null?void 0:k.nickname)||"未命名账号"},[F]),M=r.useCallback((b,k,D)=>{if(D!=null&&D.trim())return D;const C=d[`${b}:${k}`];if(C)return C;const W=l.find(K=>{if(!D||!K.item_title)return!1;const N=D.toLowerCase(),ee=K.item_title.toLowerCase();return ee.includes(N)||N.includes(ee)});return(W==null?void 0:W.item_title)||"未知商品"},[d,l]);return{orders:s,items:l,accounts:c,filter:p,setFilter:m,accountFilter:f,setAccountFilter:x,searchText:h,setSearchText:_,page:w,setPage:O,totalPages:P,loading:H,loadOrders:A,accountName:B,accountNickname:Z,getItemNameById:M}},ei=t=>{const[s,a]=r.useState(!1),[l,n]=r.useState(null),[c,u]=r.useState(null),[p,m]=r.useState(!1),[f,x]=r.useState(""),h=r.useRef(0),_=r.useRef(null),S=r.useCallback(()=>{n(null),u(null),x(""),a(!0)},[]),q=r.useCallback(()=>{var P;h.current+=1,(P=_.current)==null||P.abort(),m(!1),a(!1),n(null),u(null),x("")},[]),w=r.useCallback(async()=>{var y;if(!Vn(l,p))return;const P=l;if(!P)return;const G=Qn(P);if(G){x(G);return}const H=++h.current;(y=_.current)==null||y.abort();const X=new AbortController;_.current=X,m(!0),u(null),x("");try{const j=new FormData;j.append("file",P);const z=Wn(await Nl(j,{signal:X.signal}));if(!ft(H,h.current))return;u(z),n(null),await t(),z.failed_count===0&&ft(H,h.current)&&(alert(`订单导入成功,共 ${z.success_count} 条`),a(!1),u(null))}catch(j){ft(H,h.current)&&!X.signal.aborted&&x(Hn(j,"导入失败,请检查文件格式"))}finally{ft(H,h.current)&&m(!1)}},[l,p,t]),O=r.useCallback(async()=>{await w()},[w]);return{showImportModal:s,importFile:l,setImportFile:n,importResult:c,importing:p,importError:f,openImportModal:S,closeImportModal:q,handleImportOrders:w,handleRetryImport:O}},da=({status:t})=>{const s={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:`px-3 py-1.5 rounded-lg text-xs font-bold ${s[t]||s.cancelled}`,children:a[t]||t})},ti=()=>{const t=Xn(),s=ei(t.loadOrders),{orders:a,accounts:l,filter:n,setFilter:c,accountFilter:u,setAccountFilter:p,searchText:m,setSearchText:f,page:x,setPage:h,totalPages:_,loading:S,loadOrders:q,accountName:w,accountNickname:O,getItemNameById:P}=t,[G,H]=r.useState(!1),[X,y]=r.useState(!1),[j,z]=r.useState(null),[A,F]=r.useState(null),[d,B]=r.useState(!1),[Z,M]=r.useState(""),[b,k]=r.useState(!1),[D,C]=r.useState(null),[W,K]=r.useState(null),[N,ee]=r.useState(null),be=R=>{c(R),h(1),f("")},U=R=>{p(R),h(1)},re=R=>{f(R),h(1)},ge=async()=>{try{const R=await yl(u||void 0,n);await q(),R!=null&&R.message&&alert(R.message)}catch(R){console.error("同步订单失败:",R),alert((R==null?void 0:R.message)||"同步失败,请重试")}},$=R=>{M(R),C(null),B(!0)},L=async R=>{var T;k(!0),C(null);try{const g=await vl([Z],R),le=(T=g==null?void 0:g.results)==null?void 0:T[0];le!=null&&le.success?(C({success:!0,message:le.message}),q()):C({success:!1,message:(le==null?void 0:le.message)||"发货失败"})}catch(g){C({success:!1,message:(g==null?void 0:g.message)||"请求失败"})}finally{k(!1)}},V=R=>{z(R),H(!0)},Y=R=>{F({...R}),y(!0)},se=async()=>{if(!(!A||!A.order_id))try{const R={};A.status!==void 0&&(R.order_status=A.status),A.buyer_id!==void 0&&(R.buyer_id=A.buyer_id),A.amount!==void 0&&(R.amount=A.amount),A.receiver_name!==void 0&&(R.receiver_name=A.receiver_name),A.receiver_phone!==void 0&&(R.receiver_phone=A.receiver_phone),A.receiver_address!==void 0&&(R.receiver_address=A.receiver_address),A.item_id!==void 0&&(R.item_id=A.item_id),A.quantity!==void 0&&(R.quantity=A.quantity),A.item_title!==void 0&&(R.item_title=A.item_title),await bl(A.order_id,R),y(!1),F(null),q()}catch(R){console.error("更新订单失败:",R),alert("更新失败,请重试")}},ue=async R=>{K(R);try{const T=await jl(R);T.success?await q():alert(T.message||"同步失败")}catch(T){console.error("同步订单失败:",T),alert((T==null?void 0:T.message)||"同步失败,请重试")}finally{K(null)}},ve=async R=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){ee(R);try{await fl(R),a.length===1&&x>1?h(T=>T-1):await q()}catch(T){console.error("删除订单失败:",T),alert((T==null?void 0:T.message)||"删除失败,请重试"),await q()}finally{ee(null)}}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:q,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(We,{className:`w-5 h-5 ${S?"animate-spin":""}`})}),e.jsxs("button",{onClick:s.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(nt,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:ge,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(zs,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Zn,{filter:n,onFilterChange:be,accountFilter:u,onAccountFilterChange:U,accounts:l,accountName:w,searchText:m,onSearchChange:re}),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:a.map(R=>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:R.item_image?e.jsx("img",{src:R.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(Bt,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:P(R.cookie_id,R.item_id,R.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:O(R.cookie_id),children:[e.jsx(yt,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:O(R.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",R.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",R.quantity," • ",Ls(R.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:R.buyer_id}),R.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:R.receiver_name})]}),R.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:R.receiver_phone})]}),R.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:R.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:R.amount?`¥${R.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(da,{status:R.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[R.status==="pending_ship"&&e.jsx("button",{onClick:(()=>$(R.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=${R.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(Ca,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>V(R)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(mt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>Y(R)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>ue(R.order_id)),disabled:W===R.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(We,{className:`w-4 h-4 ${W===R.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>ve(R.order_id)),disabled:N===R.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(Ze,{className:"w-4 h-4"})})]})]},R.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:["第 ",x," 页 / 共 ",_," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:x<=1,onClick:(()=>h(R=>R-1)),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(Es,{className:"w-5 h-5"})}),e.jsx("button",{disabled:x>=_,onClick:(()=>h(R=>R+1)),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(Ts,{className:"w-5 h-5"})})]})]})]}),G&&j&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:(()=>H(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:j.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:O(j.cookie_id),children:O(j.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(da,{status:j.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:j.amount?`¥${j.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:j.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:Ls(j.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:[j.item_image&&e.jsx("img",{src:j.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:P(j.cookie_id,j.item_id,j.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",j.item_id]}),j.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",j.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:j.buyer_id})]}),j.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:j.receiver_name})]}),j.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:j.receiver_phone})]}),j.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:j.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>H(!1)),className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),j.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{H(!1),$(j.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(Yn,{...s}),d&&Oe.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:(()=>{B(!1),C(null)}),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:(()=>L("status_only")),disabled:b,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(zs,{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:(()=>L("full_delivery")),disabled:b,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(Bt,{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:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),b&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(We,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),D&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${D.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[D.success?"✓ ":"✗ ",D.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:(()=>{B(!1),C(null)}),className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:D!=null&&D.success?"完成":"取消"})})]})}),document.body),X&&A&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:(()=>y(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:A.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:A.status,onChange:(R=>F({...A,status:R.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:A.buyer_id,onChange:(R=>F({...A,buyer_id:R.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:A.amount,onChange:(R=>F({...A,amount:R.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:A.receiver_name||"",onChange:(R=>F({...A,receiver_name:R.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:A.receiver_phone||"",onChange:(R=>F({...A,receiver_phone:R.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:A.receiver_address||"",onChange:(R=>F({...A,receiver_address:R.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:A.item_title||"",onChange:(R=>F({...A,item_title:R.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:(()=>y(!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:se,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},si=({dataCards:t,downloadCardTemplate:s,...a})=>{var w;const l=O=>{var P;a.setBatchFile(((P=O.target.files)==null?void 0:P[0])||null)},n=O=>{a.setAppendContent(O.target.value)},c=O=>{a.setAppendTargetId(O.target.value)},u=()=>a.closeBatchModal(),p=()=>a.setBatchTab("create"),m=()=>a.setBatchTab("append"),f=()=>void a.handleRetryBatchCreate(),x=()=>void a.handleRetryBatchAppend(),h=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,_=O=>e.jsxs("option",{value:String(O.id),children:[O.name,"(ID: ",O.id,")"]},O.id),S=()=>void a.handleBatchCreate(),q=()=>void a.handleBatchAppend();return a.showBatchModal?Oe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:u,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(ke,{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:p,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(br,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:m,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Mt,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.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:s,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(fr,{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(Mt,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:l})]})]}),((w=a.batchResult)==null?void 0:w.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:a.batchResult.error}),e.jsx("button",{type:"button",onClick:f,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),h&&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:["共 ",h.total," 行 · 成功 ",h.created," · 失败 ",h.failed]}),h.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:h.rows.filter(O=>!O.success).map(O=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",O.row_no," 行「",O.name,"」:",O.error]},O.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:t.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:a.appendTargetId,onChange:c,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:t.map(_)})]}),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:a.appendContent,onChange:n,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:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.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:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.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:u,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:S,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Mt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:q,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(nt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ai=({type:t})=>{switch(t){case"text":return e.jsx(Ia,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Aa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(yr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Os,{className:"w-5 h-5 text-gray-500"})}},ri=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Qa=t=>t.split(` -`).map(s=>s.trim()).filter(Boolean),li=(t,s,a)=>!!(t&&Qa(s).length>0&&!a),Nt=(t,s,a,l)=>t===s&&a===l,ni=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),c=r.useRef(null),u=r.useCallback(async()=>{var j;const h=++n.current;(j=c.current)==null||j.abort();const m=new AbortController;c.current=m,l(!0);try{const x=await Ms({signal:m.signal});if(h!==n.current)return;s(x)}catch(x){h===n.current&&!m.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{h===n.current&&l(!1)}},[]);return r.useEffect(()=>(u(),()=>{var m;n.current+=1,(m=c.current)==null||m.abort()}),[u]),{cards:t,setCards:s,loading:a,loadCards:u}},ii=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[c,u]=r.useState("create"),[h,m]=r.useState(null),[j,x]=r.useState(null),[p,_]=r.useState(!1),[S,q]=r.useState(""),[w,O]=r.useState(""),[P,G]=r.useState(null),[H,X]=r.useState(""),f=r.useRef(0),y=r.useRef(null),z=r.useRef(""),I=r.useMemo(()=>Qa(w),[w]),F=r.useCallback(()=>{var k;u("create"),m(null),x(null),q((k=s[0])!=null&&k.id?String(s[0].id):""),O(""),G(null),X(""),n(!0)},[s]),d=r.useCallback(()=>{var k;f.current+=1,(k=y.current)==null||k.abort(),_(!1),n(!1)},[]),B=r.useCallback(async()=>{var C;if(!h||p)return;const k=++f.current;(C=y.current)==null||C.abort();const D=new AbortController;y.current=D,_(!0),x(null);try{const W=await Ll(h,{signal:D.signal});if(!Nt(k,f.current,"",""))return;x(W),W.created>0&&await a()}catch(W){if(!Nt(k,f.current,"",""))return;x({error:(W==null?void 0:W.message)||"上传失败"})}finally{Nt(k,f.current,"","")&&_(!1)}},[p,h,a]),Z=r.useCallback(async()=>{var W;if(!li(S,w,p))return;const k=S,D=++f.current;z.current=k,(W=y.current)==null||W.abort();const C=new AbortController;y.current=C,_(!0),G(null),X("");try{const K=await Rl(k,w,{signal:C.signal});if(!Nt(D,f.current,k,S))return;G({added:K.added}),O(""),await a()}catch(K){if(!Nt(D,f.current,k,S))return;X((K==null?void 0:K.message)||"追加失败")}finally{Nt(D,f.current,k,S)&&_(!1)}},[w,S,p,a]),M=r.useCallback(async()=>{await B()},[B]),b=r.useCallback(async()=>{z.current&&S!==z.current||await Z()},[S,Z]);return{showBatchModal:l,setShowBatchModal:n,batchTab:c,setBatchTab:u,batchFile:h,setBatchFile:m,batchResult:j,batchBusy:p,appendTargetId:S,setAppendTargetId:q,appendContent:w,setAppendContent:O,appendResult:P,appendError:H,appendPreview:I,openBatchModal:F,closeBatchModal:d,handleBatchCreate:B,handleBatchAppend:Z,handleRetryBatchCreate:M,handleRetryBatchAppend:b}},xa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),oi=()=>{const{cards:t,loadCards:s}=ni(),[a,l]=r.useState(!1),[n,c]=r.useState(!1),[u,h]=r.useState(null),[m,j]=r.useState({}),[x,p]=r.useState(xa),[_,S]=r.useState(""),[q,w]=r.useState(""),O=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),P=ii({dataCards:O,loadCards:s}),G=d=>{var B,Z,M,b,k;h(d),j({id:d.id,name:d.name||"",type:d.type||"text",api_url:((B=d.api_config)==null?void 0:B.url)||"",api_method:((Z=d.api_config)==null?void 0:Z.method)||"GET",api_timeout:((M=d.api_config)==null?void 0:M.timeout)||10,api_headers:((b=d.api_config)==null?void 0:b.headers)||"",api_params:((k=d.api_config)==null?void 0:k.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},H=async()=>{var d,B,Z,M,b,k,D,C;if(u){if(!((d=m.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!m.type){alert("请选择卡密类型");return}try{const W={name:m.name.trim(),type:m.type,description:(B=m.description)==null?void 0:B.trim(),delay_seconds:m.delay_seconds||0,enabled:m.enabled??!0};m.type==="api"?W.api_config={url:((Z=m.api_url)==null?void 0:Z.trim())||"",method:m.api_method,timeout:m.api_timeout||10,headers:((M=m.api_headers)==null?void 0:M.trim())||void 0,params:((b=m.api_params)==null?void 0:b.trim())||void 0}:m.type==="text"?W.text_content=((k=m.text_content)==null?void 0:k.trim())||"":m.type==="data"?W.data_content=((D=m.data_content)==null?void 0:D.trim())||"":m.type==="image"&&(W.image_url=((C=m.image_url)==null?void 0:C.trim())||""),await ta(u.id,W),l(!1),await s()}catch(W){console.error("更新卡密失败:",W),alert("更新失败,请重试")}}},X=async d=>{if(confirm("确认删除该卡密吗?"))try{await Sl(d),await s()}catch(B){console.error("删除卡密失败:",B),alert("删除失败,请重试")}},f=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.api_method,timeout:x.api_timeout,headers:x.api_headers.trim()||void 0,params:x.api_params.trim()||void 0}),await Cl(d),c(!1),p(xa()),await s()}catch(d){console.error("添加卡密失败:",d),alert("添加失败,请重试")}},y=async d=>{try{await ta(d.id,{...d,enabled:!d.enabled}),await s()}catch(B){console.error("切换状态失败:",B)}},z=async d=>{try{await navigator.clipboard.writeText(String(d)),alert(`已复制卡密组ID:${d}`)}catch{prompt("复制卡密组ID",String(d))}},I=r.useMemo(()=>ri(t,_,q),[t,q,_]),F=()=>{const Z=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 +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:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.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:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.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:u,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:S,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Mt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:q,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(nt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ai=({type:t})=>{switch(t){case"text":return e.jsx(Aa,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Ia,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(yr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Os,{className:"w-5 h-5 text-gray-500"})}},ri=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Qa=t=>t.split(` +`).map(s=>s.trim()).filter(Boolean),li=(t,s,a)=>!!(t&&Qa(s).length>0&&!a),Nt=(t,s,a,l)=>t===s&&a===l,ni=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),c=r.useRef(null),u=r.useCallback(async()=>{var f;const p=++n.current;(f=c.current)==null||f.abort();const m=new AbortController;c.current=m,l(!0);try{const x=await Ms({signal:m.signal});if(p!==n.current)return;s(x)}catch(x){p===n.current&&!m.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{p===n.current&&l(!1)}},[]);return r.useEffect(()=>(u(),()=>{var m;n.current+=1,(m=c.current)==null||m.abort()}),[u]),{cards:t,setCards:s,loading:a,loadCards:u}},ii=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[c,u]=r.useState("create"),[p,m]=r.useState(null),[f,x]=r.useState(null),[h,_]=r.useState(!1),[S,q]=r.useState(""),[w,O]=r.useState(""),[P,G]=r.useState(null),[H,X]=r.useState(""),y=r.useRef(0),j=r.useRef(null),z=r.useRef(""),A=r.useMemo(()=>Qa(w),[w]),F=r.useCallback(()=>{var k;u("create"),m(null),x(null),q((k=s[0])!=null&&k.id?String(s[0].id):""),O(""),G(null),X(""),n(!0)},[s]),d=r.useCallback(()=>{var k;y.current+=1,(k=j.current)==null||k.abort(),_(!1),n(!1)},[]),B=r.useCallback(async()=>{var C;if(!p||h)return;const k=++y.current;(C=j.current)==null||C.abort();const D=new AbortController;j.current=D,_(!0),x(null);try{const W=await Ll(p,{signal:D.signal});if(!Nt(k,y.current,"",""))return;x(W),W.created>0&&await a()}catch(W){if(!Nt(k,y.current,"",""))return;x({error:(W==null?void 0:W.message)||"上传失败"})}finally{Nt(k,y.current,"","")&&_(!1)}},[h,p,a]),Z=r.useCallback(async()=>{var W;if(!li(S,w,h))return;const k=S,D=++y.current;z.current=k,(W=j.current)==null||W.abort();const C=new AbortController;j.current=C,_(!0),G(null),X("");try{const K=await Rl(k,w,{signal:C.signal});if(!Nt(D,y.current,k,S))return;G({added:K.added}),O(""),await a()}catch(K){if(!Nt(D,y.current,k,S))return;X((K==null?void 0:K.message)||"追加失败")}finally{Nt(D,y.current,k,S)&&_(!1)}},[w,S,h,a]),M=r.useCallback(async()=>{await B()},[B]),b=r.useCallback(async()=>{z.current&&S!==z.current||await Z()},[S,Z]);return{showBatchModal:l,setShowBatchModal:n,batchTab:c,setBatchTab:u,batchFile:p,setBatchFile:m,batchResult:f,batchBusy:h,appendTargetId:S,setAppendTargetId:q,appendContent:w,setAppendContent:O,appendResult:P,appendError:H,appendPreview:A,openBatchModal:F,closeBatchModal:d,handleBatchCreate:B,handleBatchAppend:Z,handleRetryBatchCreate:M,handleRetryBatchAppend:b}},xa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),oi=()=>{const{cards:t,loadCards:s}=ni(),[a,l]=r.useState(!1),[n,c]=r.useState(!1),[u,p]=r.useState(null),[m,f]=r.useState({}),[x,h]=r.useState(xa),[_,S]=r.useState(""),[q,w]=r.useState(""),O=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),P=ii({dataCards:O,loadCards:s}),G=d=>{var B,Z,M,b,k;p(d),f({id:d.id,name:d.name||"",type:d.type||"text",api_url:((B=d.api_config)==null?void 0:B.url)||"",api_method:((Z=d.api_config)==null?void 0:Z.method)||"GET",api_timeout:((M=d.api_config)==null?void 0:M.timeout)||10,api_headers:((b=d.api_config)==null?void 0:b.headers)||"",api_params:((k=d.api_config)==null?void 0:k.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},H=async()=>{var d,B,Z,M,b,k,D,C;if(u){if(!((d=m.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!m.type){alert("请选择卡密类型");return}try{const W={name:m.name.trim(),type:m.type,description:(B=m.description)==null?void 0:B.trim(),delay_seconds:m.delay_seconds||0,enabled:m.enabled??!0};m.type==="api"?W.api_config={url:((Z=m.api_url)==null?void 0:Z.trim())||"",method:m.api_method,timeout:m.api_timeout||10,headers:((M=m.api_headers)==null?void 0:M.trim())||void 0,params:((b=m.api_params)==null?void 0:b.trim())||void 0}:m.type==="text"?W.text_content=((k=m.text_content)==null?void 0:k.trim())||"":m.type==="data"?W.data_content=((D=m.data_content)==null?void 0:D.trim())||"":m.type==="image"&&(W.image_url=((C=m.image_url)==null?void 0:C.trim())||""),await ta(u.id,W),l(!1),await s()}catch(W){console.error("更新卡密失败:",W),alert("更新失败,请重试")}}},X=async d=>{if(confirm("确认删除该卡密吗?"))try{await Sl(d),await s()}catch(B){console.error("删除卡密失败:",B),alert("删除失败,请重试")}},y=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.api_method,timeout:x.api_timeout,headers:x.api_headers.trim()||void 0,params:x.api_params.trim()||void 0}),await Cl(d),c(!1),h(xa()),await s()}catch(d){console.error("添加卡密失败:",d),alert("添加失败,请重试")}},j=async d=>{try{await ta(d.id,{...d,enabled:!d.enabled}),await s()}catch(B){console.error("切换状态失败:",B)}},z=async d=>{try{await navigator.clipboard.writeText(String(d)),alert(`已复制卡密组ID:${d}`)}catch{prompt("复制卡密组ID",String(d))}},A=r.useMemo(()=>ri(t,_,q),[t,q,_]),F=()=>{const Z=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 VIP-MONTH-002 VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(D=>D.map(C=>`"${String(C).replace(/"/g,'""')}"`).join(",")).join(` -`),M=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),b=URL.createObjectURL(M),k=document.createElement("a");k.href=b,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(b)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:P.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Mt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>c(!0)),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(nt,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(Oa,{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:_,onChange:(d=>S(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(St,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:q,onChange:(d=>w(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",I.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:I.map(d=>{let B="";return d.type==="data"&&d.data_content?B=`库存: ${d.data_content.split(` -`).filter(M=>M.trim()).length} 条`:d.type==="text"&&d.text_content?B=d.text_content:d.type==="api"&&d.api_config?B=d.api_config.url:d.type==="image"&&d.image_url&&(B="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ai,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>z(d.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(jr,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:B,children:B})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>y(d)),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>G(d)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>X(d.id)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ze,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),I.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ka,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&u&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>l(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:m.name||"",onChange:(d=>j({...m,name:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:m.type||"text",onChange:(d=>j({...m,type:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(u==null?void 0:u.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),m.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:m.api_url||"",onChange:(d=>j({...m,api_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:m.api_method||"GET",onChange:(d=>j({...m,api_method:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"超时时间(秒)"}),e.jsx("input",{type:"number",value:m.api_timeout||10,onChange:(d=>j({...m,api_timeout:parseInt(d.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:m.api_headers||"",onChange:(d=>j({...m,api_headers:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"Authorization": "Bearer token"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:m.api_params||"",onChange:(d=>j({...m,api_params:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"type": "card", "count": 1}'})]})]}),m.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:m.text_content||"",onChange:(d=>j({...m,text_content:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),m.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:m.data_content||"",onChange:(d=>j({...m,data_content:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个: +`),M=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),b=URL.createObjectURL(M),k=document.createElement("a");k.href=b,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(b)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:P.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Mt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>c(!0)),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(nt,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(Oa,{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:_,onChange:(d=>S(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(St,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:q,onChange:(d=>w(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",A.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:A.map(d=>{let B="";return d.type==="data"&&d.data_content?B=`库存: ${d.data_content.split(` +`).filter(M=>M.trim()).length} 条`:d.type==="text"&&d.text_content?B=d.text_content:d.type==="api"&&d.api_config?B=d.api_config.url:d.type==="image"&&d.image_url&&(B="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ai,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>z(d.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(jr,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:B,children:B})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>j(d)),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>G(d)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>X(d.id)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ze,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),A.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ka,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&u&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>l(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:m.name||"",onChange:(d=>f({...m,name:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:m.type||"text",onChange:(d=>f({...m,type:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(u==null?void 0:u.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),m.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:m.api_url||"",onChange:(d=>f({...m,api_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:m.api_method||"GET",onChange:(d=>f({...m,api_method:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"超时时间(秒)"}),e.jsx("input",{type:"number",value:m.api_timeout||10,onChange:(d=>f({...m,api_timeout:parseInt(d.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:m.api_headers||"",onChange:(d=>f({...m,api_headers:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"Authorization": "Bearer token"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:m.api_params||"",onChange:(d=>f({...m,api_params:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"type": "card", "count": 1}'})]})]}),m.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:m.text_content||"",onChange:(d=>f({...m,text_content:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),m.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:m.data_content||"",onChange:(d=>f({...m,data_content:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个: 卡号1:密码1 卡号2:密码2 或者 兑换码1 兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:m.data_content?m.data_content.split(` -`).filter(d=>d.trim()).length:0})," 条"]})]})]}),m.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:m.image_url||"",onChange:(d=>j({...m,image_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),m.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:m.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:m.delay_seconds||0,onChange:(d=>j({...m,delay_seconds:parseInt(d.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:m.description||"",onChange:(d=>j({...m,description:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>j({...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.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>l(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:H,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>c(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:x.name,onChange:(d=>p({...x,name:d.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>p({...x,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>p({...x,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ia,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>p({...x,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Aa,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:x.type==="data"?"库存内容(一行一个)":x.type==="text"?"固定回复内容":x.type==="image"?"图片 URL":"API 地址"}),x.type==="api"?e.jsx("input",{type:"url",value:x.content,onChange:(d=>p({...x,content:d.target.value})),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):x.type==="image"?e.jsx("input",{type:"url",value:x.content,onChange:(d=>p({...x,content:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}):e.jsx("textarea",{value:x.content,onChange:(d=>p({...x,content:d.target.value})),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${x.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:x.type==="data"?`CODE-123456 +`).filter(d=>d.trim()).length:0})," 条"]})]})]}),m.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:m.image_url||"",onChange:(d=>f({...m,image_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),m.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:m.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:m.delay_seconds||0,onChange:(d=>f({...m,delay_seconds:parseInt(d.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:m.description||"",onChange:(d=>f({...m,description:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>f({...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.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>l(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:H,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>c(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:x.name,onChange:(d=>h({...x,name:d.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>h({...x,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...x,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Aa,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...x,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ia,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:x.type==="data"?"库存内容(一行一个)":x.type==="text"?"固定回复内容":x.type==="image"?"图片 URL":"API 地址"}),x.type==="api"?e.jsx("input",{type:"url",value:x.content,onChange:(d=>h({...x,content:d.target.value})),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):x.type==="image"?e.jsx("input",{type:"url",value:x.content,onChange:(d=>h({...x,content:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}):e.jsx("textarea",{value:x.content,onChange:(d=>h({...x,content:d.target.value})),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${x.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:x.type==="data"?`CODE-123456 CODE-789012 ...`:"请输入每次发货时发送的固定文字"}),x.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:x.content.split(` -`).filter(d=>d.trim()).length})," 条"]})]}),x.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:x.api_method,onChange:(d=>p({...x,api_method:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:x.api_timeout,onChange:(d=>p({...x,api_timeout:parseInt(d.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:x.api_headers,onChange:(d=>p({...x,api_headers:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:x.api_params,onChange:(d=>p({...x,api_params:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:x.description,onChange:(d=>p({...x,description:d.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:x.delay_seconds,onChange:(d=>p({...x,delay_seconds:parseInt(d.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>c(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(si,{dataCards:O,downloadCardTemplate:F,...P})]})},ma="ydisks-amap-js-api",ci="c9b68d4ce9a2a97f22a4a439404488ca";let Ot=null;const di=()=>ci,xi=()=>window.AMap?Promise.resolve(window.AMap):Ot||(Ot=new Promise((t,s)=>{const a=document.getElementById(ma),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(u)},c=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},u=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=c,l.id=ma,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(di())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw Ot=null,t}),Ot),ts=t=>Number.isFinite(t)&&t!==0,mi=t=>{var n,c;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((c=t.location)==null?void 0:c.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!ts(s)||!ts(a)||s<-180||s>180||a<-90||a>90?null:l},ui=async(t,s)=>{if(!ts(t)||!ts(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await xi();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(u,h)=>{var j;if(u!=="complete"){if(u==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const m=(((j=h==null?void 0:h.poiList)==null?void 0:j.pois)||[]).map(mi).filter(x=>x!==null);l(m)})})},pi=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Rs=t=>t==="running"||t==="canceling",hi=t=>!!(t!=null&&t.preview_id&&Number(t.valid||0)>0),gi=t=>!!(t!=null&&t.id&&Number(t.retryable||0)>0&&!Rs(t.status)),bi=(t,s)=>t===s,ua=t=>{switch(t){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 t||"-"}},pa=t=>{switch(t){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"}},fi=t=>{const[s,a]=r.useState(!1),[l,n]=r.useState("upload"),[c,u]=r.useState(null),[h,m]=r.useState(null),[j,x]=r.useState(""),[p,_]=r.useState(!1),[S,q]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[w,O]=r.useState(null),[P,G]=r.useState(null),[H,X]=r.useState(null),[f,y]=r.useState([]),[z,I]=r.useState(null),[F,d]=r.useState(!1),B=r.useRef(!1),Z=r.useRef(0),M=r.useCallback(async()=>{n("upload"),O(null),G(null),u(null),m(null),x(""),q({catId:"",catName:"",channelCatId:"",tbCatId:""}),y([]),I(null),a(!0),d(!0);try{const U=await za(20),re=pi(U);if(re!=null&&re.id){const ge=await vt(re.id);X(ge),G(ge),n(["running","canceling"].includes(ge.status)?"running":"done")}}catch(U){console.error("恢复最近批量铺货任务失败:",U)}finally{d(!1)}},[]),b=r.useCallback(async()=>{const U=j.trim();if(!t.selectedAccount){alert("请先选择默认发布账号");return}if(!U){alert("请输入类目关键词");return}_(!0);try{const ge=(await Tl(t.selectedAccount,U)).category;q({catId:ge.cat_id,catName:ge.cat_name,channelCatId:ge.channel_cat_id,tbCatId:ge.tb_cat_id||""})}catch(re){console.error("获取推荐类目失败:",re),alert((re==null?void 0:re.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{_(!1)}},[j,t.selectedAccount]),k=r.useCallback(async()=>{if(H!=null&&H.id){d(!0),a(!0);try{const U=await vt(H.id);G(U),n(["running","canceling"].includes(U.status)?"running":"done")}catch(U){console.error("加载最近批量铺货结果失败:",U)}finally{d(!1)}}},[H==null?void 0:H.id]),D=r.useCallback(async()=>{if(!c){alert("请先上传商品表格");return}if(!t.selectedAccount){alert("请先选择默认发布账号");return}d(!0);try{const U=await El({file:c,imagesZip:h,defaultCookieId:t.selectedAccount,fallbackCategory:S,location:z||void 0});O(U),G(null),n("preview")}catch(U){console.error("批量铺货预检失败:",U),alert((U==null?void 0:U.message)||"预检失败,请检查表格和图片 zip")}finally{d(!1)}},[S,c,h,z,t.selectedAccount]),C=r.useCallback(async()=>{if(w!=null&&w.preview_id){if(!hi(w)){alert("没有可发布的商品行");return}d(!0);try{const U=await Dl(w.preview_id),re=await vt(U.batch_id||w.preview_id);G(re),X(re),n(re.status==="running"?"running":"done")}catch(U){console.error("启动批量铺货失败:",U),alert((U==null?void 0:U.message)||"启动发布任务失败")}finally{d(!1)}}},[w]),W=r.useCallback(async()=>{if(P!=null&&P.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){d(!0);try{const U=await Ml(P.id),re=await vt(P.id);G(re),n((U==null?void 0:U.status)==="canceling"||re.status==="canceling"?"running":"done")}catch(U){alert((U==null?void 0:U.message)||"取消失败")}finally{d(!1)}}},[P==null?void 0:P.id]),K=r.useCallback(async()=>{const U=w==null?void 0:w.preview_id;if(U&&l==="preview")try{await $l(U)}catch(re){console.error("清理批量铺货预检失败:",re)}O(null),n("upload")},[l,w==null?void 0:w.preview_id]),N=r.useCallback(async()=>{await K(),a(!1)},[K]),ee=r.useCallback(async()=>{if(!(!(P!=null&&P.id)||!gi(P))){d(!0);try{await ql(P.id),G(await vt(P.id)),n("running")}catch(U){alert((U==null?void 0:U.message)||"重试失败")}finally{d(!1)}}},[P]);return r.useEffect(()=>{if(!s||!(P!=null&&P.id)||!Rs(P.status))return;const U=++Z.current,re=async()=>{if(!B.current){B.current=!0;try{const $=await vt(P.id);if(!bi(U,Z.current))return;G($),X($),Rs($.status)||(n("done"),await Promise.all([t.loadItems(),t.loadShippingRules()]))}catch($){console.error("刷新批量铺货进度失败:",$)}finally{B.current=!1}}},ge=window.setInterval(()=>void re(),3e3);return(()=>{window.clearInterval(ge),Z.current+=1})},[P==null?void 0:P.id,P==null?void 0:P.status,t.loadItems,t.loadShippingRules,s]),{showBatchModal:s,setShowBatchModal:a,batchLoading:F,batchPhase:l,setBatchPhase:n,batchFile:c,setBatchFile:u,batchImagesZip:h,setBatchImagesZip:m,batchCategoryKeyword:j,setBatchCategoryKeyword:x,batchCategoryLoading:p,batchFallbackCategory:S,setBatchFallbackCategory:q,batchPreview:w,setBatchPreview:O,batchDetail:P,setBatchDetail:G,recentBatch:H,setRecentBatch:X,batchLocations:f,batchLocation:z,setBatchLocations:y,setBatchLocation:I,openBatchModal:M,handleRecommendBatchCategory:b,openRecentBatchResult:k,handlePreviewBatch:D,handleStartBatch:C,handleCancelBatch:W,abandonBatchPreview:K,closeBatchModal:N,handleRetryBatchFailed:ee}},yi=({phase:t})=>{const s=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:s.map(([a,l])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${t===a?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:l},a))})},ji=t=>{const s=String(t||"").trim();return s?/^[¥¥]/.test(s)?s:`¥${s}`:"-"},vi=({onConfigureDelivery:t})=>{const[s,a]=r.useState([]),[l,n]=r.useState([]),[c,u]=r.useState([]),[h,m]=r.useState(""),[j,x]=r.useState(""),[p,_]=r.useState(!1),[S,q]=r.useState(!1),[w,O]=r.useState(!1),[P,G]=r.useState(!1),[H,X]=r.useState(!1),[f,y]=r.useState(!1),[z,I]=r.useState([]),[F,d]=r.useState(null),[B,Z]=r.useState(null),[M,b]=r.useState({}),[k,D]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[C,W]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[K,N]=r.useState([]),ee=r.useCallback(async()=>{const o=await Lt();a(o)},[]),be=r.useCallback(async()=>{n(await Ss())},[]),U=fi({selectedAccount:h,loadItems:ee,loadShippingRules:be}),{showBatchModal:re,setShowBatchModal:ge,batchLoading:$,batchPhase:L,batchFile:V,setBatchFile:Y,batchImagesZip:se,setBatchImagesZip:ue,batchCategoryKeyword:ve,setBatchCategoryKeyword:R,batchCategoryLoading:T,batchFallbackCategory:g,setBatchFallbackCategory:le,batchPreview:oe,batchDetail:ne,recentBatch:de,setRecentBatch:Se,batchLocations:Ee,batchLocation:Te,setBatchLocations:Ue,setBatchLocation:Me,openBatchModal:Be,handleRecommendBatchCategory:Je,openRecentBatchResult:He,handlePreviewBatch:we,handleStartBatch:pe,handleCancelBatch:Ke,abandonBatchPreview:it,closeBatchModal:tt,handleRetryBatchFailed:Ve}=U;r.useEffect(()=>{if(!H||C.images.length===0){N([]);return}const o=C.images.map((Q,xe)=>({key:Q.name+xe,url:URL.createObjectURL(Q)}));return N(o),(()=>{o.forEach(Q=>URL.revokeObjectURL(Q.url))})},[H,C.images]),r.useEffect(()=>{Promise.all([Ft(),Lt(),Ss(),za(20)]).then(([o,Q,xe,Le])=>{u(o),a(Q),n(xe);const st=Le.find(Qe=>["running","canceling"].includes(Qe.status))||Le.find(Qe=>Qe.status!=="preview");Se(st||null)}).catch(o=>console.error("加载商品配置失败:",o))},[]);const Ge=async()=>{if(!h)return alert("请先选择账号");_(!0);try{const o=await Al(h);await ee(),alert((o==null?void 0:o.message)||"商品同步完成")}catch(o){console.error("同步商品失败:",o),alert((o==null?void 0:o.message)||"同步失败,请重试")}finally{_(!1)}},ot=o=>{Z(o),b({...o}),O(!0)},pt=async()=>{if(B)try{await Bl(B.cookie_id,B.item_id,{item_title:M.item_title||"",item_description:M.item_description||"",item_category:M.item_category||"",item_price:M.item_price||"",item_detail:M.item_detail||B.item_detail||""}),await ee(),await be(),O(!1),Z(null)}catch(o){console.error("更新商品失败:",o),alert("更新失败,请重试")}},ht=async o=>{if(confirm(`确认删除商品"${o.item_title}"吗?`))try{await Il(o.cookie_id,o.item_id),a(Q=>Q.filter(xe=>!(xe.cookie_id===o.cookie_id&&xe.item_id===o.item_id)))}catch(Q){console.error("删除商品失败:",Q),alert("删除失败,请重试")}},J=async()=>{try{if(!k.cookie_id||!k.item_id){alert("请选择账号并填写商品ID");return}await Ol(k.cookie_id,{item_id:k.item_id,item_title:k.item_title,item_price:k.item_price,item_detail:k.item_image?JSON.stringify({item_image:k.item_image}):""}),await ee(),G(!1),D({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(o){console.error("添加商品失败:",o),alert("添加失败,请重试")}},ie=async()=>{if(!C.cookie_id)return alert("请选择发布账号");if(!C.title.trim())return alert("请填写商品标题");if(!C.price.trim())return alert("请填写商品价格");if(!C.quantity||Number(C.quantity)<=0)return alert("库存数量必须大于 0");if(C.images.length===0)return alert("至少上传 1 张商品图片");if(C.postage_mode==="fixed"&&!C.postage.trim())return alert("请填写一口价邮费");q(!0);try{const o=await Pl({...C,location:F||void 0});if(await ee(),X(!1),W({cookie_id:h||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),I([]),d(null),o!=null&&o.item_id){const Q={id:o.item_id,cookie_id:C.cookie_id,item_id:o.item_id,item_title:o.item_title||C.title,item_price:o.item_price||C.price,item_image:o.item_image};t(Q),alert("商品发布成功,ID: "+o.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(o){console.error("发布商品失败:",o);const Q=o==null?void 0:o.payload;if((Q==null?void 0:Q.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((o==null?void 0:o.message)||"发布失败,请重试")}finally{q(!1)}},v=()=>{const xe=[["账号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(zt=>zt.map(Ut=>`"${String(Ut).replace(/"/g,'""')}"`).join(",")).join(` -`),Le=new Blob(["\uFEFF"+xe],{type:"text/csv;charset=utf-8"}),st=URL.createObjectURL(Le),Qe=document.createElement("a");Qe.href=st,Qe.download="批量铺货模板.csv",document.body.appendChild(Qe),Qe.click(),Qe.remove(),URL.revokeObjectURL(st)},E=()=>{D(o=>({...o,cookie_id:h||o.cookie_id})),G(!0)},ae=()=>{W(o=>({...o,cookie_id:h||o.cookie_id})),X(!0)},ce=async o=>{if(!(o?h:C.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");y(!0),navigator.geolocation.getCurrentPosition(async xe=>{try{const Le=await ui(xe.coords.longitude,xe.coords.latitude);if(!Le.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(Ue(Le),Me(Le[0])):(I(Le),d(Le[0]))}catch(Le){alert((Le==null?void 0:Le.message)||"获取发货地失败")}finally{y(!1)}},xe=>{y(!1),alert(xe.code===xe.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},fe=o=>l.filter(Q=>Q.cookie_id===o.cookie_id&&Q.item_id===o.item_id).length>0?l.filter(Q=>Q.cookie_id===o.cookie_id&&Q.item_id===o.item_id):l.filter(Q=>Q.cookie_id===o.cookie_id&&!Q.item_id),De=r.useMemo(()=>new Map(c.map(o=>[o.id,o])),[c]),Ne=r.useMemo(()=>j?s.filter(o=>o.cookie_id===j):s,[j,s]),Pe=o=>{const Q=De.get(o),xe=(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname);return xe?`${xe} · ${o.slice(0,6)}`:`账号 ${o.slice(0,8)}`},me=o=>{const Q=De.get(o);return(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.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(vr,{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:j,onChange:(o=>x(o.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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(yt,{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:h,onChange:(o=>m(o.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.id))]})]})]}),e.jsxs("button",{onClick:Ge,disabled:p||!h,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(We,{className:`w-4 h-4 ${p?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:E,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(nt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:ae,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(ls,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void Be()),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(Wt,{className:"w-4 h-4"}),de&&["running","canceling"].includes(de.status)?"继续批量任务":"批量铺货"]}),de&&!["running","canceling"].includes(de.status)&&e.jsx("button",{onClick:(()=>void He()),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:[Ne.map(o=>{const Q=fe(o),xe=Q.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:(()=>ot(o)),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(kt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:(()=>ht(o)),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(Ze,{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:[o.item_image?e.jsx("img",{src:o.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(Na,{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:ji(o.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:o.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:me(o.cookie_id),children:[e.jsx(yt,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:me(o.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: ",o.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${xe?"text-emerald-600":"text-amber-600"}`,children:[xe?e.jsx(vs,{className:"w-3 h-3"}):e.jsx(Nr,{className:"w-3 h-3"}),xe?`${Q.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:(()=>t(o)),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${xe?"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(_r,{className:"w-3.5 h-3.5"}),xe?"查看发货规则":"关联发货规则"]}),e.jsx(Ns,{className:"w-3.5 h-3.5"})]})})]},`${o.cookie_id}-${o.item_id}`)}),Ne.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(_a,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),j?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),w&&B&&Oe.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: ",B.item_id]})]}),e.jsx("button",{onClick:(()=>O(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ke,{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:M.item_title||"",onChange:(o=>b({...M,item_title:o.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:M.item_price||"",onChange:(o=>b({...M,item_price:o.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:M.item_category||"",onChange:(o=>b({...M,item_category:o.target.value}))}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:M.item_description||"",onChange:(o=>b({...M,item_description:o.target.value}))})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:pt,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),P&&Oe.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:(()=>G(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(ke,{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:k.cookie_id,onChange:(o=>D({...k,cookie_id:o.target.value})),children:[e.jsx("option",{value:"",children:"选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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:k.item_id,onChange:(o=>D({...k,item_id:o.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:k.item_price,onChange:(o=>D({...k,item_price:o.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:k.item_title,onChange:(o=>D({...k,item_title:o.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:k.item_image,onChange:(o=>D({...k,item_image:o.target.value}))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:J,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(nt,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),H&&Oe.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:(()=>X(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(ke,{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:C.cookie_id,onChange:(o=>{W({...C,cookie_id:o.target.value}),I([]),d(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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:C.title,onChange:(o=>W({...C,title:o.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:C.quantity,onChange:(o=>W({...C,quantity:o.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:C.description,onChange:(o=>W({...C,description:o.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:C.price,onChange:(o=>W({...C,price:o.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:C.original_price,onChange:(o=>W({...C,original_price:o.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:C.postage_mode,onChange:(o=>W({...C,postage_mode:o.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:"无需邮寄"})]})]})]}),C.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:C.postage,onChange:(o=>W({...C,postage:o.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:f||!C.cookie_id,onClick:(()=>void ce(!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(Us,{className:"h-4 w-4"}),f?"定位中...":"获取当前位置"]})]}),z.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,z.indexOf(F))),onChange:(o=>d(z[Number(o.target.value)]||null)),children:z.map((o,Q)=>e.jsx("option",{value:String(Q),children:[o.province,o.city,o.area,o.poi_name].filter(Boolean).join(" ")},`${o.division_id}-${o.poi_id}-${Q}`))})]}),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(Wt,{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:C.images.length?"已选择 "+C.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:(o=>W({...C,images:Array.from(o.target.files||[]).slice(0,9)}))})]}),K.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:K.map(o=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:o.url,alt:"",className:"w-full h-full object-cover"})},o.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:S,onClick:ie,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(ls,{className:"w-4 h-4"}),S?"正在发布...":"发布到闲鱼"]})})]})}),document.body),re&&Oe.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 tt()),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx(yi,{phase:L}),L==="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:v,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:h,onChange:(o=>{m(o.target.value),Ue([]),Me(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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(St,{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:ve,onChange:(o=>R(o.target.value)),onKeyDown:(o=>{o.key==="Enter"&&(o.preventDefault(),Je())})})]}),e.jsxs("button",{type:"button",disabled:!h||!ve.trim()||T,onClick:(()=>void Je()),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(St,{className:"h-4 w-4"}),T?"匹配中...":"获取类目"]})]}),g.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(vs,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:g.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",g.catId," · 频道 ",g.channelCatId]})]}),e.jsx("button",{type:"button",title:"清除默认类目",onClick:(()=>le({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(ke,{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:f||!h,onClick:(()=>void ce(!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(Us,{className:"h-4 w-4"}),f?"定位中...":"获取当前位置"]})]}),Ee.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,Ee.indexOf(Te))),onChange:(o=>Me(Ee[Number(o.target.value)]||null)),children:Ee.map((o,Q)=>e.jsx("option",{value:String(Q),children:[o.province,o.city,o.area,o.poi_name].filter(Boolean).join(" ")},`${o.division_id}-${o.poi_id}-${Q}`))})]}),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(Wt,{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:V?V.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:(o=>{var Q;return Y(((Q=o.target.files)==null?void 0:Q[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(Wt,{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:se?se.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:(o=>{var Q;return ue(((Q=o.target.files)==null?void 0:Q[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(([o,Q,xe])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:o}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${Q==="每个商品都要填"?"text-red-600":Q==="可以留空"?"text-gray-500":"text-amber-700"}`,children:Q}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:xe})]},o))})]})})]})]}),L==="preview"&&oe&&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:oe.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:oe.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:oe.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:oe.rows.map(o=>{var Q,xe,Le,st;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:o.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 ${o.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:o.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:o.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",o.price||"-"," / ",o.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:((Q=o.category)==null?void 0:Q.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((xe=o.category)==null?void 0:xe.cat_id)||"失败后使用电子资料"})]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((Le=o.images)==null?void 0:Le.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((st=o.errors)==null?void 0:st.join(";"))||"-"})]},o.row_no)})})]})})]}),(L==="running"||L==="done")&&ne&&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 ${pa(ne.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:ua(ne.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:ne.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:ne.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:ne.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:ne.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:ne.rows.map(o=>{var Q,xe;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:o.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 ${pa(o.status)}`,children:ua(o.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:o.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:((Q=o.category)==null?void 0:Q.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((xe=o.category)==null?void 0:xe.cat_id)||"失败后使用电子资料"})]}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:o.item_url?e.jsx("a",{href:o.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:o.item_id}):o.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:o.error_message||"-"})]},o.id)})})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[L==="upload"&&e.jsxs("button",{disabled:$||!V||!h,onClick:we,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(We,{className:`w-4 h-4 ${$?"animate-spin":""}`}),$?"正在预检...":"开始预检"]}),L==="preview"&&oe&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:$,onClick:(()=>void it()),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:$||oe.valid<=0,onClick:pe,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(ls,{className:"w-4 h-4"}),$?"启动中...":`确认发布 ${oe.valid} 个商品`]})]}),(L==="running"||L==="done")&&ne&&e.jsxs("div",{className:"flex gap-3 w-full",children:[ne.status==="running"?e.jsx("button",{disabled:$,onClick:Ke,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):ne.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/${ne.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:"下载结果"}),ne.retryable>0&&!["running","canceling"].includes(ne.status)&&e.jsxs("button",{disabled:$,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(We,{className:`w-4 h-4 ${$?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(ne.status)&&e.jsx("button",{onClick:(()=>{ge(!1),ee(),be()}),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)]})},Ha="https://dashscope.aliyuncs.com/compatible-mode/v1",Ni=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],_i=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"]),wi=t=>Object.fromEntries(Object.entries(t).filter(([s,a])=>!_i.has(s)&&a!==void 0&&a!==null)),ki=t=>t.new_username.trim().length<3?"用户名至少需要 3 个字符":t.current_password?t.new_password&&t.new_password.length<8?"新密码至少需要 8 个字符":t.new_password!==t.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",rt=(t,s,a)=>t===s&&!a.aborted,Gt=t=>t instanceof Error&&t.message==="请求已取消",Kt=(t,s)=>t instanceof Error?t.message:s,Ci=(t="")=>({new_username:t,current_password:"",new_password:"",confirm_password:""}),Vt=(t,s)=>({type:t,text:s}),Si=()=>{const[t,s]=r.useState(null),[a,l]=r.useState(!1),[n,c]=r.useState(""),[u,h]=r.useState(!1),[m,j]=r.useState(""),[x,p]=r.useState([]),[_,S]=r.useState(!1),[q,w]=r.useState(""),[O,P]=r.useState(!1),[G,H]=r.useState(!1),[X,f]=r.useState(!1),[y,z]=r.useState(!1),[I,F]=r.useState(!1),[d,B]=r.useState(!1),[Z,M]=r.useState(null),[b,k]=r.useState(()=>Ci()),[D,C]=r.useState("idle"),W=r.useRef(null),K=r.useRef(null),N=r.useRef(0),ee=r.useRef(null);K.current=t;const be=r.useCallback(()=>{var V;(V=ee.current)==null||V.abort();const L=new AbortController;return ee.current=L,N.current+=1,{controller:L,sequence:N.current}},[]),U=r.useCallback(async(L,V=!1,Y)=>{const se=L||K.current,ue=(se==null?void 0:se.ai_api_url)||(se==null?void 0:se.ai_base_url)||Ha;S(!0),w("");try{const ve=await sn(ue,(se==null?void 0:se.ai_api_key)||"",{signal:Y});if(Y!=null&&Y.aborted)return;p(ve),P(V&&ve.length>0),!(se!=null&&se.ai_model)&&ve.length>0&&s(R=>R&&{...R,ai_model:ve[0]})}catch(ve){if(Y!=null&&Y.aborted||Gt(ve))return;p([]),P(!1),w(Kt(ve,"读取模型失败"))}finally{Y!=null&&Y.aborted||S(!1)}},[]),re=r.useCallback(()=>{const{controller:L,sequence:V}=be();l(!0),C("loading"),c(""),Promise.all([Wa({signal:L.signal}),qa({signal:L.signal})]).then(([Y,se])=>{rt(N.current,V,L.signal)&&(s(Y),se.username&&k(ue=>({...ue,new_username:se.username||""})),U(Y,!1,L.signal),C("success"))}).catch(Y=>{!rt(N.current,V,L.signal)||Gt(Y)||(s(null),c(Kt(Y,"加载配置失败")),C("error"))}).finally(()=>{rt(N.current,V,L.signal)&&l(!1)})},[be,U]);r.useEffect(()=>(re(),(()=>{var L;return(L=ee.current)==null?void 0:L.abort()})),[re]),r.useEffect(()=>{const L=V=>{var Y;(Y=W.current)!=null&&Y.contains(V.target)||P(!1)};return document.addEventListener("mousedown",L),(()=>document.removeEventListener("mousedown",L))},[]);const ge=r.useCallback(async()=>{if(!t||u)return;const{controller:L,sequence:V}=be();h(!0),j("");try{if(await Ja(wi(t),{signal:L.signal}),!rt(N.current,V,L.signal))return;window.alert("系统配置已保存")}catch(Y){if(!rt(N.current,V,L.signal)||Gt(Y))return;j(Kt(Y,"保存配置失败"))}finally{rt(N.current,V,L.signal)&&h(!1)}},[be,u,t]),$=r.useCallback(async L=>{L.preventDefault(),M(null);const V=ki(b);if(V){M(Vt("error",V));return}const{controller:Y,sequence:se}=be();B(!0);try{const ue=await Zr({current_password:b.current_password,new_username:b.new_username.trim(),new_password:b.new_password||void 0},{signal:Y.signal});if(!rt(N.current,se,Y.signal))return;if(!ue.success){M(Vt("error",ue.message||"登录凭据更新失败"));return}M(Vt("success",ue.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(ue){if(!rt(N.current,se,Y.signal)||Gt(ue))return;M(Vt("error",Kt(ue,"登录凭据更新失败")))}finally{rt(N.current,se,Y.signal)&&B(!1)}},[be,b]);return{settings:t,loading:a,loadError:n,saving:u,saveError:m,aiModels:x,modelsLoading:_,modelError:q,modelDropdownOpen:O,showApiKey:G,showCaptchaSecret:X,showCurrentPassword:y,showNewPassword:I,credentialsSaving:d,credentialsMessage:Z,credentials:b,requestStatus:D,modelPickerRef:W,loadSettings:re,loadAIModels:((L,V)=>void U(L,V)),handleSave:ge,handleCredentialsSave:$,setSettings:s,setModelDropdownOpen:P,setShowApiKey:H,setShowCaptchaSecret:f,setShowCurrentPassword:z,setShowNewPassword:F,setCredentials:k,setCredentialsMessage:M}},Li=()=>{const{settings:t,loading:s,loadError:a,saving:l,saveError:n,aiModels:c,modelsLoading:u,modelError:h,modelDropdownOpen:m,showApiKey:j,showCaptchaSecret:x,showCurrentPassword:p,showNewPassword:_,credentialsSaving:S,credentialsMessage:q,credentials:w,modelPickerRef:O,loadSettings:P,loadAIModels:G,handleSave:H,handleCredentialsSave:X,setSettings:f,setModelDropdownOpen:y,setShowApiKey:z,setShowCaptchaSecret:I,setShowCurrentPassword:F,setShowNewPassword:d,setCredentials:B}=Si();if(!t)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[a||(s?"加载配置中...":"暂无配置"),!s&&a&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:P,children:"重新加载"})})]});const Z=t.ai_model||"",M=c;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(Ps,{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:P,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(We,{className:"w-4 h-4"}),"刷新"]})]}),n&&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:n}),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(wr,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:t.log_level||"info",onChange:(b=>f({...t,log_level:b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:Ni.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:t.log_format||"text",onChange:(b=>f({...t,log_format:b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:t.renewal_log_retention_days??10,onChange:(b=>f({...t,renewal_log_retention_days:parseInt(b.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-brand text-white",children:e.jsx(Ds,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:t.ai_api_url||Ha,onChange:(b=>f({...t,ai_api_url:b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:j?"text":"password",value:t.ai_api_key||"",onChange:(b=>f({...t,ai_api_key:b.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:t.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>z(!j)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:j?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:O,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:Z,onFocus:(()=>c.length>0&&y(!0)),onChange:(b=>{f({...t,ai_model:b.target.value}),c.length>0&&y(!0)}),onKeyDown:(b=>{b.key==="Escape"&&y(!1),b.key==="ArrowDown"&&c.length>0&&y(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>c.length>0&&y(b=>!b)),disabled:c.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(kr,{className:`w-4 h-4 transition-transform ${m?"rotate-180":""}`})}),m&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:M.length>0?M.map(b=>e.jsxs("button",{type:"button",onClick:(()=>{f({...t,ai_model:b}),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:b}),b===Z&&e.jsx(Ye,{className:"w-4 h-4 shrink-0 text-brand"})]},b)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>G(void 0,!0)),disabled:u,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(We,{className:`w-4 h-4 ${u?"animate-spin":""}`}),"读取模型"]})]}),h?e.jsx("p",{className:"text-xs text-red-500",children:h}):e.jsx("p",{className:"text-xs text-gray-500",children:c.length>0?`已从当前 API 地址读取到 ${c.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(qt,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:t["captcha.remote_service_url"]||"",onChange:(b=>f({...t,"captcha.remote_service_url":b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:x?"text":"password",value:t["captcha.remote_secret_key"]||"",onChange:(b=>f({...t,"captcha.remote_secret_key":b.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:t["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>I(!x)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:x?"隐藏秘钥":"显示秘钥",children:x?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(t["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(b=>f({...t,"captcha.remote_pass_cookies":b.target.checked})),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(Ws,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:X,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(Zt,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:w.new_username,onChange:(b=>B({...w,new_username:b.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:p?"text":"password",value:w.current_password,onChange:(b=>B({...w,current_password:b.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:(()=>F(!p)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:p?"隐藏密码":"显示密码",children:p?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:_?"text":"password",value:w.new_password,onChange:(b=>B({...w,new_password:b.target.value})),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:(()=>d(!_)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:_?"隐藏密码":"显示密码",children:_?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:_?"text":"password",value:w.confirm_password,onChange:(b=>B({...w,confirm_password:b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),q&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${q.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(qt,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:q.text})]}),e.jsxs("button",{type:"submit",disabled:S||!w.new_username||!w.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(Ws,{className:"w-4 h-4"}),S?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:H,disabled:l,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(lt,{className:"w-6 h-6"}),l?"保存中...":"保存所有配置"]})})]})},us=(t,s)=>t.allowed_resolutions.includes(s),Ri=(t,s)=>({runs:t.runs.filter(a=>!s||a.cookie_id===s),pending_tasks:t.pending_tasks.filter(a=>!s||a.cookie_id===s)}),Ai=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",Ii=({runs:t,pendingTasks:s,onResolveRun:a,onResolveDeferredTask:l})=>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(ut,{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:[t.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:Ai(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:[us(n,"continue")&&e.jsx("button",{onClick:(()=>a(n.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),us(n,"retry")&&e.jsx("button",{onClick:(()=>a(n.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),us(n,"cancel")&&e.jsx("button",{onClick:(()=>a(n.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${n.id}`)),s.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:(()=>l(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:(()=>l(n.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${n.id}`))]})]}),ps=()=>({submitting:!1,result:"idle"}),hs=t=>t.submitting?t:{submitting:!0,result:"idle"},gs=(t,s)=>({submitting:!1,result:s?"success":"failure"}),ha=t=>t+1,bs=(t,s,a,l)=>t===s&&a===l,Oi=t=>{const[s,a]=r.useState([]),[l,n]=r.useState({runs:[],pending_tasks:[]}),[c,u]=r.useState([]),[h,m]=r.useState({}),[j,x]=r.useState([]),[p,_]=r.useState([]),[S,q]=r.useState([]),[w,O]=r.useState(!1),P=r.useRef(0),G=r.useRef(0),[H,X]=r.useState(0),[f,y]=r.useState(0),[z,I]=r.useState({}),F=r.useCallback(async()=>{const k=Promise.all([Ft(),Ms(),Lt(),ra()]),[D,C,W,K]=await k;x(D),_(C),q(W),m(K),t.setSelectedAccountId(N=>{var ee;return N||((ee=D[0])==null?void 0:ee.id)||""})},[t.setSelectedAccountId]),d=r.useCallback(async()=>{var K;const k=ha(P.current);P.current=k;const D=Wl().catch(N=>(console.warn("加载自动化异常列表失败,不阻断规则展示",N),null)),C=await Fl({cookieId:t.selectedAccountId||void 0,triggerType:t.automationTriggerFilter,enabled:t.automationStatusFilter==="all"?void 0:t.automationStatusFilter==="enabled",search:t.debouncedAutomationSearch,page:t.automationPage,pageSize:t.automationPageSize});if(!bs(k,P.current,t.selectedAccountId,t.selectedAccountId))return;a(C.data),X(C.total),y(C.total_pages),I(C.trigger_counts||{}),C.page!==t.automationPage&&((K=t.onAutomationPageChange)==null||K.call(t,C.page));const W=await D;bs(k,P.current,t.selectedAccountId,t.selectedAccountId)&&W&&n(W)},[t.automationPage,t.automationPageSize,t.automationStatusFilter,t.automationTriggerFilter,t.debouncedAutomationSearch,t.onAutomationPageChange,t.selectedAccountId]),B=r.useCallback(async()=>{const k=ha(G.current);G.current=k;const D=t.selectedAccountId;if(u([]),!D)return;const C=await Ql(D);bs(k,G.current,D,t.selectedAccountId)&&u(C)},[t.selectedAccountId]),Z=r.useCallback(async()=>{m(await ra())},[]),M=r.useCallback(async()=>{O(!0);try{t.activeTab==="automation"?await d():t.activeTab==="reply"?await B():await Z()}finally{O(!1)}},[d,Z,B,t.activeTab]);return{automationRules:s,automationIssues:l,replyRules:c,defaultReplies:h,accounts:j,cards:p,items:S,automationTotal:H,automationTotalPages:f,automationTriggerCounts:z,loading:w,setLoading:O,setAutomationRules:a,setCards:_,setItems:q,loadReferenceData:F,loadAutomationRules:d,loadReplyRules:B,loadDefaultReplies:Z,refresh:M}},xt={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:Bt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:Cr},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:Pa}},Qt=["order_paid","buyer_reviewed","review_missing_timeout"],Pi="亲,商品使用满意的话,麻烦给个评价,谢谢~",Pt=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),Za=t=>{if(!t)return{};try{const s=JSON.parse(t);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}},gt=(t,s={})=>{const a=Za(t);return JSON.stringify({after_shipped_hours:Number(a.after_shipped_hours||72),repeat_interval_hours:Number(a.repeat_interval_hours||24),max_attempts:Number(a.max_attempts||1),...s})},Tt=(t,s)=>{var l;const a=((l=xt[t])==null?void 0:l.label)||"自动化规则";return s?`${a} - ${s}`:a},ga=t=>{const s=(t||"").trim();return s?Object.values(xt).some(a=>s===a.label||s.startsWith(`${a.label} -`)):!0},Et=(t,s=0)=>{if(t==="review_missing_timeout")return[{action_type:"send_text",message_template:Pi,enabled:!0,sort_order:1}];const a={action_type:"send_card",card_id:s,delivery_count:1,enabled:!0,sort_order:1};return t==="order_paid"?[a,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[a]},Ti=t=>{var a,l;if(t.trigger_type==="review_missing_timeout")return((l=(a=t.actions)==null?void 0:a.find(n=>n.action_type==="send_text"))==null?void 0:l.message_template)||"发送求评价文案";const s=(t.actions||[]).filter(n=>n.action_type==="send_card");return s.length?s.map(n=>n.card_name||`卡密 ${n.card_id}`).join(" / "):"未配置卡密库存"},ba=(t,s=!1)=>{const a={blue:s?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:s?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:s?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return a[t]||a.blue},Ei=t=>t?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Ht=t=>(t==null?void 0:t.nickname)||(t==null?void 0:t.remark)||(t==null?void 0:t.id)||"未知账号",Di=t=>t===!0||t===1||t==="1",$i=({initialDeliveryTarget:t,onDeliveryTargetHandled:s})=>{var Qe,zt,Ut;const[a,l]=r.useState("automation"),[n,c]=r.useState(""),[u,h]=r.useState(""),[m,j]=r.useState(""),[x,p]=r.useState(""),[_,S]=r.useState("all"),[q,w]=r.useState(1),[O,P]=r.useState(10),G=Oi({activeTab:a,selectedAccountId:n,automationTriggerFilter:x,automationStatusFilter:_,debouncedAutomationSearch:m,automationPage:q,automationPageSize:O,setSelectedAccountId:c,onAutomationPageChange:w}),{automationRules:H,automationIssues:X,replyRules:f,defaultReplies:y,accounts:z,cards:I,items:F,loading:d,setLoading:B,automationTotal:Z,automationTotalPages:M,automationTriggerCounts:b,setAutomationRules:k,setCards:D,setItems:C,loadReferenceData:W,loadAutomationRules:K,loadReplyRules:N,loadDefaultReplies:ee,refresh:be}=G,[U,re]=r.useState(!1),[ge,$]=r.useState(!1),[L,V]=r.useState(!1),[Y,se]=r.useState(ps),[ue,ve]=r.useState(ps),[R,T]=r.useState(ps),[g,le]=r.useState(null),[oe,ne]=r.useState(null),[de,Se]=r.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""});z.find(i=>i.id===n),r.useEffect(()=>{const i=window.setTimeout(()=>{w(1),j(u.trim())},300);return(()=>window.clearTimeout(i))},[u]),r.useEffect(()=>{W().catch(i=>console.error("加载规则参考数据失败",i))},[W]),r.useEffect(()=>{be().catch(i=>console.error("刷新规则页面失败",i))},[be]);const Ee=r.useMemo(()=>H.filter(i=>!n||i.cookie_id===n),[H,n]),Te=r.useMemo(()=>Ri(X,n),[X,n]),Ue=r.useMemo(()=>z.filter(i=>!n||i.id===n),[z,n]),Me=r.useMemo(()=>{if(M<=1)return[];const i=Math.max(1,Math.min(q-2,M-4)),A=Math.min(M,i+4);return Array.from({length:A-i+1},(te,he)=>i+he)},[q,M]),Be=!!(u.trim()||x||_!=="all"),Je=()=>{h(""),j(""),p(""),S("all"),w(1)},He=r.useMemo(()=>{const i=(g==null?void 0:g.cookie_id)||n;return F.filter(A=>A.cookie_id===i)},[g==null?void 0:g.cookie_id,F,n]),we=r.useMemo(()=>{if(!(!(g!=null&&g.cookie_id)||!(g!=null&&g.item_id)))return F.find(i=>i.cookie_id===g.cookie_id&&i.item_id===g.item_id)},[g==null?void 0:g.cookie_id,g==null?void 0:g.item_id,F]),pe=Di(we==null?void 0:we.is_multi_spec),Ke=(g==null?void 0:g.trigger_type)||"order_paid",it=xt[Ke],tt=Za(g==null?void 0:g.config_json),Ve=r.useCallback((i="order_paid",A=n,te="")=>{const he=F.find($e=>$e.cookie_id===A&&$e.item_id===te),Ae=(he==null?void 0:he.item_title)||te;return{name:Tt(i,Ae),trigger_type:i,cookie_id:A,item_id:te,item_title:(he==null?void 0:he.item_title)||"",item_keyword:Ae,card_group_id:0,priority:100,enabled:!0,config_json:i==="review_missing_timeout"?gt():"{}",actions:Et(i),variants:i==="review_missing_timeout"?[]:[Pt()]}},[F,n]),Ge=r.useCallback(i=>{var te,he;const A=i.trigger_type||"order_paid";le({...i,trigger_type:A,config_json:A==="review_missing_timeout"?gt(i.config_json):i.config_json||"{}",actions:(te=i.actions)!=null&&te.length?i.actions.map(Ae=>({...Ae})):Et(A,i.card_group_id),variants:(he=i.variants)!=null&&he.length?i.variants.map(Ae=>({...Ae})):A==="review_missing_timeout"?[]:[Pt()]}),re(!0)},[]);r.useEffect(()=>{if(!t)return;let i=!1;return(async()=>{l("automation"),c(t.cookieId),B(!0);try{const[te,he,Ae]=await Promise.all([Ss(),Lt(),Ms().catch(Re=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",Re),[]))]);if(i)return;k(te),C(he),D(Ae);const $e=te.find(Re=>Re.cookie_id===t.cookieId&&Re.item_id===t.itemId&&Re.trigger_type==="order_paid");if($e)Ge($e);else{const Re=he.find(ct=>ct.cookie_id===t.cookieId&&ct.item_id===t.itemId);le({...Ve("order_paid",t.cookieId,t.itemId),item_title:(Re==null?void 0:Re.item_title)||"",item_keyword:(Re==null?void 0:Re.item_title)||t.itemId,name:Tt("order_paid",(Re==null?void 0:Re.item_title)||t.itemId)}),re(!0)}}catch(te){console.error("打开商品自动化规则失败",te),alert("无法加载该商品的自动化规则")}finally{i||(B(!1),s==null||s())}})(),(()=>{i=!0})},[Ve,t,s,Ge]);const ot=(i="order_paid")=>{if(!n){alert("请先选择账号");return}le(Ve(i)),re(!0)},pt=i=>{var he,Ae,$e,Re,ct;if(!g)return;const A=((Ae=(he=g.variants)==null?void 0:he.find(jt=>jt.card_id))==null?void 0:Ae.card_id)||((Re=($e=g.actions)==null?void 0:$e.find(jt=>jt.action_type==="send_card"))==null?void 0:Re.card_id)||g.card_group_id||0,te=(we==null?void 0:we.item_title)||g.item_title||g.item_id||"";le({...g,trigger_type:i,name:ga(g.name)?Tt(i,te):g.name,card_group_id:A,config_json:i==="review_missing_timeout"?gt(g.config_json):"{}",actions:Et(i,A),variants:i==="review_missing_timeout"?[]:(ct=g.variants)!=null&&ct.length?g.variants:[{...Pt(),card_id:A}]})},ht=i=>{if(!g)return;const A=F.find(he=>he.cookie_id===(g.cookie_id||n)&&he.item_id===i),te=(A==null?void 0:A.item_title)||i;le({...g,item_id:i,item_title:(A==null?void 0:A.item_title)||"",item_keyword:te,name:ga(g.name)?Tt(Ke,te):g.name})},J=(Qe=g==null?void 0:g.variants)!=null&&Qe.length?g.variants:[Pt()],ie=(i,A)=>{var he;if(!g)return;const te=J.map((Ae,$e)=>$e===i?{...Ae,...A}:Ae);le({...g,variants:te,card_group_id:((he=te[0])==null?void 0:he.card_id)||0})},v=()=>{if(!g)return;const i=J[J.length-1];le({...g,variants:[...J,{...Pt(),spec_name:pe&&(i==null?void 0:i.spec_name)||"",spec_value:pe&&(i==null?void 0:i.spec_value)||""}]})},E=async()=>{var Ae,$e,Re,ct,jt;if(!g||Y.submitting)return;const i=g.trigger_type||"order_paid";if(!g.cookie_id){alert("请选择账号");return}const A=(Ae=g.variants)!=null&&Ae.length?g.variants:[];if(i!=="review_missing_timeout"){if(!A.length||A.some(qe=>!qe.card_id)){alert(i==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");return}if(pe&&A.some(qe=>!qe.spec_name.trim()||!qe.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}}if(i==="review_missing_timeout"&&!(((Re=($e=g.actions)==null?void 0:$e.find(nr=>nr.action_type==="send_text"))==null?void 0:Re.message_template)||"").trim()){alert("请填写求评价文案");return}const te=i==="review_missing_timeout"?[]:A.map(qe=>({...qe,spec_name:pe?qe.spec_name.trim():"",spec_value:pe?qe.spec_value.trim():"",delivery_count:Math.max(1,Number(qe.delivery_count)||1),enabled:qe.enabled!==!1}));se(hs(Y));let he=!1;try{await sa({...g,trigger_type:i,name:(g.name||"").trim()||Tt(i,(we==null?void 0:we.item_title)||g.item_id||""),config_json:i==="review_missing_timeout"?gt(g.config_json):g.config_json||"{}",actions:(ct=g.actions)!=null&&ct.length?g.actions:Et(i,((jt=te[0])==null?void 0:jt.card_id)||g.card_group_id||0),variants:te}),re(!1),await Promise.all([K(),W()]),alert("保存成功"),he=!0}catch(qe){console.error("保存自动化规则失败:",qe),alert("保存失败:"+qe.message)}finally{se(qe=>gs(qe,he))}},ae=async i=>{if(confirm("确定删除该自动化规则吗?"))try{await Ul(i),await K(),alert("删除成功")}catch(A){alert("删除失败:"+A.message)}},ce=async i=>{try{await sa({...i,enabled:!i.enabled}),await K()}catch(A){alert("操作失败:"+A.message)}},fe=async(i,A)=>{if(confirm(A==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":A==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Jl(i,A),await K()}catch(he){alert("处理失败:"+he.message)}},De=async(i,A)=>{if(confirm(A==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Gl(i,A),await K()}catch(te){alert("处理失败:"+te.message)}},Ne=()=>{if(!n){alert("请先选择账号");return}ne({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),$(!0)},Pe=async()=>{var te,he,Ae;if(!oe||!n||ue.submitting)return;const i=oe.type==="image"?!!((te=oe.image_url)!=null&&te.trim()):!!((he=oe.reply_content)!=null&&he.trim());if(!((Ae=oe.keyword)!=null&&Ae.trim())||!i){alert("请填写关键词和回复内容");return}ve(hs(ue));let A=!1;try{await Hl({...oe,match_type:"fuzzy",enabled:!0},n),$(!1),await N(),alert("保存成功"),A=!0}catch($e){alert("保存失败:"+$e.message)}finally{ve($e=>gs($e,A))}},me=async i=>{if(!(!n||!confirm("确定删除该回复规则吗?")))try{await Zl(i,n),await N(),alert("删除成功")}catch(A){alert("删除失败:"+A.message)}},o=async(i=n)=>{if(!i){alert("请先选择账号");return}try{const A=await cn(i);Se({cookie_id:i,enabled:A.enabled,reply_content:A.reply_content,reply_once:A.reply_once,reply_image_url:A.reply_image_url||""})}catch{Se({cookie_id:i,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}V(!0)},Q=async()=>{if(R.submitting)return;if(!de.cookie_id){alert("请先选择账号");return}if(de.enabled&&!de.reply_content.trim()&&!de.reply_image_url.trim()){alert("启用默认回复时,请填写回复内容或图片 URL");return}T(hs(R));let i=!1;try{await dn(de.cookie_id,{enabled:de.enabled,reply_content:de.reply_content,reply_once:de.reply_once,reply_image_url:de.reply_image_url}),V(!1),await ee(),alert("保存成功"),i=!0}catch(A){alert("保存失败:"+A.message)}finally{T(A=>gs(A,i))}},xe=async i=>{if(confirm("确定删除该账号默认回复吗?"))try{await xn(i),await ee(),alert("删除成功")}catch(A){alert("删除失败:"+A.message)}},Le=async i=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await mn(i),alert("清空成功")}catch(A){alert("清空失败:"+A.message)}},st=a==="automation"?"新建自动化":a==="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:(i=>{c(i.target.value),w(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),z.map(i=>e.jsx("option",{value:i.id,children:Ht(i)},i.id))]}),e.jsxs("button",{onClick:be,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(We,{className:`w-4 h-4 ${d?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:a==="automation"?(()=>ot("order_paid")):a==="reply"?Ne:(()=>void o()),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(nt,{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:js},{id:"reply",label:"关键词回复",icon:$t},{id:"default",label:"账号默认回复",icon:wt}].map(i=>{const A=i.icon;return e.jsxs("button",{onClick:(()=>l(i.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${a===i.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(A,{className:"w-4 h-4"}),i.label]},i.id)})}),a==="automation"&&(Te.runs.length>0||Te.pending_tasks.length>0)&&e.jsx(Ii,{runs:Te.runs,pendingTasks:Te.pending_tasks,onResolveRun:((i,A)=>void fe(i,A)),onResolveDeferredTask:((i,A)=>void De(i,A))}),a==="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:Qt.map(i=>{const A=xt[i],te=A.icon;return e.jsx("button",{type:"button",onClick:(()=>ot(i)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${ba(A.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(te,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:A.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:A.description})]})]})},i)})})]}),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:["共 ",Z," 条"]})]}),e.jsx("div",{className:"space-y-3",children:Qt.map(i=>{const A=xt[i],te=A.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(te,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:A.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:b[i]||0})]},i)})})]})]}),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(St,{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:u,onChange:(i=>{h(i.target.value),w(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(Oa,{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:(i=>{p(i.target.value),w(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:"全部自动化类型"}),Qt.map(i=>e.jsx("option",{value:i,children:xt[i].shortLabel},i))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:_,onChange:(i=>{S(i.target.value),w(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:"已禁用"})]}),Be&&e.jsx("button",{type:"button",onClick:Je,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(ke,{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:["找到 ",Z," 条规则"]}),d&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(We,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),d&&Ee.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(We,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):Ee.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(js,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:Be?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:Be?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):Ee.map(i=>{const A=xt[i.trigger_type],te=A.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 ${ba(A.accent,!0)}`,children:e.jsx(te,{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:i.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Ei(i.enabled)}`,children:i.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:A.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:i.item_title||i.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:Ti(i)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>Ge(i)),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(kt,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>ce(i)),className:`px-4 py-2 rounded-xl text-sm font-bold ${i.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:i.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>ae(i.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ze,{className:"w-4 h-4"})})]})]})},i.id)}),Z>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:["第 ",q," / ",Math.max(M,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:(i=>{P(Number(i.target.value)),w(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(i=>e.jsxs("option",{value:i,children:[i," 条/页"]},i))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:q<=1||d,onClick:(()=>w(i=>Math.max(1,i-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(Es,{className:"h-4 w-4"})}),Me.map(i=>e.jsx("button",{type:"button",disabled:d,onClick:(()=>w(i)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${i===q?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${i} 页`,"aria-current":i===q?"page":void 0,children:i},i)),e.jsx("button",{type:"button",disabled:q>=M||d,onClick:(()=>w(i=>Math.min(M,i+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(Ts,{className:"h-4 w-4"})})]})]})]})]}),a==="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(ut,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[f.map(i=>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:["“",i.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:i.type==="image"&&i.image_url?i.image_url:i.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:(()=>{ne({...i}),$(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>me(i.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ze,{className:"w-5 h-5"})})]})]},i.id)),f.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),a==="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(ut,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Ue.map(i=>{const A=y[i.id],te=!!(A!=null&&A.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 ${te?"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 ${te?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(wt,{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:Ht(i)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${te?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:te?"已启用":"未启用"}),(A==null?void 0:A.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:te?A.reply_content||A.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 o(i.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),te&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void Le(i.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 xe(i.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ze,{className:"w-5 h-5"})})]})]})]},i.id)}),Ue.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),U&&g&&Oe.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:g.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:it.description})]}),e.jsx("button",{onClick:(()=>re(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(ke,{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:Qt.map(i=>{const A=xt[i],te=A.icon,he=Ke===i;return e.jsx("button",{type:"button",onClick:(()=>pt(i)),className:`w-full rounded-2xl p-4 text-left border transition-all ${he?"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(te,{className:`w-5 h-5 mt-0.5 ${he?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:A.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${he?"text-gray-500":"text-gray-400"}`,children:A.description})]})]})},i)})}),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:it.flow.map((i,A)=>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:A+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:i})]},i))})]})]}),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(vs,{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:g.name||"",onChange:(i=>le({...g,name:i.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:g.cookie_id||"",onChange:(i=>le({...g,cookie_id:i.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:"选择账号"}),z.map(i=>e.jsx("option",{value:i.id,children:Ht(i)},i.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:g.item_id||"",onChange:(i=>ht(i.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),He.map(i=>e.jsx("option",{value:i.item_id,children:i.item_title||i.item_id},`${i.cookie_id}-${i.item_id}`))]})]})]}),we&&Ke!=="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:we.item_title||we.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${pe?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:pe?"多规格商品":"普通商品"}),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:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),Ke!=="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(Sr,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:Ke==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:pe?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:v,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(nt,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:J.map((i,A)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${pe?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[pe&&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:i.spec_name,onChange:(te=>ie(A,{spec_name:te.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:i.spec_value,onChange:(te=>ie(A,{spec_value:te.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:i.card_id||"",onChange:(te=>ie(A,{card_id:Number(te.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),I.filter(te=>te.enabled&&te.type!=="api").map(te=>e.jsx("option",{value:te.id,children:te.name},te.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:i.delivery_count,onChange:(te=>ie(A,{delivery_count:Math.max(1,Number(te.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:i.delay_override===!0,onChange:(te=>ie(A,{delay_override:te.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),i.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:i.delay_seconds||0,onChange:(te=>ie(A,{delay_seconds:Math.max(0,Number(te.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:i.delay_override?`本动作延时 ${i.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:J.length===1,onClick:(()=>le({...g,variants:J.filter((te,he)=>he!==A)})),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(Ze,{className:"w-4 h-4"})})]},i.id||A))})]}):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(Pa,{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(tt.after_shipped_hours||72),onChange:(i=>le({...g,config_json:gt(g.config_json,{after_shipped_hours:Math.max(1,Number(i.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(tt.repeat_interval_hours||24),onChange:(i=>le({...g,config_json:gt(g.config_json,{repeat_interval_hours:Math.max(1,Number(i.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(tt.max_attempts||1),onChange:(i=>le({...g,config_json:gt(g.config_json,{max_attempts:Math.max(1,Number(i.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:((Ut=(zt=g.actions)==null?void 0:zt.find(i=>i.action_type==="send_text"))==null?void 0:Ut.message_template)||"",onChange:(i=>{var A;return le({...g,actions:((A=g.actions)!=null&&A.length?g.actions:Et("review_missing_timeout")).map(te=>te.action_type==="send_text"?{...te,message_template:i.target.value}:te)})}),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:g.priority||100,onChange:(i=>le({...g,priority:Number(i.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:g.enabled!==!1,onChange:(i=>le({...g,enabled:i.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:(()=>re(!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:E,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),ge&&oe&&Oe.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:oe.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>$(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:oe.item_id||"",onChange:(i=>ne({...oe,item_id:i.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),F.filter(i=>!n||i.cookie_id===n).map(i=>e.jsx("option",{value:i.item_id,children:i.item_title||i.item_id},`${i.cookie_id}-${i.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:oe.type||"text",onChange:(i=>{const A=i.target.value;ne({...oe,type:A,reply_content:A==="text"?oe.reply_content:"",image_url:A==="image"?oe.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:oe.keyword||"",onChange:(i=>ne({...oe,keyword:i.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),oe.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:oe.image_url||"",onChange:(i=>ne({...oe,image_url:i.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:oe.reply_content||"",onChange:(i=>ne({...oe,reply_content:i.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:(()=>$(!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:Pe,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ss,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),L&&Oe.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:(()=>V(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(ke,{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:de.cookie_id,onChange:(i=>Se({...de,cookie_id:i.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),z.map(i=>e.jsx("option",{value:i.id,children:Ht(i)},i.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:(()=>Se({...de,enabled:!de.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${de.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 ${de.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:de.reply_content,onChange:(i=>Se({...de,reply_content:i.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:de.reply_image_url,onChange:(i=>Se({...de,reply_image_url:i.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:de.reply_once,onChange:(i=>Se({...de,reply_once:i.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>V(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Q,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})},qs=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],As=(t,s)=>{if(typeof t=="boolean")return t;if(typeof t=="string"){if(["true","1","yes","on"].includes(t.toLowerCase()))return!0;if(["false","0","no","off"].includes(t.toLowerCase()))return!1}return s},Ya=t=>{const s=Object.prototype.hasOwnProperty.call(t,"use_custom_smtp"),a=qs.some(l=>String(t[l]??"").trim()!=="");return{...t,use_custom_smtp:s?As(t.use_custom_smtp,!1):a}},Xa=(t,s)=>{const a={...t,use_custom_smtp:!0};for(const l of qs)String(a[l]??"").trim()===""&&s[l]!==void 0&&(a[l]=s[l]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=As(a.smtp_use_tls,!0),a.smtp_use_ssl=As(a.smtp_use_ssl,!1),a},er=t=>{const s=Ya(t),a={to_email:String(s.to_email??"").trim(),use_custom_smtp:s.use_custom_smtp===!0};if(a.use_custom_smtp)for(const l of qs)a[l]=s[l];return a},Ct={bark:{label:"Bark",icon:Rt,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:$t,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:$t,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:$t,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:Lr,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:ss,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:Ta,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},tr=[{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:"后台任务或系统级异常"}],fa=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Mi=t=>!t||t.length===0?"全部事件":t.map(s=>{var a;return((a=tr.find(l=>l.value===s))==null?void 0:a.label)||s}).join("、"),qi=(t,s)=>{const a=t.type==="email"?Ya({...t.config||{}}):null,l=a?a.use_custom_smtp===!0?Xa(a,s):a:{...t.config||{}};return{name:t.name,type:t.type,enabled:t.enabled,config:l,event_types:t.event_types||[]}},Bi=t=>{const a=Ct[t.type].fields.find(l=>l.required&&!String(t.config[l.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!t.name.trim())return"请填写渠道名称";if(t.type==="email"){const l=er(t.config);if(l.use_custom_smtp){const c=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([u])=>!String(l[u]||"").trim());if(c)return`请填写 ${c[1]}`}}return""},Fi=t=>({name:t.name.trim(),type:t.type,config:t.type==="email"?er(t.config):t.config,event_types:t.event_types,enabled:t.enabled}),Ie=(t,s)=>t===s,Dt=(t,s)=>t instanceof Error&&t.message?t.message:s,zi=({channels:t,testingId:s,onEdit:a,onDelete:l,onToggleEnabled:n,onTest:c})=>{const u=_=>t.find(S=>S.id===_.currentTarget.dataset.channelId)||null,h=_=>{const S=u(_);S&&n(S)},m=_=>{const S=u(_);S&&c(S)},j=_=>{const S=u(_);S&&a(S)},x=_=>{const S=u(_);S&&l(S)},p=_=>{const S=Ct[_.type]||Ct.webhook,q=S.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(q,{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:_.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:S.label}),!_.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:S.fields.map(w=>{var O;return(O=_.config)==null?void 0:O[w.key]}).filter(Boolean).map((w,O)=>e.jsx("span",{className:"mr-3",children:String(w).length>40?`${String(w).slice(0,40)}…`:String(w)},O))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Mi(_.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":_.id,onClick:h,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${_.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:_.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":_.id,onClick:m,disabled:s===_.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:[s===_.id?e.jsx(_e,{className:"w-3 h-3 animate-spin"}):e.jsx(ss,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":_.id,onClick:j,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(Ra,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":_.id,onClick:x,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(Ze,{className:"w-4 h-4"})})]})]},_.id)};return t.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(Rt,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:t.map(p)})},Ui=({selectedEvents:t,onToggleEvent:s})=>{const a=l=>{const n=l.currentTarget.dataset.event;n&&s(n)};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:tr.map(l=>{const n=t.includes(l.value);return e.jsxs("button",{type:"button","data-event":l.value,onClick:a,className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${n?"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 ${n?"bg-brand border-brand":"border-gray-300"}`,children:n&&e.jsx(Ye,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${n?"text-brand":"text-gray-800"}`,children:l.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:l.description})]},l.value)})})]})},Wi=({showModal:t,editing:s,form:a,setForm:l,smtp:n,showChannelSmtpPassword:c,setShowChannelSmtpPassword:u,saving:h,onClose:m,onSave:j})=>{const x=Ct[a.type],p=f=>l(y=>({...y,name:f.target.value})),_=f=>{const y=f.currentTarget.dataset.type;y&&l(z=>({...z,type:y,config:{}}))},S=f=>{const y=f.currentTarget.dataset.field;y&&l(z=>({...z,config:{...z.config,[y]:f.target.value}}))},q=()=>l(f=>({...f,config:f.config.use_custom_smtp===!0?{...f.config,use_custom_smtp:!1}:Xa(f.config,n)})),w=f=>l(y=>({...y,config:{...y.config,smtp_use_tls:f.target.checked,smtp_use_ssl:f.target.checked?!1:y.config.smtp_use_ssl}})),O=f=>l(y=>({...y,config:{...y.config,smtp_use_ssl:f.target.checked,smtp_use_tls:f.target.checked?!1:y.config.smtp_use_tls}})),P=f=>l(y=>({...y,event_types:y.event_types.includes(f)?y.event_types.filter(z=>z!==f):[...y.event_types,f]})),G=()=>l(f=>({...f,enabled:!f.enabled})),H=()=>u(f=>!f),X=(f,y)=>e.jsx("li",{children:f},y);return t?Oe.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:s?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:m,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(ke,{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:p,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(Ct).map(f=>{const y=Ct[f],z=y.icon,I=a.type===f;return e.jsxs("button",{"data-type":f,type:"button",onClick:_,className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${I?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(z,{className:`w-5 h-5 ${I?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${I?"text-brand":"text-gray-600"}`,children:y.label})]},f)})})]}),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(Rt,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",x.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:x.guide.steps.map(X)}),x.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:x.guide.urlFormat})]}),x.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",x.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:x.fields.map(f=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[f.label,f.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":f.key,type:f.type==="password"?"password":f.type==="number"?"number":"text",value:String(a.config[f.key]||""),onChange:S,placeholder:f.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),f.help&&e.jsx("p",{className:"text-xs text-gray-500",children:f.help})]},f.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:q,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:S,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:S,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:S,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:c?"text":"password",value:String(a.config.smtp_password||""),onChange:S,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:H,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:c?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:S,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:S,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:w}),"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:O}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Ui,{selectedEvents:a.event_types,onToggleEvent:P}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:G,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:m,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:j,disabled:h,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[h?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Ye,{className:"w-4 h-4"}),h?"保存中...":"保存"]})]})]})}),document.body):null},Ji=({smtp:t,setSmtp:s,smtpSaving:a,showPassword:l,setShowPassword:n,onSave:c})=>{const u=_=>{const S=_.currentTarget.dataset.field;S&&s(q=>({...q,[S]:_.target.value}))},h=_=>{s(S=>({...S,smtp_port:parseInt(_.target.value,10)||587}))},m=_=>{s(S=>({...S,smtp_use_tls:_.target.checked,smtp_use_ssl:_.target.checked?!1:S.smtp_use_ssl}))},j=_=>{s(S=>({...S,smtp_use_ssl:_.target.checked,smtp_use_tls:_.target.checked?!1:S.smtp_use_tls}))},x=_=>{s(S=>({...S,smtp_password:_.target.value}))},p=()=>n(_=>!_);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(Ta,{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:t.smtp_server||"",onChange:u,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:t.smtp_port||587,onChange:h,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:t.smtp_user||"",onChange:u,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:l?"text":"password",value:t.smtp_password||"",onChange:x,placeholder:t.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:p,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:l?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:t.smtp_from_name||"",onChange:u,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:t.smtp_from_address||t.smtp_user||"",onChange:u,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:t.smtp_use_tls!==!1,onChange:m}),"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:t.smtp_use_ssl===!0,onChange:j}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:c,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(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},Gi=t=>{const[s,a]=r.useState([]),[l,n]=r.useState(!0),[c,u]=r.useState(!1),[h,m]=r.useState(null),[j,x]=r.useState(!1),[p,_]=r.useState(""),[S,q]=r.useState(null),[w,O]=r.useState({}),[P,G]=r.useState(!1),[H,X]=r.useState(!1),[f,y]=r.useState(!1),[z,I]=r.useState(fa),F=r.useRef(0),d=r.useRef(null),B=r.useRef(0),Z=r.useRef(null),M=r.useRef(0),b=r.useRef(null),k=r.useRef(null),D=r.useCallback((L,V)=>{q({type:L,text:V}),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{k.current=null,q(null)},3e3)},[]),C=r.useCallback(async()=>{var Y;const L=++F.current;(Y=d.current)==null||Y.abort();const V=new AbortController;d.current=V,n(!0);try{const se=await Ka({signal:V.signal});if(!Ie(L,F.current))return;a(se.data||[])}catch(se){Ie(L,F.current)&&!V.signal.aborted&&console.error("加载通知渠道失败",se)}finally{Ie(L,F.current)&&n(!1)}},[]),W=r.useCallback(async()=>{var Y;const L=++B.current;(Y=Z.current)==null||Y.abort();const V=new AbortController;Z.current=V;try{const se=await Wa({signal:V.signal});Ie(L,B.current)&&O(se||{})}catch(se){Ie(L,B.current)&&!V.signal.aborted&&console.error("加载 SMTP 配置失败",se)}},[]);r.useEffect(()=>{var L;return C(),t?W():(B.current+=1,(L=Z.current)==null||L.abort(),O({})),(()=>{var V,Y;F.current+=1,(V=d.current)==null||V.abort(),B.current+=1,(Y=Z.current)==null||Y.abort()})},[t,C,W]),r.useEffect(()=>(()=>{k.current!==null&&window.clearTimeout(k.current)}),[]);const K=r.useCallback(()=>{m(null),I(fa()),y(!1),u(!0)},[]),N=r.useCallback(L=>{m(L),I(qi(L,w)),y(!1),u(!0)},[w]),ee=r.useCallback(()=>{var L;M.current+=1,(L=b.current)==null||L.abort(),x(!1),u(!1)},[]),be=r.useCallback(async()=>{var se;const L=Bi(z);if(L){D("error",L);return}const V=++M.current;(se=b.current)==null||se.abort();const Y=new AbortController;b.current=Y,x(!0);try{const ue=Fi(z);if(h?await aa(h.id,ue,{signal:Y.signal}):await rn(ue,{signal:Y.signal}),!Ie(V,M.current)||(u(!1),await C(),!Ie(V,M.current)))return;D("success",h?"已更新":"已创建")}catch(ue){Ie(V,M.current)&&!Y.signal.aborted&&D("error",Dt(ue,"保存失败"))}finally{Ie(V,M.current)&&x(!1)}},[h,z,C,D]),U=r.useCallback(async L=>{var se;if(!confirm(`确认删除渠道「${L.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const V=++M.current;(se=b.current)==null||se.abort();const Y=new AbortController;b.current=Y;try{if(await ln(L.id,{signal:Y.signal}),!Ie(V,M.current)||(await C(),!Ie(V,M.current)))return;D("success","已删除")}catch(ue){Ie(V,M.current)&&!Y.signal.aborted&&D("error",Dt(ue,"删除失败"))}},[C,D]),re=r.useCallback(async L=>{var se;const V=++M.current;(se=b.current)==null||se.abort();const Y=new AbortController;b.current=Y;try{if(await aa(L.id,{enabled:!L.enabled},{signal:Y.signal}),!Ie(V,M.current))return;a(ue=>ue.map(ve=>ve.id===L.id?{...ve,enabled:!ve.enabled}:ve))}catch(ue){Ie(V,M.current)&&!Y.signal.aborted&&D("error",Dt(ue,"切换失败"))}},[D]),ge=r.useCallback(async L=>{var se;_(L.id);const V=++M.current;(se=b.current)==null||se.abort();const Y=new AbortController;b.current=Y;try{await on(L.id,{signal:Y.signal}),Ie(V,M.current)&&D("success","测试通知已发送,请检查对应渠道")}catch(ue){Ie(V,M.current)&&!Y.signal.aborted&&D("error",Dt(ue,"发送失败"))}finally{Ie(V,M.current)&&_("")}},[D]),$=r.useCallback(async()=>{var Y;const L=++B.current;(Y=Z.current)==null||Y.abort();const V=new AbortController;Z.current=V,G(!0);try{const se={smtp_server:w.smtp_server||"",smtp_port:w.smtp_port||587,smtp_user:w.smtp_user||"",smtp_from_name:w.smtp_from_name||"",smtp_from_address:w.smtp_from_address||w.smtp_user||"",smtp_use_tls:w.smtp_use_tls!==!1,smtp_use_ssl:w.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(w,"smtp_password")&&(se.smtp_password=w.smtp_password),await Ja(se,{signal:V.signal}),Ie(L,B.current)&&D("success","SMTP 配置已保存")}catch(se){Ie(L,B.current)&&!V.signal.aborted&&D("error",Dt(se,"保存失败"))}finally{Ie(L,B.current)&&G(!1)}},[D,w]);return{channels:s,loading:l,showModal:c,editing:h,saving:j,testingId:p,toast:S,smtp:w,smtpSaving:P,showSmtpPassword:H,showChannelSmtpPassword:f,form:z,setForm:I,setSmtp:O,setShowSmtpPassword:X,setShowChannelSmtpPassword:y,loadChannels:C,openCreate:K,openEdit:N,closeModal:ee,showToast:D,handleSave:be,handleDelete:U,handleToggleEnabled:re,handleTest:ge,handleSaveSmtp:$}},Ki=({isAdmin:t=!1})=>{const s=Gi(t);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:s.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(We,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:s.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(nt,{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(Rt,{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:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),s.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(_e,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(zi,{channels:s.channels,testingId:s.testingId,onEdit:s.openEdit,onDelete:s.handleDelete,onToggleEnabled:s.handleToggleEnabled,onTest:s.handleTest}),t&&e.jsx(Ji,{smtp:s.smtp,setSmtp:s.setSmtp,smtpSaving:s.smtpSaving,showPassword:s.showSmtpPassword,setShowPassword:s.setShowSmtpPassword,onSave:s.handleSaveSmtp}),e.jsx(Wi,{showModal:s.showModal,editing:s.editing,form:s.form,setForm:s.setForm,smtp:s.smtp,showChannelSmtpPassword:s.showChannelSmtpPassword,setShowChannelSmtpPassword:s.setShowChannelSmtpPassword,saving:s.saving,onClose:s.closeModal,onSave:s.handleSave}),s.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 ${s.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[s.toast.type==="success"?e.jsx(Ye,{className:"w-4 h-4"}):e.jsx(ke,{className:"w-4 h-4"}),s.toast.text]})]})},sr=[["尊嘟假嘟","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"]],Vi=t=>t,Qi=new Map(sr.map(([t,s])=>[t,s])),Hi=t=>t.split(/(\[[^\]]+\])/g).map((s,a)=>{const l=s.startsWith("[")?Qi.get(s.slice(1,-1)):void 0;return l?e.jsx("img",{src:l,alt:s,title:s,className:"mx-0.5 inline-block h-7 w-7 align-middle"},a):e.jsx(Is.Fragment,{children:s},a)}),Zi=(t,s,a)=>{const l=s.trim().toLowerCase();return t.filter(n=>a&&n.unread_count<=0?!1:l?[n.buyer_name,n.buyer_id,n.item_title,n.last_message].some(c=>(c||"").toLowerCase().includes(l)):!0)},Yi=(t,s)=>{const a=new Set(t.map(l=>l.message_key));return[...s.filter(l=>!a.has(l.message_key)),...t]},fs=(t,s)=>{const a=t.findIndex(l=>l.message_key===s.message_key);return a<0?[...t,s]:t.map((l,n)=>n===a?s:l)},Fe=(t,s,a)=>t===s&&!a.aborted,_t=t=>t instanceof Error&&t.message==="请求已取消",Xi=t=>{if(!t)return"";const s=new Date(t<1e10?t*1e3:t),a=new Date;return s.toDateString()===a.toDateString()?s.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):s.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},eo=t=>new Date(t<1e10?t*1e3:t).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),to=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(""),[n,c]=r.useState({}),[u,h]=r.useState(""),[m,j]=r.useState([]),[x,p]=r.useState(""),[_,S]=r.useState(!1),[q,w]=r.useState(""),[O,P]=r.useState(!0),[G,H]=r.useState(!1),[X,f]=r.useState(!1),[y,z]=r.useState(!1),[I,F]=r.useState(),[d,B]=r.useState({}),[Z,M]=r.useState({}),[b,k]=r.useState(!1),[D,C]=r.useState(!1),[W,K]=r.useState(!1),[N,ee]=r.useState(""),[be,U]=r.useState("connecting"),[re,ge]=r.useState(null),[$,L]=r.useState(null),V=r.useRef(""),Y=r.useRef(""),se=r.useRef(null),ue=r.useRef({accountID:"",chatID:""}),ve=r.useRef(!0),R=r.useRef(!1),T=r.useRef(null),g=r.useRef(new Set),le=r.useRef(0),oe=r.useRef(null),ne=r.useRef(0),de=r.useRef(null),Se=r.useRef(0),Ee=r.useRef(null),Te=r.useRef(0),Ue=r.useRef(null);r.useEffect(()=>{V.current=a},[a]),r.useEffect(()=>{Y.current=u},[u]);const Me=r.useCallback(async J=>{var E;const ie=++le.current;(E=oe.current)==null||E.abort();const v=new AbortController;oe.current=v;try{const ae=await is(J,void 0,{signal:v.signal},!0);return Fe(le.current,ie,v.signal)?(c(ce=>({...ce,[J]:ae.sessions})),B(ce=>({...ce,[J]:ae.next_cursor})),M(ce=>({...ce,[J]:ae.has_more})),ae.sessions):[]}catch(ae){return Fe(le.current,ie,v.signal)&&!_t(ae)&&ee(ae instanceof Error?ae.message:"同步会话失败"),[]}},[]);r.useEffect(()=>{const J=new AbortController;return(async()=>{var v;P(!0);try{const[E,ae]=await Promise.all([Ft({signal:J.signal}),Cs({signal:J.signal})]),fe=E.map(me=>{var o,Q;return{...me,runtime_state:((o=ae[me.id])==null?void 0:o.state)||(me.enabled?"connecting":"disabled"),runtime_connected:((Q=ae[me.id])==null?void 0:Q.connected)===!0}}).filter(me=>me.enabled),De=await Promise.all(fe.map(async me=>[me.id,await is(me.id,void 0,{signal:J.signal})]));if(J.signal.aborted)return;s(fe),c(Object.fromEntries(De.map(([me,o])=>[me,o.sessions]))),B(Object.fromEntries(De.map(([me,o])=>[me,o.next_cursor]))),M(Object.fromEntries(De.map(([me,o])=>[me,o.has_more])));const Ne=window.localStorage.getItem("ydisks.chat.account.v1")||"",Pe=fe.some(me=>me.id===Ne)?Ne:((v=fe[0])==null?void 0:v.id)||"";l(Pe)}catch(E){J.signal.aborted||ee(E instanceof Error?E.message:"加载聊天数据失败")}finally{J.signal.aborted||P(!1)}})(),(()=>J.abort())},[]),r.useEffect(()=>{let J=!1,ie=0,v=null;const E=async()=>{v=new AbortController;try{const ae=await Cs({signal:v.signal,timeoutMs:1e4});J||s(ce=>ce.map(fe=>{var De,Ne;return{...fe,runtime_state:((De=ae[fe.id])==null?void 0:De.state)||fe.runtime_state,runtime_connected:((Ne=ae[fe.id])==null?void 0:Ne.connected)??fe.runtime_connected}}))}catch{}finally{J||(ie=window.setTimeout(E,3e3))}};return ie=window.setTimeout(E,3e3),(()=>{J=!0,window.clearTimeout(ie),v==null||v.abort()})},[]),r.useEffect(()=>{if(!a)return;window.localStorage.setItem("ydisks.chat.account.v1",a);const J=n[a]||[];h(ie=>{var v;return J.some(E=>E.chat_id===ie)?ie:((v=J[0])==null?void 0:v.chat_id)||""})},[a,n]),r.useEffect(()=>{!a||g.current.has(a)||(g.current.add(a),Me(a))},[a,Me]),r.useEffect(()=>{var v;if(!a||!u){j([]);return}const J=++ne.current;(v=de.current)==null||v.abort();const ie=new AbortController;return de.current=ie,H(!0),Promise.all([Ys(a,u,void 0,void 0,{signal:ie.signal}),Xs(a,u,{signal:ie.signal})]).then(([E])=>{Fe(ne.current,J,ie.signal)&&(j(E.messages),z(E.has_more),F(E.next_cursor),E.session&&c(ae=>({...ae,[a]:(ae[a]||[]).map(ce=>{var fe;return ce.chat_id===((fe=E.session)==null?void 0:fe.chat_id)?E.session:ce})})),c(ae=>({...ae,[a]:(ae[a]||[]).map(ce=>ce.chat_id===u?{...ce,unread_count:0}:ce)})))}).catch(E=>{Fe(ne.current,J,ie.signal)&&!_t(E)&&ee(E instanceof Error?E.message:"加载消息失败")}).finally(()=>{Fe(ne.current,J,ie.signal)&&H(!1)}),(()=>ie.abort())},[a,u]),r.useEffect(()=>{var J;(J=Ee.current)==null||J.abort(),Se.current+=1},[a]),r.useEffect(()=>{var J;(J=Ue.current)==null||J.abort(),Te.current+=1},[a,u]),r.useEffect(()=>(()=>{var J,ie,v,E;(J=oe.current)==null||J.abort(),(ie=de.current)==null||ie.abort(),(v=Ee.current)==null||v.abort(),(E=Ue.current)==null||E.abort()}),[]);const Be=r.useCallback(async()=>{var ae;if(!a||!u||X||!y)return;const J=se.current,ie=(J==null?void 0:J.scrollHeight)||0,v=ne.current,E=new AbortController;R.current=!0,f(!0),ee("");try{const ce=(ae=m[0])==null?void 0:ae.id,fe=await Ys(a,u,I,ce,{signal:E.signal});if(!Fe(ne.current,v,E.signal))return;j(De=>Yi(De,fe.messages)),z(fe.has_more),F(fe.next_cursor),requestAnimationFrame(()=>{J&&(J.scrollTop+=J.scrollHeight-ie)})}catch(ce){R.current=!1,_t(ce)||ee(ce instanceof Error?ce.message:"加载历史消息失败")}finally{f(!1)}},[a,u,y,I,m,X]);r.useEffect(()=>{let J=!1,ie=0,v=0,E=null;const ae=()=>{if(J)return;U("connecting");const ce=window.location.protocol==="https:"?"wss:":"ws:";E=new WebSocket(`${ce}//${window.location.host}/api/v1/chat/ws`),E.onopen=()=>{v=0,U("online")},E.onmessage=fe=>{try{const Ne=JSON.parse(fe.data).message;if(!Ne)return;const Pe=Ne.account_id;c(me=>{const o=me[Pe]||[];return o.some(xe=>xe.chat_id===Ne.chat_id)?{...me,[Pe]:o.map(xe=>xe.chat_id===Ne.chat_id?{...xe,last_message:Ne.content,last_message_at:Ne.sent_at,unread_count:Ne.direction==="incoming"&&(V.current!==Pe||Y.current!==Ne.chat_id)?xe.unread_count+1:xe.unread_count}:xe).sort((xe,Le)=>Le.last_message_at-xe.last_message_at)}:(Me(Pe),me)}),V.current===Pe&&Y.current===Ne.chat_id&&(j(me=>fs(me,Ne)),Ne.direction==="incoming"&&Xs(Pe,Ne.chat_id))}catch{}},E.onclose=()=>{if(J)return;U("offline");const fe=Math.min(15e3,1e3*2**Math.min(v++,4));ie=window.setTimeout(ae,fe)},E.onerror=()=>E==null?void 0:E.close()};return ae(),(()=>{J=!0,window.clearTimeout(ie),E==null||E.close()})},[Me]);const Je=r.useCallback(()=>{const J=se.current;if(!J)return;const ie=J.scrollHeight-J.scrollTop-J.clientHeight;ve.current=ie<=48},[]);r.useLayoutEffect(()=>{const J=ue.current.accountID!==a||ue.current.chatID!==u;ue.current={accountID:a,chatID:u},J&&(ve.current=!0);const ie=se.current;if(ie){if(R.current){R.current=!1;return}(G||ve.current)&&(ie.scrollTop=ie.scrollHeight)}},[a,u,m,G]);const He=t.find(J=>J.id===a),we=n[a]||[],pe=we.find(J=>J.chat_id===u),Ke=r.useMemo(()=>Zi(we,x,_),[we,x,_]),it=r.useCallback(J=>(n[J]||[]).reduce((ie,v)=>ie+v.unread_count,0),[n]),tt=r.useCallback(async()=>{var E;if(!a||b||!Z[a])return;const J=++Se.current;(E=Ee.current)==null||E.abort();const ie=new AbortController;Ee.current=ie;const v=a;k(!0),ee("");try{const ae=await is(v,d[v],{signal:ie.signal},!0);if(!Fe(Se.current,J,ie.signal))return;c(ce=>({...ce,[v]:ae.sessions})),B(ce=>({...ce,[v]:ae.next_cursor})),M(ce=>({...ce,[v]:ae.has_more}))}catch(ae){Fe(Se.current,J,ie.signal)&&!_t(ae)&&ee(ae instanceof Error?ae.message:"加载历史联系人失败")}finally{Fe(Se.current,J,ie.signal)&&k(!1)}},[a,d,b,Z]),Ve=r.useCallback(async(J,ie)=>{var ae;if(!pe||!a||W)return;const v=++Te.current;(ae=Ue.current)==null||ae.abort();const E=new AbortController;Ue.current=E,K(!0),ee("");try{const ce=await el({account_id:a,chat_id:pe.chat_id,buyer_id:pe.buyer_id,buyer_name:pe.buyer_name,item_id:pe.item_id,item_title:pe.item_title,text:J},{signal:E.signal});if(!Fe(Te.current,v,E.signal))return;w(""),ge(null),j(fe=>fs(fe,ce.message))}catch(ce){Fe(Te.current,v,E.signal)&&(ie&&ge(J),_t(ce)||ee(ce instanceof Error?ce.message:"消息发送失败"))}finally{Fe(Te.current,v,E.signal)&&K(!1)}},[a,pe,W]),Ge=r.useCallback(async(J,ie)=>{var ae;if(!pe||!a||W)return;const v=++Te.current;(ae=Ue.current)==null||ae.abort();const E=new AbortController;Ue.current=E,K(!0),ee("");try{const ce=await tl({account_id:a,chat_id:pe.chat_id,buyer_id:pe.buyer_id,buyer_name:pe.buyer_name,buyer_avatar_url:pe.buyer_avatar_url,item_id:pe.item_id,item_title:pe.item_title,image:J},{signal:E.signal});if(!Fe(Te.current,v,E.signal))return;L(null),j(fe=>fs(fe,ce.message))}catch(ce){Fe(Te.current,v,E.signal)&&(ie&&L(J),_t(ce)||ee(ce instanceof Error?ce.message:"图片发送失败"))}finally{Fe(Te.current,v,E.signal)&&(K(!1),T.current&&(T.current.value=""))}},[a,pe,W]),ot=r.useCallback(async()=>{const J=q.trim();!J||!pe||!a||W||await Ve(J,!0)},[a,q,pe,Ve,W]),pt=r.useCallback(async J=>{!J||!pe||!a||W||await Ge(J,!0)},[a,pe,Ge,W]),ht=r.useCallback(async()=>{re?await Ve(re,!1):$&&await Ge($,!1)},[$,re,Ge,Ve]);return{accounts:t,activeAccountID:a,activeSessions:we,selectedSession:pe,activeAccount:He,messages:m,search:x,unreadOnly:_,draft:q,loading:O,messagesLoading:G,olderLoading:X,hasOlder:y,contactsLoading:b,hasMoreContacts:Z[a]===!0,emojiOpen:D,sending:W,error:N,liveState:be,activeChatID:u,filteredSessions:Ke,scrollRef:se,imageInputRef:T,setActiveAccountID:l,setActiveChatID:h,setSearch:p,setUnreadOnly:S,setDraft:w,setEmojiOpen:C,reloadSessions:Me,loadMoreContacts:tt,loadOlderMessages:Be,handleMessageScroll:Je,handleSend:ot,handleImage:pt,retrySend:ht,retryAvailable:!!(re||$),unreadForAccount:it,emojiURL:Vi,xianyuEmojis:sr,renderXianyuText:Hi,formatClock:Xi,messageTime:eo}},so=()=>{const{accounts:t,activeAccountID:s,activeChatID:a,activeAccount:l,selectedSession:n,filteredSessions:c,messages:u,search:h,unreadOnly:m,draft:j,loading:x,messagesLoading:p,olderLoading:_,hasOlder:S,contactsLoading:q,hasMoreContacts:w,emojiOpen:O,sending:P,error:G,liveState:H,scrollRef:X,imageInputRef:f,setActiveAccountID:y,setActiveChatID:z,setSearch:I,setUnreadOnly:F,setDraft:d,setEmojiOpen:B,reloadSessions:Z,loadMoreContacts:M,loadOlderMessages:b,handleMessageScroll:k,handleSend:D,handleImage:C,retrySend:W,retryAvailable:K,unreadForAccount:N,emojiURL:ee,xianyuEmojis:be,renderXianyuText:U,formatClock:re,messageTime:ge}=to();return x?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(_e,{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 ${H==="online"?"bg-emerald-50 text-emerald-700":H==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[H==="online"?e.jsx(Rr,{className:"h-3.5 w-3.5"}):e.jsx(Ar,{className:"h-3.5 w-3.5"}),H==="online"?"实时同步中":H==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:t.map($=>{const L=$.id===s,V=N($.id),Y=$.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":L,onClick:(()=>y($.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${L?"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 ${Y?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:$.nickname||$.remark||$.id}),V>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:V>99?"99+":V})]},$.id)})})]}),t.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(ys,{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(St,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:h,onChange:($=>I($.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:(()=>F($=>!$)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${m?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:m?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void Z(s)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(We,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[c.map($=>e.jsxs("button",{type:"button",onClick:(()=>z($.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${$.chat_id===a?"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:$.buyer_avatar_url?e.jsx("img",{src:$.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(Zt,{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:$.buyer_name||`用户 ${$.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:re($.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:$.last_message||"暂无消息"}),$.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:$.unread_count})]}),$.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",$.item_title]})]})]},$.chat_id)),c.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),w&&!h&&!m&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void M()),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(_e,{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:n?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:n.buyer_name||n.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",n.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(l==null?void 0:l.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(l==null?void 0:l.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:X,onScroll:k,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:p?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(_e,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[S&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void b()),disabled:_,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:[_&&e.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}),_?"正在加载":"加载更早消息"]})}),u.map($=>{const L=$.direction==="outgoing";return $.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:[U($.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:ge($.sent_at)})]})},$.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${L?"justify-end":"justify-start"}`,children:[!L&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:n.buyer_avatar_url?e.jsx("img",{src:n.buyer_avatar_url,alt:n.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(Zt,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${L?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:L?(l==null?void 0:l.nickname)||(l==null?void 0:l.remark)||"我":n.buyer_name||$.sender_name||n.buyer_id}),$.message_type==="image"?e.jsx("a",{href:$.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${L?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:$.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):$.message_type==="video"?e.jsx("video",{src:$.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 ${L?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:U($.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[ge($.sent_at),L&&($.status==="failed"?e.jsx(ut,{className:"h-3 w-3 text-red-500"}):$.status==="sent"?e.jsx(Ir,{className:"h-3 w-3 text-sky-500"}):e.jsx(Ye,{className:"h-3 w-3"}))]})]}),L&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:l!=null&&l.avatar_url?e.jsx("img",{src:l.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(Zt,{className:"m-2 h-5 w-5 text-sky-600"})})]},$.message_key)})]})}),G&&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:G}),K&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void W()),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:(()=>B($=>!$)),disabled:P||(l==null?void 0:l.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(Or,{className:"h-5 w-5"})}),O&&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:be.map(([$,L])=>e.jsx("button",{type:"button",title:`[${$}]`,onClick:(()=>{d(V=>V+`[${$}]`),B(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:ee(L),alt:`[${$}]`,className:"h-8 w-8 object-contain"})},$))})]})]}),e.jsx("input",{ref:f,type:"file",accept:"image/*",className:"hidden",onChange:($=>{var L;return void C((L=$.target.files)==null?void 0:L[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var $;return($=f.current)==null?void 0:$.click()}),disabled:P||(l==null?void 0:l.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(Pr,{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:j,onChange:($=>d($.target.value)),rows:2,maxLength:2e3,onKeyDown:($=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),D())}),disabled:(l==null?void 0:l.runtime_state)!=="online",placeholder:(l==null?void 0:l.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 D()),disabled:!j.trim()||P||(l==null?void 0:l.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:P?e.jsx(_e,{className:"h-4 w-4 animate-spin"}):e.jsx(ss,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(ys,{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:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})},ar="ydisks.sidebar.v1",ao=()=>{try{return window.localStorage.getItem(ar)==="collapsed"}catch{return!1}},ro=t=>{try{window.localStorage.setItem(ar,t?"collapsed":"expanded")}catch{}},rr={"/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"},ya=Object.fromEntries(Object.entries(rr).map(([t,s])=>[s,t])),ja=()=>rr[window.location.pathname]||"dashboard",lo=()=>{const[t,s]=r.useState(!1),[a,l]=r.useState(!1),[n,c]=r.useState(ja),[u,h]=r.useState(!0),[m,j]=r.useState(!1),[x,p]=r.useState(""),[_,S]=r.useState(""),[q,w]=r.useState(!1),[O,P]=r.useState(""),[G,H]=r.useState(""),[X,f]=r.useState(""),[y,z]=r.useState(!1),[I,F]=r.useState(""),[d,B]=r.useState(),[Z,M]=r.useState(ao),b=K=>{const N=K==="settings"&&!a?"dashboard":K,ee=ya[N];ee&&ee!==window.location.pathname&&window.history.pushState({},"",ee),c(N)};r.useEffect(()=>{const K=()=>c(ja());return window.addEventListener("popstate",K),()=>window.removeEventListener("popstate",K)},[]),r.useEffect(()=>{qa().then(N=>{if((N==null?void 0:N.initialized)===!1){j(!0),s(!1),l(!1);return}j(!1),N!=null&&N.authenticated?(s(!0),l(N.is_admin===!0)):l(!1)}).catch(()=>{s(!1),l(!1)}).finally(()=>h(!1));const K=()=>{s(!1),l(!1)};return window.addEventListener("auth:logout",K),()=>window.removeEventListener("auth:logout",K)},[]),r.useEffect(()=>{!u&&t&&!a&&n==="settings"&&(window.history.replaceState({},"",ya.dashboard),c("dashboard"))},[u,t,a,n]);const k=async K=>{K.preventDefault(),w(!0),P("");try{const N=await Kr({username:x,password:_});N.success?(s(!0),l(N.is_admin===!0)):P(N.message||"登录失败")}catch(N){const ee=N instanceof Error?N.message:String(N);P(ee||"登录失败")}finally{w(!1)}},D=async K=>{if(K.preventDefault(),F(""),G.length<8){F("密码至少需要 8 个字符");return}if(G!==X){F("两次输入的密码不一致");return}z(!0);try{const N=await Vr(G);if(!N.success){F(N.message||"初始化失败,请重试");return}j(!1),s(!0),l(N.is_admin===!0),H(""),f("")}catch(N){const ee=N instanceof Error?N.message:String(N);F(ee||"初始化失败,请重试")}finally{z(!1)}},C=async()=>{try{await Hr()}catch(K){console.error("退出登录失败",K)}finally{s(!1),l(!1)}};if(u)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface",children:e.jsx(_e,{className:"w-8 h-8 text-brand animate-spin"})});if(m)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-xl border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:e.jsx(ws,{sizeClass:"w-24 h-24"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"首次设置管理员密码"}),e.jsx("p",{className:"text-gray-600 font-medium",children:"设置完成后会自动进入系统,管理员账号为 admin。"})]}),e.jsxs("form",{onSubmit:D,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(Js,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"设置管理员密码(至少 8 个字符)",value:G,onChange:K=>H(K.target.value),autoFocus:!0,className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(qt,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"再次输入密码",value:X,onChange:K=>f(K.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),I&&e.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4"})," ",I]}),e.jsx("button",{type:"submit",disabled:y,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:y?e.jsx(_e,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["设置密码并进入系统 ",e.jsx(Ns,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!t)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-lg border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"group mx-auto mb-6 flex cursor-pointer justify-center",children:e.jsx(ws,{sizeClass:"w-24 h-24",logoClassName:"w-full h-full text-white group-hover:scale-110 transition-transform"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),e.jsxs("form",{onSubmit:k,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(yt,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"text",placeholder:"管理员账号",value:x,onChange:K=>p(K.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(Js,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"密码",value:_,onChange:K=>S(K.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),O&&e.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4"})," ",O]}),e.jsx("button",{type:"submit",disabled:q,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:q?e.jsx(_e,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["立即登录 ",e.jsx(Ns,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:e.jsx("div",{className:"mt-6 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const W=()=>{switch(n){case"dashboard":return e.jsx(ds,{});case"accounts":return e.jsx(zn,{});case"chat":return e.jsx(so,{});case"orders":return e.jsx(ti,{});case"cards":return e.jsx(oi,{});case"items":return e.jsx(vi,{onConfigureDelivery:K=>{B({cookieId:K.cookie_id,itemId:K.item_id,requestId:Date.now()}),b("rules")}});case"rules":return e.jsx($i,{initialDeliveryTarget:d,onDeliveryTargetHandled:()=>B(void 0)});case"notifications":return e.jsx(Ki,{isAdmin:a});case"settings":return a?e.jsx(Li,{}):e.jsx(ds,{});default:return e.jsx(ds,{})}};return e.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[e.jsx(un,{activeTab:n,isAdmin:a,collapsed:Z,onToggleCollapsed:()=>M(K=>{const N=!K;return ro(N),N}),onNavigate:b,onLogout:C}),e.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${Z?"ml-16":"ml-64"} ${n==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[e.jsx("div",{className:"fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"}),e.jsx("div",{className:`${n==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:W()})]})]})},lr=document.getElementById("root");if(!lr)throw new Error("Could not find root element to mount to");const no=ir.createRoot(lr);no.render(e.jsx(Is.StrictMode,{children:e.jsx(lo,{})})); +`).filter(d=>d.trim()).length})," 条"]})]}),x.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:x.api_method,onChange:(d=>h({...x,api_method:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:x.api_timeout,onChange:(d=>h({...x,api_timeout:parseInt(d.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:x.api_headers,onChange:(d=>h({...x,api_headers:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:x.api_params,onChange:(d=>h({...x,api_params:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:x.description,onChange:(d=>h({...x,description:d.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:x.delay_seconds,onChange:(d=>h({...x,delay_seconds:parseInt(d.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>c(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:y,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(si,{dataCards:O,downloadCardTemplate:F,...P})]})},ma="ydisks-amap-js-api",ci="c9b68d4ce9a2a97f22a4a439404488ca";let Ot=null;const di=()=>ci,xi=()=>window.AMap?Promise.resolve(window.AMap):Ot||(Ot=new Promise((t,s)=>{const a=document.getElementById(ma),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(u)},c=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},u=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=c,l.id=ma,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(di())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw Ot=null,t}),Ot),ts=t=>Number.isFinite(t)&&t!==0,mi=t=>{var n,c;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((c=t.location)==null?void 0:c.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!ts(s)||!ts(a)||s<-180||s>180||a<-90||a>90?null:l},ui=async(t,s)=>{if(!ts(t)||!ts(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await xi();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(u,p)=>{var f;if(u!=="complete"){if(u==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const m=(((f=p==null?void 0:p.poiList)==null?void 0:f.pois)||[]).map(mi).filter(x=>x!==null);l(m)})})},pi=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Rs=t=>t==="running"||t==="canceling",hi=t=>!!(t!=null&&t.preview_id&&Number(t.valid||0)>0),gi=t=>!!(t!=null&&t.id&&Number(t.retryable||0)>0&&!Rs(t.status)),bi=(t,s)=>t===s,ua=t=>{switch(t){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 t||"-"}},pa=t=>{switch(t){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"}},fi=t=>{const[s,a]=r.useState(!1),[l,n]=r.useState("upload"),[c,u]=r.useState(null),[p,m]=r.useState(null),[f,x]=r.useState(""),[h,_]=r.useState(!1),[S,q]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[w,O]=r.useState(null),[P,G]=r.useState(null),[H,X]=r.useState(null),[y,j]=r.useState([]),[z,A]=r.useState(null),[F,d]=r.useState(!1),B=r.useRef(!1),Z=r.useRef(0),M=r.useCallback(async()=>{n("upload"),O(null),G(null),u(null),m(null),x(""),q({catId:"",catName:"",channelCatId:"",tbCatId:""}),j([]),A(null),a(!0),d(!0);try{const U=await za(20),re=pi(U);if(re!=null&&re.id){const ge=await vt(re.id);X(ge),G(ge),n(["running","canceling"].includes(ge.status)?"running":"done")}}catch(U){console.error("恢复最近批量铺货任务失败:",U)}finally{d(!1)}},[]),b=r.useCallback(async()=>{const U=f.trim();if(!t.selectedAccount){alert("请先选择默认发布账号");return}if(!U){alert("请输入类目关键词");return}_(!0);try{const ge=(await Tl(t.selectedAccount,U)).category;q({catId:ge.cat_id,catName:ge.cat_name,channelCatId:ge.channel_cat_id,tbCatId:ge.tb_cat_id||""})}catch(re){console.error("获取推荐类目失败:",re),alert((re==null?void 0:re.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{_(!1)}},[f,t.selectedAccount]),k=r.useCallback(async()=>{if(H!=null&&H.id){d(!0),a(!0);try{const U=await vt(H.id);G(U),n(["running","canceling"].includes(U.status)?"running":"done")}catch(U){console.error("加载最近批量铺货结果失败:",U)}finally{d(!1)}}},[H==null?void 0:H.id]),D=r.useCallback(async()=>{if(!c){alert("请先上传商品表格");return}if(!t.selectedAccount){alert("请先选择默认发布账号");return}d(!0);try{const U=await El({file:c,imagesZip:p,defaultCookieId:t.selectedAccount,fallbackCategory:S,location:z||void 0});O(U),G(null),n("preview")}catch(U){console.error("批量铺货预检失败:",U),alert((U==null?void 0:U.message)||"预检失败,请检查表格和图片 zip")}finally{d(!1)}},[S,c,p,z,t.selectedAccount]),C=r.useCallback(async()=>{if(w!=null&&w.preview_id){if(!hi(w)){alert("没有可发布的商品行");return}d(!0);try{const U=await Dl(w.preview_id),re=await vt(U.batch_id||w.preview_id);G(re),X(re),n(re.status==="running"?"running":"done")}catch(U){console.error("启动批量铺货失败:",U),alert((U==null?void 0:U.message)||"启动发布任务失败")}finally{d(!1)}}},[w]),W=r.useCallback(async()=>{if(P!=null&&P.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){d(!0);try{const U=await Ml(P.id),re=await vt(P.id);G(re),n((U==null?void 0:U.status)==="canceling"||re.status==="canceling"?"running":"done")}catch(U){alert((U==null?void 0:U.message)||"取消失败")}finally{d(!1)}}},[P==null?void 0:P.id]),K=r.useCallback(async()=>{const U=w==null?void 0:w.preview_id;if(U&&l==="preview")try{await $l(U)}catch(re){console.error("清理批量铺货预检失败:",re)}O(null),n("upload")},[l,w==null?void 0:w.preview_id]),N=r.useCallback(async()=>{await K(),a(!1)},[K]),ee=r.useCallback(async()=>{if(!(!(P!=null&&P.id)||!gi(P))){d(!0);try{await ql(P.id),G(await vt(P.id)),n("running")}catch(U){alert((U==null?void 0:U.message)||"重试失败")}finally{d(!1)}}},[P]);return r.useEffect(()=>{if(!s||!(P!=null&&P.id)||!Rs(P.status))return;const U=++Z.current,re=async()=>{if(!B.current){B.current=!0;try{const $=await vt(P.id);if(!bi(U,Z.current))return;G($),X($),Rs($.status)||(n("done"),await Promise.all([t.loadItems(),t.loadShippingRules()]))}catch($){console.error("刷新批量铺货进度失败:",$)}finally{B.current=!1}}},ge=window.setInterval(()=>void re(),3e3);return(()=>{window.clearInterval(ge),Z.current+=1})},[P==null?void 0:P.id,P==null?void 0:P.status,t.loadItems,t.loadShippingRules,s]),{showBatchModal:s,setShowBatchModal:a,batchLoading:F,batchPhase:l,setBatchPhase:n,batchFile:c,setBatchFile:u,batchImagesZip:p,setBatchImagesZip:m,batchCategoryKeyword:f,setBatchCategoryKeyword:x,batchCategoryLoading:h,batchFallbackCategory:S,setBatchFallbackCategory:q,batchPreview:w,setBatchPreview:O,batchDetail:P,setBatchDetail:G,recentBatch:H,setRecentBatch:X,batchLocations:y,batchLocation:z,setBatchLocations:j,setBatchLocation:A,openBatchModal:M,handleRecommendBatchCategory:b,openRecentBatchResult:k,handlePreviewBatch:D,handleStartBatch:C,handleCancelBatch:W,abandonBatchPreview:K,closeBatchModal:N,handleRetryBatchFailed:ee}},yi=({phase:t})=>{const s=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:s.map(([a,l])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${t===a?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:l},a))})},ji=t=>{const s=String(t||"").trim();return s?/^[¥¥]/.test(s)?s:`¥${s}`:"-"},vi=({onConfigureDelivery:t})=>{const[s,a]=r.useState([]),[l,n]=r.useState([]),[c,u]=r.useState([]),[p,m]=r.useState(""),[f,x]=r.useState(""),[h,_]=r.useState(!1),[S,q]=r.useState(!1),[w,O]=r.useState(!1),[P,G]=r.useState(!1),[H,X]=r.useState(!1),[y,j]=r.useState(!1),[z,A]=r.useState([]),[F,d]=r.useState(null),[B,Z]=r.useState(null),[M,b]=r.useState({}),[k,D]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[C,W]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[K,N]=r.useState([]),ee=r.useCallback(async()=>{const o=await Lt();a(o)},[]),be=r.useCallback(async()=>{n(await Ss())},[]),U=fi({selectedAccount:p,loadItems:ee,loadShippingRules:be}),{showBatchModal:re,setShowBatchModal:ge,batchLoading:$,batchPhase:L,batchFile:V,setBatchFile:Y,batchImagesZip:se,setBatchImagesZip:ue,batchCategoryKeyword:ve,setBatchCategoryKeyword:R,batchCategoryLoading:T,batchFallbackCategory:g,setBatchFallbackCategory:le,batchPreview:oe,batchDetail:ne,recentBatch:de,setRecentBatch:Se,batchLocations:Ee,batchLocation:Te,setBatchLocations:Ue,setBatchLocation:Me,openBatchModal:Be,handleRecommendBatchCategory:Je,openRecentBatchResult:He,handlePreviewBatch:we,handleStartBatch:pe,handleCancelBatch:Ke,abandonBatchPreview:it,closeBatchModal:tt,handleRetryBatchFailed:Ve}=U;r.useEffect(()=>{if(!H||C.images.length===0){N([]);return}const o=C.images.map((Q,xe)=>({key:Q.name+xe,url:URL.createObjectURL(Q)}));return N(o),(()=>{o.forEach(Q=>URL.revokeObjectURL(Q.url))})},[H,C.images]),r.useEffect(()=>{Promise.all([Ft(),Lt(),Ss(),za(20)]).then(([o,Q,xe,Le])=>{u(o),a(Q),n(xe);const st=Le.find(Qe=>["running","canceling"].includes(Qe.status))||Le.find(Qe=>Qe.status!=="preview");Se(st||null)}).catch(o=>console.error("加载商品配置失败:",o))},[]);const Ge=async()=>{if(!p)return alert("请先选择账号");_(!0);try{const o=await Il(p);await ee(),alert((o==null?void 0:o.message)||"商品同步完成")}catch(o){console.error("同步商品失败:",o),alert((o==null?void 0:o.message)||"同步失败,请重试")}finally{_(!1)}},ot=o=>{Z(o),b({...o}),O(!0)},pt=async()=>{if(B)try{await Bl(B.cookie_id,B.item_id,{item_title:M.item_title||"",item_description:M.item_description||"",item_category:M.item_category||"",item_price:M.item_price||"",item_detail:M.item_detail||B.item_detail||""}),await ee(),await be(),O(!1),Z(null)}catch(o){console.error("更新商品失败:",o),alert("更新失败,请重试")}},ht=async o=>{if(confirm(`确认删除商品"${o.item_title}"吗?`))try{await Al(o.cookie_id,o.item_id),a(Q=>Q.filter(xe=>!(xe.cookie_id===o.cookie_id&&xe.item_id===o.item_id)))}catch(Q){console.error("删除商品失败:",Q),alert("删除失败,请重试")}},J=async()=>{try{if(!k.cookie_id||!k.item_id){alert("请选择账号并填写商品ID");return}await Ol(k.cookie_id,{item_id:k.item_id,item_title:k.item_title,item_price:k.item_price,item_detail:k.item_image?JSON.stringify({item_image:k.item_image}):""}),await ee(),G(!1),D({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(o){console.error("添加商品失败:",o),alert("添加失败,请重试")}},ie=async()=>{if(!C.cookie_id)return alert("请选择发布账号");if(!C.title.trim())return alert("请填写商品标题");if(!C.price.trim())return alert("请填写商品价格");if(!C.quantity||Number(C.quantity)<=0)return alert("库存数量必须大于 0");if(C.images.length===0)return alert("至少上传 1 张商品图片");if(C.postage_mode==="fixed"&&!C.postage.trim())return alert("请填写一口价邮费");q(!0);try{const o=await Pl({...C,location:F||void 0});if(await ee(),X(!1),W({cookie_id:p||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),A([]),d(null),o!=null&&o.item_id){const Q={id:o.item_id,cookie_id:C.cookie_id,item_id:o.item_id,item_title:o.item_title||C.title,item_price:o.item_price||C.price,item_image:o.item_image};t(Q),alert("商品发布成功,ID: "+o.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(o){console.error("发布商品失败:",o);const Q=o==null?void 0:o.payload;if((Q==null?void 0:Q.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((o==null?void 0:o.message)||"发布失败,请重试")}finally{q(!1)}},v=()=>{const xe=[["账号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(zt=>zt.map(Ut=>`"${String(Ut).replace(/"/g,'""')}"`).join(",")).join(` +`),Le=new Blob(["\uFEFF"+xe],{type:"text/csv;charset=utf-8"}),st=URL.createObjectURL(Le),Qe=document.createElement("a");Qe.href=st,Qe.download="批量铺货模板.csv",document.body.appendChild(Qe),Qe.click(),Qe.remove(),URL.revokeObjectURL(st)},E=()=>{D(o=>({...o,cookie_id:p||o.cookie_id})),G(!0)},ae=()=>{W(o=>({...o,cookie_id:p||o.cookie_id})),X(!0)},ce=async o=>{if(!(o?p:C.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");j(!0),navigator.geolocation.getCurrentPosition(async xe=>{try{const Le=await ui(xe.coords.longitude,xe.coords.latitude);if(!Le.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(Ue(Le),Me(Le[0])):(A(Le),d(Le[0]))}catch(Le){alert((Le==null?void 0:Le.message)||"获取发货地失败")}finally{j(!1)}},xe=>{j(!1),alert(xe.code===xe.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},fe=o=>l.filter(Q=>Q.cookie_id===o.cookie_id&&Q.item_id===o.item_id).length>0?l.filter(Q=>Q.cookie_id===o.cookie_id&&Q.item_id===o.item_id):l.filter(Q=>Q.cookie_id===o.cookie_id&&!Q.item_id),De=r.useMemo(()=>new Map(c.map(o=>[o.id,o])),[c]),Ne=r.useMemo(()=>f?s.filter(o=>o.cookie_id===f):s,[f,s]),Pe=o=>{const Q=De.get(o),xe=(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname);return xe?`${xe} · ${o.slice(0,6)}`:`账号 ${o.slice(0,8)}`},me=o=>{const Q=De.get(o);return(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.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(vr,{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:f,onChange:(o=>x(o.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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(yt,{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:p,onChange:(o=>m(o.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.id))]})]})]}),e.jsxs("button",{onClick:Ge,disabled:h||!p,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(We,{className:`w-4 h-4 ${h?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:E,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(nt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:ae,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(ls,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void Be()),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(Wt,{className:"w-4 h-4"}),de&&["running","canceling"].includes(de.status)?"继续批量任务":"批量铺货"]}),de&&!["running","canceling"].includes(de.status)&&e.jsx("button",{onClick:(()=>void He()),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:[Ne.map(o=>{const Q=fe(o),xe=Q.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:(()=>ot(o)),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(kt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:(()=>ht(o)),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(Ze,{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:[o.item_image?e.jsx("img",{src:o.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(Na,{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:ji(o.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:o.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:me(o.cookie_id),children:[e.jsx(yt,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:me(o.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: ",o.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${xe?"text-emerald-600":"text-amber-600"}`,children:[xe?e.jsx(vs,{className:"w-3 h-3"}):e.jsx(Nr,{className:"w-3 h-3"}),xe?`${Q.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:(()=>t(o)),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${xe?"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(_r,{className:"w-3.5 h-3.5"}),xe?"查看发货规则":"关联发货规则"]}),e.jsx(Ns,{className:"w-3.5 h-3.5"})]})})]},`${o.cookie_id}-${o.item_id}`)}),Ne.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(_a,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),f?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),w&&B&&Oe.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: ",B.item_id]})]}),e.jsx("button",{onClick:(()=>O(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ke,{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:M.item_title||"",onChange:(o=>b({...M,item_title:o.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:M.item_price||"",onChange:(o=>b({...M,item_price:o.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:M.item_category||"",onChange:(o=>b({...M,item_category:o.target.value}))}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:M.item_description||"",onChange:(o=>b({...M,item_description:o.target.value}))})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:pt,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),P&&Oe.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:(()=>G(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(ke,{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:k.cookie_id,onChange:(o=>D({...k,cookie_id:o.target.value})),children:[e.jsx("option",{value:"",children:"选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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:k.item_id,onChange:(o=>D({...k,item_id:o.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:k.item_price,onChange:(o=>D({...k,item_price:o.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:k.item_title,onChange:(o=>D({...k,item_title:o.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:k.item_image,onChange:(o=>D({...k,item_image:o.target.value}))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:J,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(nt,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),H&&Oe.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:(()=>X(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(ke,{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:C.cookie_id,onChange:(o=>{W({...C,cookie_id:o.target.value}),A([]),d(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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:C.title,onChange:(o=>W({...C,title:o.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:C.quantity,onChange:(o=>W({...C,quantity:o.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:C.description,onChange:(o=>W({...C,description:o.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:C.price,onChange:(o=>W({...C,price:o.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:C.original_price,onChange:(o=>W({...C,original_price:o.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:C.postage_mode,onChange:(o=>W({...C,postage_mode:o.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:"无需邮寄"})]})]})]}),C.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:C.postage,onChange:(o=>W({...C,postage:o.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:y||!C.cookie_id,onClick:(()=>void ce(!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(Us,{className:"h-4 w-4"}),y?"定位中...":"获取当前位置"]})]}),z.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,z.indexOf(F))),onChange:(o=>d(z[Number(o.target.value)]||null)),children:z.map((o,Q)=>e.jsx("option",{value:String(Q),children:[o.province,o.city,o.area,o.poi_name].filter(Boolean).join(" ")},`${o.division_id}-${o.poi_id}-${Q}`))})]}),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(Wt,{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:C.images.length?"已选择 "+C.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:(o=>W({...C,images:Array.from(o.target.files||[]).slice(0,9)}))})]}),K.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:K.map(o=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:o.url,alt:"",className:"w-full h-full object-cover"})},o.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:S,onClick:ie,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(ls,{className:"w-4 h-4"}),S?"正在发布...":"发布到闲鱼"]})})]})}),document.body),re&&Oe.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 tt()),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx(yi,{phase:L}),L==="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:v,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:p,onChange:(o=>{m(o.target.value),Ue([]),Me(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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(St,{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:ve,onChange:(o=>R(o.target.value)),onKeyDown:(o=>{o.key==="Enter"&&(o.preventDefault(),Je())})})]}),e.jsxs("button",{type:"button",disabled:!p||!ve.trim()||T,onClick:(()=>void Je()),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(St,{className:"h-4 w-4"}),T?"匹配中...":"获取类目"]})]}),g.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(vs,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:g.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",g.catId," · 频道 ",g.channelCatId]})]}),e.jsx("button",{type:"button",title:"清除默认类目",onClick:(()=>le({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(ke,{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:y||!p,onClick:(()=>void ce(!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(Us,{className:"h-4 w-4"}),y?"定位中...":"获取当前位置"]})]}),Ee.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,Ee.indexOf(Te))),onChange:(o=>Me(Ee[Number(o.target.value)]||null)),children:Ee.map((o,Q)=>e.jsx("option",{value:String(Q),children:[o.province,o.city,o.area,o.poi_name].filter(Boolean).join(" ")},`${o.division_id}-${o.poi_id}-${Q}`))})]}),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(Wt,{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:V?V.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:(o=>{var Q;return Y(((Q=o.target.files)==null?void 0:Q[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(Wt,{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:se?se.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:(o=>{var Q;return ue(((Q=o.target.files)==null?void 0:Q[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(([o,Q,xe])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:o}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${Q==="每个商品都要填"?"text-red-600":Q==="可以留空"?"text-gray-500":"text-amber-700"}`,children:Q}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:xe})]},o))})]})})]})]}),L==="preview"&&oe&&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:oe.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:oe.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:oe.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:oe.rows.map(o=>{var Q,xe,Le,st;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:o.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 ${o.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:o.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:o.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",o.price||"-"," / ",o.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:((Q=o.category)==null?void 0:Q.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((xe=o.category)==null?void 0:xe.cat_id)||"失败后使用电子资料"})]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((Le=o.images)==null?void 0:Le.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((st=o.errors)==null?void 0:st.join(";"))||"-"})]},o.row_no)})})]})})]}),(L==="running"||L==="done")&&ne&&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 ${pa(ne.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:ua(ne.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:ne.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:ne.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:ne.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:ne.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:ne.rows.map(o=>{var Q,xe;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:o.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 ${pa(o.status)}`,children:ua(o.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:o.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:((Q=o.category)==null?void 0:Q.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((xe=o.category)==null?void 0:xe.cat_id)||"失败后使用电子资料"})]}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:o.item_url?e.jsx("a",{href:o.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:o.item_id}):o.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:o.error_message||"-"})]},o.id)})})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[L==="upload"&&e.jsxs("button",{disabled:$||!V||!p,onClick:we,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(We,{className:`w-4 h-4 ${$?"animate-spin":""}`}),$?"正在预检...":"开始预检"]}),L==="preview"&&oe&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:$,onClick:(()=>void it()),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:$||oe.valid<=0,onClick:pe,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(ls,{className:"w-4 h-4"}),$?"启动中...":`确认发布 ${oe.valid} 个商品`]})]}),(L==="running"||L==="done")&&ne&&e.jsxs("div",{className:"flex gap-3 w-full",children:[ne.status==="running"?e.jsx("button",{disabled:$,onClick:Ke,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):ne.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/${ne.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:"下载结果"}),ne.retryable>0&&!["running","canceling"].includes(ne.status)&&e.jsxs("button",{disabled:$,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(We,{className:`w-4 h-4 ${$?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(ne.status)&&e.jsx("button",{onClick:(()=>{ge(!1),ee(),be()}),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)]})},Ha="https://dashscope.aliyuncs.com/compatible-mode/v1",Ni=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],_i=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"]),wi=t=>Object.fromEntries(Object.entries(t).filter(([s,a])=>!_i.has(s)&&a!==void 0&&a!==null)),ki=t=>t.new_username.trim().length<3?"用户名至少需要 3 个字符":t.current_password?t.new_password&&t.new_password.length<8?"新密码至少需要 8 个字符":t.new_password!==t.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",rt=(t,s,a)=>t===s&&!a.aborted,Gt=t=>t instanceof Error&&t.message==="请求已取消",Kt=(t,s)=>t instanceof Error?t.message:s,Ci=(t="")=>({new_username:t,current_password:"",new_password:"",confirm_password:""}),Vt=(t,s)=>({type:t,text:s}),Si=()=>{const[t,s]=r.useState(null),[a,l]=r.useState(!1),[n,c]=r.useState(""),[u,p]=r.useState(!1),[m,f]=r.useState(""),[x,h]=r.useState([]),[_,S]=r.useState(!1),[q,w]=r.useState(""),[O,P]=r.useState(!1),[G,H]=r.useState(!1),[X,y]=r.useState(!1),[j,z]=r.useState(!1),[A,F]=r.useState(!1),[d,B]=r.useState(!1),[Z,M]=r.useState(null),[b,k]=r.useState(()=>Ci()),[D,C]=r.useState("idle"),W=r.useRef(null),K=r.useRef(null),N=r.useRef(0),ee=r.useRef(null);K.current=t;const be=r.useCallback(()=>{var V;(V=ee.current)==null||V.abort();const L=new AbortController;return ee.current=L,N.current+=1,{controller:L,sequence:N.current}},[]),U=r.useCallback(async(L,V=!1,Y)=>{const se=L||K.current,ue=(se==null?void 0:se.ai_api_url)||(se==null?void 0:se.ai_base_url)||Ha;S(!0),w("");try{const ve=await sn(ue,(se==null?void 0:se.ai_api_key)||"",{signal:Y});if(Y!=null&&Y.aborted)return;h(ve),P(V&&ve.length>0),!(se!=null&&se.ai_model)&&ve.length>0&&s(R=>R&&{...R,ai_model:ve[0]})}catch(ve){if(Y!=null&&Y.aborted||Gt(ve))return;h([]),P(!1),w(Kt(ve,"读取模型失败"))}finally{Y!=null&&Y.aborted||S(!1)}},[]),re=r.useCallback(()=>{const{controller:L,sequence:V}=be();l(!0),C("loading"),c(""),Promise.all([Wa({signal:L.signal}),qa({signal:L.signal})]).then(([Y,se])=>{rt(N.current,V,L.signal)&&(s(Y),se.username&&k(ue=>({...ue,new_username:se.username||""})),U(Y,!1,L.signal),C("success"))}).catch(Y=>{!rt(N.current,V,L.signal)||Gt(Y)||(s(null),c(Kt(Y,"加载配置失败")),C("error"))}).finally(()=>{rt(N.current,V,L.signal)&&l(!1)})},[be,U]);r.useEffect(()=>(re(),(()=>{var L;return(L=ee.current)==null?void 0:L.abort()})),[re]),r.useEffect(()=>{const L=V=>{var Y;(Y=W.current)!=null&&Y.contains(V.target)||P(!1)};return document.addEventListener("mousedown",L),(()=>document.removeEventListener("mousedown",L))},[]);const ge=r.useCallback(async()=>{if(!t||u)return;const{controller:L,sequence:V}=be();p(!0),f("");try{if(await Ja(wi(t),{signal:L.signal}),!rt(N.current,V,L.signal))return;window.alert("系统配置已保存")}catch(Y){if(!rt(N.current,V,L.signal)||Gt(Y))return;f(Kt(Y,"保存配置失败"))}finally{rt(N.current,V,L.signal)&&p(!1)}},[be,u,t]),$=r.useCallback(async L=>{L.preventDefault(),M(null);const V=ki(b);if(V){M(Vt("error",V));return}const{controller:Y,sequence:se}=be();B(!0);try{const ue=await Zr({current_password:b.current_password,new_username:b.new_username.trim(),new_password:b.new_password||void 0},{signal:Y.signal});if(!rt(N.current,se,Y.signal))return;if(!ue.success){M(Vt("error",ue.message||"登录凭据更新失败"));return}M(Vt("success",ue.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(ue){if(!rt(N.current,se,Y.signal)||Gt(ue))return;M(Vt("error",Kt(ue,"登录凭据更新失败")))}finally{rt(N.current,se,Y.signal)&&B(!1)}},[be,b]);return{settings:t,loading:a,loadError:n,saving:u,saveError:m,aiModels:x,modelsLoading:_,modelError:q,modelDropdownOpen:O,showApiKey:G,showCaptchaSecret:X,showCurrentPassword:j,showNewPassword:A,credentialsSaving:d,credentialsMessage:Z,credentials:b,requestStatus:D,modelPickerRef:W,loadSettings:re,loadAIModels:((L,V)=>void U(L,V)),handleSave:ge,handleCredentialsSave:$,setSettings:s,setModelDropdownOpen:P,setShowApiKey:H,setShowCaptchaSecret:y,setShowCurrentPassword:z,setShowNewPassword:F,setCredentials:k,setCredentialsMessage:M}},Li=()=>{const{settings:t,loading:s,loadError:a,saving:l,saveError:n,aiModels:c,modelsLoading:u,modelError:p,modelDropdownOpen:m,showApiKey:f,showCaptchaSecret:x,showCurrentPassword:h,showNewPassword:_,credentialsSaving:S,credentialsMessage:q,credentials:w,modelPickerRef:O,loadSettings:P,loadAIModels:G,handleSave:H,handleCredentialsSave:X,setSettings:y,setModelDropdownOpen:j,setShowApiKey:z,setShowCaptchaSecret:A,setShowCurrentPassword:F,setShowNewPassword:d,setCredentials:B}=Si();if(!t)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[a||(s?"加载配置中...":"暂无配置"),!s&&a&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:P,children:"重新加载"})})]});const Z=t.ai_model||"",M=c;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(Ps,{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:P,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(We,{className:"w-4 h-4"}),"刷新"]})]}),n&&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:n}),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(wr,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:t.log_level||"info",onChange:(b=>y({...t,log_level:b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:Ni.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:t.log_format||"text",onChange:(b=>y({...t,log_format:b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:t.renewal_log_retention_days??10,onChange:(b=>y({...t,renewal_log_retention_days:parseInt(b.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-brand text-white",children:e.jsx(Ds,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:t.ai_api_url||Ha,onChange:(b=>y({...t,ai_api_url:b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:f?"text":"password",value:t.ai_api_key||"",onChange:(b=>y({...t,ai_api_key:b.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:t.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>z(!f)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:f?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:O,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:Z,onFocus:(()=>c.length>0&&j(!0)),onChange:(b=>{y({...t,ai_model:b.target.value}),c.length>0&&j(!0)}),onKeyDown:(b=>{b.key==="Escape"&&j(!1),b.key==="ArrowDown"&&c.length>0&&j(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>c.length>0&&j(b=>!b)),disabled:c.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(kr,{className:`w-4 h-4 transition-transform ${m?"rotate-180":""}`})}),m&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:M.length>0?M.map(b=>e.jsxs("button",{type:"button",onClick:(()=>{y({...t,ai_model:b}),j(!1)}),className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:b}),b===Z&&e.jsx(Ye,{className:"w-4 h-4 shrink-0 text-brand"})]},b)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>G(void 0,!0)),disabled:u,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(We,{className:`w-4 h-4 ${u?"animate-spin":""}`}),"读取模型"]})]}),p?e.jsx("p",{className:"text-xs text-red-500",children:p}):e.jsx("p",{className:"text-xs text-gray-500",children:c.length>0?`已从当前 API 地址读取到 ${c.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(qt,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:t["captcha.remote_service_url"]||"",onChange:(b=>y({...t,"captcha.remote_service_url":b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:x?"text":"password",value:t["captcha.remote_secret_key"]||"",onChange:(b=>y({...t,"captcha.remote_secret_key":b.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:t["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>A(!x)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:x?"隐藏秘钥":"显示秘钥",children:x?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(t["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(b=>y({...t,"captcha.remote_pass_cookies":b.target.checked})),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(Ws,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:X,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(Zt,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:w.new_username,onChange:(b=>B({...w,new_username:b.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:h?"text":"password",value:w.current_password,onChange:(b=>B({...w,current_password:b.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:(()=>F(!h)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:h?"隐藏密码":"显示密码",children:h?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:_?"text":"password",value:w.new_password,onChange:(b=>B({...w,new_password:b.target.value})),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:(()=>d(!_)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:_?"隐藏密码":"显示密码",children:_?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:_?"text":"password",value:w.confirm_password,onChange:(b=>B({...w,confirm_password:b.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),q&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${q.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(qt,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:q.text})]}),e.jsxs("button",{type:"submit",disabled:S||!w.new_username||!w.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(Ws,{className:"w-4 h-4"}),S?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:H,disabled:l,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(lt,{className:"w-6 h-6"}),l?"保存中...":"保存所有配置"]})})]})},us=(t,s)=>t.allowed_resolutions.includes(s),Ri=(t,s)=>({runs:t.runs.filter(a=>!s||a.cookie_id===s),pending_tasks:t.pending_tasks.filter(a=>!s||a.cookie_id===s)}),Ii=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",Ai=({runs:t,pendingTasks:s,onResolveRun:a,onResolveDeferredTask:l})=>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(ut,{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:[t.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:Ii(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:[us(n,"continue")&&e.jsx("button",{onClick:(()=>a(n.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),us(n,"retry")&&e.jsx("button",{onClick:(()=>a(n.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),us(n,"cancel")&&e.jsx("button",{onClick:(()=>a(n.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${n.id}`)),s.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:(()=>l(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:(()=>l(n.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${n.id}`))]})]}),ps=()=>({submitting:!1,result:"idle"}),hs=t=>t.submitting?t:{submitting:!0,result:"idle"},gs=(t,s)=>({submitting:!1,result:s?"success":"failure"}),ha=t=>t+1,bs=(t,s,a,l)=>t===s&&a===l,Oi=t=>{const[s,a]=r.useState([]),[l,n]=r.useState({runs:[],pending_tasks:[]}),[c,u]=r.useState([]),[p,m]=r.useState({}),[f,x]=r.useState([]),[h,_]=r.useState([]),[S,q]=r.useState([]),[w,O]=r.useState(!1),P=r.useRef(0),G=r.useRef(0),[H,X]=r.useState(0),[y,j]=r.useState(0),[z,A]=r.useState({}),F=r.useCallback(async()=>{const k=Promise.all([Ft(),Ms(),Lt(),ra()]),[D,C,W,K]=await k;x(D),_(C),q(W),m(K),t.setSelectedAccountId(N=>{var ee;return N||((ee=D[0])==null?void 0:ee.id)||""})},[t.setSelectedAccountId]),d=r.useCallback(async()=>{var K;const k=ha(P.current);P.current=k;const D=Wl().catch(N=>(console.warn("加载自动化异常列表失败,不阻断规则展示",N),null)),C=await Fl({cookieId:t.selectedAccountId||void 0,triggerType:t.automationTriggerFilter,enabled:t.automationStatusFilter==="all"?void 0:t.automationStatusFilter==="enabled",search:t.debouncedAutomationSearch,page:t.automationPage,pageSize:t.automationPageSize});if(!bs(k,P.current,t.selectedAccountId,t.selectedAccountId))return;a(C.data),X(C.total),j(C.total_pages),A(C.trigger_counts||{}),C.page!==t.automationPage&&((K=t.onAutomationPageChange)==null||K.call(t,C.page));const W=await D;bs(k,P.current,t.selectedAccountId,t.selectedAccountId)&&W&&n(W)},[t.automationPage,t.automationPageSize,t.automationStatusFilter,t.automationTriggerFilter,t.debouncedAutomationSearch,t.onAutomationPageChange,t.selectedAccountId]),B=r.useCallback(async()=>{const k=ha(G.current);G.current=k;const D=t.selectedAccountId;if(u([]),!D)return;const C=await Ql(D);bs(k,G.current,D,t.selectedAccountId)&&u(C)},[t.selectedAccountId]),Z=r.useCallback(async()=>{m(await ra())},[]),M=r.useCallback(async()=>{O(!0);try{t.activeTab==="automation"?await d():t.activeTab==="reply"?await B():await Z()}finally{O(!1)}},[d,Z,B,t.activeTab]);return{automationRules:s,automationIssues:l,replyRules:c,defaultReplies:p,accounts:f,cards:h,items:S,automationTotal:H,automationTotalPages:y,automationTriggerCounts:z,loading:w,setLoading:O,setAutomationRules:a,setCards:_,setItems:q,loadReferenceData:F,loadAutomationRules:d,loadReplyRules:B,loadDefaultReplies:Z,refresh:M}},xt={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:Bt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:Cr},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:Pa}},Qt=["order_paid","buyer_reviewed","review_missing_timeout"],Pi="亲,商品使用满意的话,麻烦给个评价,谢谢~",Pt=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),Za=t=>{if(!t)return{};try{const s=JSON.parse(t);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}},gt=(t,s={})=>{const a=Za(t);return JSON.stringify({after_shipped_hours:Number(a.after_shipped_hours||72),repeat_interval_hours:Number(a.repeat_interval_hours||24),max_attempts:Number(a.max_attempts||1),...s})},Tt=(t,s)=>{var l;const a=((l=xt[t])==null?void 0:l.label)||"自动化规则";return s?`${a} - ${s}`:a},ga=t=>{const s=(t||"").trim();return s?Object.values(xt).some(a=>s===a.label||s.startsWith(`${a.label} -`)):!0},Et=(t,s=0)=>{if(t==="review_missing_timeout")return[{action_type:"send_text",message_template:Pi,enabled:!0,sort_order:1}];const a={action_type:"send_card",card_id:s,delivery_count:1,enabled:!0,sort_order:1};return t==="order_paid"?[a,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[a]},Ti=t=>{var a,l;if(t.trigger_type==="review_missing_timeout")return((l=(a=t.actions)==null?void 0:a.find(n=>n.action_type==="send_text"))==null?void 0:l.message_template)||"发送求评价文案";const s=(t.actions||[]).filter(n=>n.action_type==="send_card");return s.length?s.map(n=>n.card_name||`卡密 ${n.card_id}`).join(" / "):"未配置卡密库存"},ba=(t,s=!1)=>{const a={blue:s?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:s?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:s?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return a[t]||a.blue},Ei=t=>t?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Ht=t=>(t==null?void 0:t.nickname)||(t==null?void 0:t.remark)||(t==null?void 0:t.id)||"未知账号",Di=t=>t===!0||t===1||t==="1",$i=({initialDeliveryTarget:t,onDeliveryTargetHandled:s})=>{var Qe,zt,Ut;const[a,l]=r.useState("automation"),[n,c]=r.useState(""),[u,p]=r.useState(""),[m,f]=r.useState(""),[x,h]=r.useState(""),[_,S]=r.useState("all"),[q,w]=r.useState(1),[O,P]=r.useState(10),G=Oi({activeTab:a,selectedAccountId:n,automationTriggerFilter:x,automationStatusFilter:_,debouncedAutomationSearch:m,automationPage:q,automationPageSize:O,setSelectedAccountId:c,onAutomationPageChange:w}),{automationRules:H,automationIssues:X,replyRules:y,defaultReplies:j,accounts:z,cards:A,items:F,loading:d,setLoading:B,automationTotal:Z,automationTotalPages:M,automationTriggerCounts:b,setAutomationRules:k,setCards:D,setItems:C,loadReferenceData:W,loadAutomationRules:K,loadReplyRules:N,loadDefaultReplies:ee,refresh:be}=G,[U,re]=r.useState(!1),[ge,$]=r.useState(!1),[L,V]=r.useState(!1),[Y,se]=r.useState(ps),[ue,ve]=r.useState(ps),[R,T]=r.useState(ps),[g,le]=r.useState(null),[oe,ne]=r.useState(null),[de,Se]=r.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""});z.find(i=>i.id===n),r.useEffect(()=>{const i=window.setTimeout(()=>{w(1),f(u.trim())},300);return(()=>window.clearTimeout(i))},[u]),r.useEffect(()=>{W().catch(i=>console.error("加载规则参考数据失败",i))},[W]),r.useEffect(()=>{be().catch(i=>console.error("刷新规则页面失败",i))},[be]);const Ee=r.useMemo(()=>H.filter(i=>!n||i.cookie_id===n),[H,n]),Te=r.useMemo(()=>Ri(X,n),[X,n]),Ue=r.useMemo(()=>z.filter(i=>!n||i.id===n),[z,n]),Me=r.useMemo(()=>{if(M<=1)return[];const i=Math.max(1,Math.min(q-2,M-4)),I=Math.min(M,i+4);return Array.from({length:I-i+1},(te,he)=>i+he)},[q,M]),Be=!!(u.trim()||x||_!=="all"),Je=()=>{p(""),f(""),h(""),S("all"),w(1)},He=r.useMemo(()=>{const i=(g==null?void 0:g.cookie_id)||n;return F.filter(I=>I.cookie_id===i)},[g==null?void 0:g.cookie_id,F,n]),we=r.useMemo(()=>{if(!(!(g!=null&&g.cookie_id)||!(g!=null&&g.item_id)))return F.find(i=>i.cookie_id===g.cookie_id&&i.item_id===g.item_id)},[g==null?void 0:g.cookie_id,g==null?void 0:g.item_id,F]),pe=Di(we==null?void 0:we.is_multi_spec),Ke=(g==null?void 0:g.trigger_type)||"order_paid",it=xt[Ke],tt=Za(g==null?void 0:g.config_json),Ve=r.useCallback((i="order_paid",I=n,te="")=>{const he=F.find($e=>$e.cookie_id===I&&$e.item_id===te),Ie=(he==null?void 0:he.item_title)||te;return{name:Tt(i,Ie),trigger_type:i,cookie_id:I,item_id:te,item_title:(he==null?void 0:he.item_title)||"",item_keyword:Ie,card_group_id:0,priority:100,enabled:!0,config_json:i==="review_missing_timeout"?gt():"{}",actions:Et(i),variants:i==="review_missing_timeout"?[]:[Pt()]}},[F,n]),Ge=r.useCallback(i=>{var te,he;const I=i.trigger_type||"order_paid";le({...i,trigger_type:I,config_json:I==="review_missing_timeout"?gt(i.config_json):i.config_json||"{}",actions:(te=i.actions)!=null&&te.length?i.actions.map(Ie=>({...Ie})):Et(I,i.card_group_id),variants:(he=i.variants)!=null&&he.length?i.variants.map(Ie=>({...Ie})):I==="review_missing_timeout"?[]:[Pt()]}),re(!0)},[]);r.useEffect(()=>{if(!t)return;let i=!1;return(async()=>{l("automation"),c(t.cookieId),B(!0);try{const[te,he,Ie]=await Promise.all([Ss(),Lt(),Ms().catch(Re=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",Re),[]))]);if(i)return;k(te),C(he),D(Ie);const $e=te.find(Re=>Re.cookie_id===t.cookieId&&Re.item_id===t.itemId&&Re.trigger_type==="order_paid");if($e)Ge($e);else{const Re=he.find(ct=>ct.cookie_id===t.cookieId&&ct.item_id===t.itemId);le({...Ve("order_paid",t.cookieId,t.itemId),item_title:(Re==null?void 0:Re.item_title)||"",item_keyword:(Re==null?void 0:Re.item_title)||t.itemId,name:Tt("order_paid",(Re==null?void 0:Re.item_title)||t.itemId)}),re(!0)}}catch(te){console.error("打开商品自动化规则失败",te),alert("无法加载该商品的自动化规则")}finally{i||(B(!1),s==null||s())}})(),(()=>{i=!0})},[Ve,t,s,Ge]);const ot=(i="order_paid")=>{if(!n){alert("请先选择账号");return}le(Ve(i)),re(!0)},pt=i=>{var he,Ie,$e,Re,ct;if(!g)return;const I=((Ie=(he=g.variants)==null?void 0:he.find(jt=>jt.card_id))==null?void 0:Ie.card_id)||((Re=($e=g.actions)==null?void 0:$e.find(jt=>jt.action_type==="send_card"))==null?void 0:Re.card_id)||g.card_group_id||0,te=(we==null?void 0:we.item_title)||g.item_title||g.item_id||"";le({...g,trigger_type:i,name:ga(g.name)?Tt(i,te):g.name,card_group_id:I,config_json:i==="review_missing_timeout"?gt(g.config_json):"{}",actions:Et(i,I),variants:i==="review_missing_timeout"?[]:(ct=g.variants)!=null&&ct.length?g.variants:[{...Pt(),card_id:I}]})},ht=i=>{if(!g)return;const I=F.find(he=>he.cookie_id===(g.cookie_id||n)&&he.item_id===i),te=(I==null?void 0:I.item_title)||i;le({...g,item_id:i,item_title:(I==null?void 0:I.item_title)||"",item_keyword:te,name:ga(g.name)?Tt(Ke,te):g.name})},J=(Qe=g==null?void 0:g.variants)!=null&&Qe.length?g.variants:[Pt()],ie=(i,I)=>{var he;if(!g)return;const te=J.map((Ie,$e)=>$e===i?{...Ie,...I}:Ie);le({...g,variants:te,card_group_id:((he=te[0])==null?void 0:he.card_id)||0})},v=()=>{if(!g)return;const i=J[J.length-1];le({...g,variants:[...J,{...Pt(),spec_name:pe&&(i==null?void 0:i.spec_name)||"",spec_value:pe&&(i==null?void 0:i.spec_value)||""}]})},E=async()=>{var Ie,$e,Re,ct,jt;if(!g||Y.submitting)return;const i=g.trigger_type||"order_paid";if(!g.cookie_id){alert("请选择账号");return}const I=(Ie=g.variants)!=null&&Ie.length?g.variants:[];if(i!=="review_missing_timeout"){if(!I.length||I.some(qe=>!qe.card_id)){alert(i==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");return}if(pe&&I.some(qe=>!qe.spec_name.trim()||!qe.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}}if(i==="review_missing_timeout"&&!(((Re=($e=g.actions)==null?void 0:$e.find(nr=>nr.action_type==="send_text"))==null?void 0:Re.message_template)||"").trim()){alert("请填写求评价文案");return}const te=i==="review_missing_timeout"?[]:I.map(qe=>({...qe,spec_name:pe?qe.spec_name.trim():"",spec_value:pe?qe.spec_value.trim():"",delivery_count:Math.max(1,Number(qe.delivery_count)||1),enabled:qe.enabled!==!1}));se(hs(Y));let he=!1;try{await sa({...g,trigger_type:i,name:(g.name||"").trim()||Tt(i,(we==null?void 0:we.item_title)||g.item_id||""),config_json:i==="review_missing_timeout"?gt(g.config_json):g.config_json||"{}",actions:(ct=g.actions)!=null&&ct.length?g.actions:Et(i,((jt=te[0])==null?void 0:jt.card_id)||g.card_group_id||0),variants:te}),re(!1),await Promise.all([K(),W()]),alert("保存成功"),he=!0}catch(qe){console.error("保存自动化规则失败:",qe),alert("保存失败:"+qe.message)}finally{se(qe=>gs(qe,he))}},ae=async i=>{if(confirm("确定删除该自动化规则吗?"))try{await Ul(i),await K(),alert("删除成功")}catch(I){alert("删除失败:"+I.message)}},ce=async i=>{try{await sa({...i,enabled:!i.enabled}),await K()}catch(I){alert("操作失败:"+I.message)}},fe=async(i,I)=>{if(confirm(I==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":I==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Jl(i,I),await K()}catch(he){alert("处理失败:"+he.message)}},De=async(i,I)=>{if(confirm(I==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Gl(i,I),await K()}catch(te){alert("处理失败:"+te.message)}},Ne=()=>{if(!n){alert("请先选择账号");return}ne({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),$(!0)},Pe=async()=>{var te,he,Ie;if(!oe||!n||ue.submitting)return;const i=oe.type==="image"?!!((te=oe.image_url)!=null&&te.trim()):!!((he=oe.reply_content)!=null&&he.trim());if(!((Ie=oe.keyword)!=null&&Ie.trim())||!i){alert("请填写关键词和回复内容");return}ve(hs(ue));let I=!1;try{await Hl({...oe,match_type:"fuzzy",enabled:!0},n),$(!1),await N(),alert("保存成功"),I=!0}catch($e){alert("保存失败:"+$e.message)}finally{ve($e=>gs($e,I))}},me=async i=>{if(!(!n||!confirm("确定删除该回复规则吗?")))try{await Zl(i,n),await N(),alert("删除成功")}catch(I){alert("删除失败:"+I.message)}},o=async(i=n)=>{if(!i){alert("请先选择账号");return}try{const I=await cn(i);Se({cookie_id:i,enabled:I.enabled,reply_content:I.reply_content,reply_once:I.reply_once,reply_image_url:I.reply_image_url||""})}catch{Se({cookie_id:i,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}V(!0)},Q=async()=>{if(R.submitting)return;if(!de.cookie_id){alert("请先选择账号");return}if(de.enabled&&!de.reply_content.trim()&&!de.reply_image_url.trim()){alert("启用默认回复时,请填写回复内容或图片 URL");return}T(hs(R));let i=!1;try{await dn(de.cookie_id,{enabled:de.enabled,reply_content:de.reply_content,reply_once:de.reply_once,reply_image_url:de.reply_image_url}),V(!1),await ee(),alert("保存成功"),i=!0}catch(I){alert("保存失败:"+I.message)}finally{T(I=>gs(I,i))}},xe=async i=>{if(confirm("确定删除该账号默认回复吗?"))try{await xn(i),await ee(),alert("删除成功")}catch(I){alert("删除失败:"+I.message)}},Le=async i=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await mn(i),alert("清空成功")}catch(I){alert("清空失败:"+I.message)}},st=a==="automation"?"新建自动化":a==="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:(i=>{c(i.target.value),w(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),z.map(i=>e.jsx("option",{value:i.id,children:Ht(i)},i.id))]}),e.jsxs("button",{onClick:be,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(We,{className:`w-4 h-4 ${d?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:a==="automation"?(()=>ot("order_paid")):a==="reply"?Ne:(()=>void o()),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(nt,{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:js},{id:"reply",label:"关键词回复",icon:$t},{id:"default",label:"账号默认回复",icon:wt}].map(i=>{const I=i.icon;return e.jsxs("button",{onClick:(()=>l(i.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${a===i.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"}),i.label]},i.id)})}),a==="automation"&&(Te.runs.length>0||Te.pending_tasks.length>0)&&e.jsx(Ai,{runs:Te.runs,pendingTasks:Te.pending_tasks,onResolveRun:((i,I)=>void fe(i,I)),onResolveDeferredTask:((i,I)=>void De(i,I))}),a==="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:Qt.map(i=>{const I=xt[i],te=I.icon;return e.jsx("button",{type:"button",onClick:(()=>ot(i)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${ba(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(te,{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})]})]})},i)})})]}),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:["共 ",Z," 条"]})]}),e.jsx("div",{className:"space-y-3",children:Qt.map(i=>{const I=xt[i],te=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(te,{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:b[i]||0})]},i)})})]})]}),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(St,{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:u,onChange:(i=>{p(i.target.value),w(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(Oa,{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:(i=>{h(i.target.value),w(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:"全部自动化类型"}),Qt.map(i=>e.jsx("option",{value:i,children:xt[i].shortLabel},i))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:_,onChange:(i=>{S(i.target.value),w(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:"已禁用"})]}),Be&&e.jsx("button",{type:"button",onClick:Je,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(ke,{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:["找到 ",Z," 条规则"]}),d&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(We,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),d&&Ee.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(We,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):Ee.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(js,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:Be?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:Be?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):Ee.map(i=>{const I=xt[i.trigger_type],te=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 ${ba(I.accent,!0)}`,children:e.jsx(te,{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:i.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Ei(i.enabled)}`,children:i.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:i.item_title||i.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:Ti(i)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>Ge(i)),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(kt,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>ce(i)),className:`px-4 py-2 rounded-xl text-sm font-bold ${i.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:i.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>ae(i.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ze,{className:"w-4 h-4"})})]})]})},i.id)}),Z>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:["第 ",q," / ",Math.max(M,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:(i=>{P(Number(i.target.value)),w(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(i=>e.jsxs("option",{value:i,children:[i," 条/页"]},i))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:q<=1||d,onClick:(()=>w(i=>Math.max(1,i-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(Es,{className:"h-4 w-4"})}),Me.map(i=>e.jsx("button",{type:"button",disabled:d,onClick:(()=>w(i)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${i===q?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${i} 页`,"aria-current":i===q?"page":void 0,children:i},i)),e.jsx("button",{type:"button",disabled:q>=M||d,onClick:(()=>w(i=>Math.min(M,i+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(Ts,{className:"h-4 w-4"})})]})]})]})]}),a==="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(ut,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[y.map(i=>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:["“",i.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:i.type==="image"&&i.image_url?i.image_url:i.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:(()=>{ne({...i}),$(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>me(i.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ze,{className:"w-5 h-5"})})]})]},i.id)),y.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),a==="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(ut,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Ue.map(i=>{const I=j[i.id],te=!!(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 ${te?"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 ${te?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(wt,{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:Ht(i)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${te?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:te?"已启用":"未启用"}),(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:te?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 o(i.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),te&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void Le(i.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 xe(i.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ze,{className:"w-5 h-5"})})]})]})]},i.id)}),Ue.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),U&&g&&Oe.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:g.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:it.description})]}),e.jsx("button",{onClick:(()=>re(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(ke,{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:Qt.map(i=>{const I=xt[i],te=I.icon,he=Ke===i;return e.jsx("button",{type:"button",onClick:(()=>pt(i)),className:`w-full rounded-2xl p-4 text-left border transition-all ${he?"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(te,{className:`w-5 h-5 mt-0.5 ${he?"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 ${he?"text-gray-500":"text-gray-400"}`,children:I.description})]})]})},i)})}),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:it.flow.map((i,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:i})]},i))})]})]}),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(vs,{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:g.name||"",onChange:(i=>le({...g,name:i.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:g.cookie_id||"",onChange:(i=>le({...g,cookie_id:i.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:"选择账号"}),z.map(i=>e.jsx("option",{value:i.id,children:Ht(i)},i.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:g.item_id||"",onChange:(i=>ht(i.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),He.map(i=>e.jsx("option",{value:i.item_id,children:i.item_title||i.item_id},`${i.cookie_id}-${i.item_id}`))]})]})]}),we&&Ke!=="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:we.item_title||we.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${pe?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:pe?"多规格商品":"普通商品"}),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:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),Ke!=="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(Sr,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:Ke==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:pe?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:v,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(nt,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:J.map((i,I)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${pe?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[pe&&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:i.spec_name,onChange:(te=>ie(I,{spec_name:te.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:i.spec_value,onChange:(te=>ie(I,{spec_value:te.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:i.card_id||"",onChange:(te=>ie(I,{card_id:Number(te.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),A.filter(te=>te.enabled&&te.type!=="api").map(te=>e.jsx("option",{value:te.id,children:te.name},te.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:i.delivery_count,onChange:(te=>ie(I,{delivery_count:Math.max(1,Number(te.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:i.delay_override===!0,onChange:(te=>ie(I,{delay_override:te.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),i.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:i.delay_seconds||0,onChange:(te=>ie(I,{delay_seconds:Math.max(0,Number(te.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:i.delay_override?`本动作延时 ${i.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:J.length===1,onClick:(()=>le({...g,variants:J.filter((te,he)=>he!==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(Ze,{className:"w-4 h-4"})})]},i.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(Pa,{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(tt.after_shipped_hours||72),onChange:(i=>le({...g,config_json:gt(g.config_json,{after_shipped_hours:Math.max(1,Number(i.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(tt.repeat_interval_hours||24),onChange:(i=>le({...g,config_json:gt(g.config_json,{repeat_interval_hours:Math.max(1,Number(i.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(tt.max_attempts||1),onChange:(i=>le({...g,config_json:gt(g.config_json,{max_attempts:Math.max(1,Number(i.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:((Ut=(zt=g.actions)==null?void 0:zt.find(i=>i.action_type==="send_text"))==null?void 0:Ut.message_template)||"",onChange:(i=>{var I;return le({...g,actions:((I=g.actions)!=null&&I.length?g.actions:Et("review_missing_timeout")).map(te=>te.action_type==="send_text"?{...te,message_template:i.target.value}:te)})}),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:g.priority||100,onChange:(i=>le({...g,priority:Number(i.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:g.enabled!==!1,onChange:(i=>le({...g,enabled:i.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:(()=>re(!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:E,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),ge&&oe&&Oe.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:oe.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>$(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:oe.item_id||"",onChange:(i=>ne({...oe,item_id:i.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),F.filter(i=>!n||i.cookie_id===n).map(i=>e.jsx("option",{value:i.item_id,children:i.item_title||i.item_id},`${i.cookie_id}-${i.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:oe.type||"text",onChange:(i=>{const I=i.target.value;ne({...oe,type:I,reply_content:I==="text"?oe.reply_content:"",image_url:I==="image"?oe.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:oe.keyword||"",onChange:(i=>ne({...oe,keyword:i.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),oe.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:oe.image_url||"",onChange:(i=>ne({...oe,image_url:i.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:oe.reply_content||"",onChange:(i=>ne({...oe,reply_content:i.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:(()=>$(!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:Pe,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ss,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),L&&Oe.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:(()=>V(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(ke,{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:de.cookie_id,onChange:(i=>Se({...de,cookie_id:i.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),z.map(i=>e.jsx("option",{value:i.id,children:Ht(i)},i.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:(()=>Se({...de,enabled:!de.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${de.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 ${de.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:de.reply_content,onChange:(i=>Se({...de,reply_content:i.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:de.reply_image_url,onChange:(i=>Se({...de,reply_image_url:i.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:de.reply_once,onChange:(i=>Se({...de,reply_once:i.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>V(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Q,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})},qs=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],Is=(t,s)=>{if(typeof t=="boolean")return t;if(typeof t=="string"){if(["true","1","yes","on"].includes(t.toLowerCase()))return!0;if(["false","0","no","off"].includes(t.toLowerCase()))return!1}return s},Ya=t=>{const s=Object.prototype.hasOwnProperty.call(t,"use_custom_smtp"),a=qs.some(l=>String(t[l]??"").trim()!=="");return{...t,use_custom_smtp:s?Is(t.use_custom_smtp,!1):a}},Xa=(t,s)=>{const a={...t,use_custom_smtp:!0};for(const l of qs)String(a[l]??"").trim()===""&&s[l]!==void 0&&(a[l]=s[l]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=Is(a.smtp_use_tls,!0),a.smtp_use_ssl=Is(a.smtp_use_ssl,!1),a},er=t=>{const s=Ya(t),a={to_email:String(s.to_email??"").trim(),use_custom_smtp:s.use_custom_smtp===!0};if(a.use_custom_smtp)for(const l of qs)a[l]=s[l];return a},Ct={bark:{label:"Bark",icon:Rt,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:$t,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:$t,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:$t,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:Lr,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:ss,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:Ta,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},tr=[{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:"后台任务或系统级异常"}],fa=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Mi=t=>!t||t.length===0?"全部事件":t.map(s=>{var a;return((a=tr.find(l=>l.value===s))==null?void 0:a.label)||s}).join("、"),qi=(t,s)=>{const a=t.type==="email"?Ya({...t.config||{}}):null,l=a?a.use_custom_smtp===!0?Xa(a,s):a:{...t.config||{}};return{name:t.name,type:t.type,enabled:t.enabled,config:l,event_types:t.event_types||[]}},Bi=t=>{const a=Ct[t.type].fields.find(l=>l.required&&!String(t.config[l.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!t.name.trim())return"请填写渠道名称";if(t.type==="email"){const l=er(t.config);if(l.use_custom_smtp){const c=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([u])=>!String(l[u]||"").trim());if(c)return`请填写 ${c[1]}`}}return""},Fi=t=>({name:t.name.trim(),type:t.type,config:t.type==="email"?er(t.config):t.config,event_types:t.event_types,enabled:t.enabled}),Ae=(t,s)=>t===s,Dt=(t,s)=>t instanceof Error&&t.message?t.message:s,zi=({channels:t,testingId:s,onEdit:a,onDelete:l,onToggleEnabled:n,onTest:c})=>{const u=_=>t.find(S=>S.id===_.currentTarget.dataset.channelId)||null,p=_=>{const S=u(_);S&&n(S)},m=_=>{const S=u(_);S&&c(S)},f=_=>{const S=u(_);S&&a(S)},x=_=>{const S=u(_);S&&l(S)},h=_=>{const S=Ct[_.type]||Ct.webhook,q=S.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(q,{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:_.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:S.label}),!_.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:S.fields.map(w=>{var O;return(O=_.config)==null?void 0:O[w.key]}).filter(Boolean).map((w,O)=>e.jsx("span",{className:"mr-3",children:String(w).length>40?`${String(w).slice(0,40)}…`:String(w)},O))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Mi(_.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":_.id,onClick:p,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${_.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:_.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":_.id,onClick:m,disabled:s===_.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:[s===_.id?e.jsx(_e,{className:"w-3 h-3 animate-spin"}):e.jsx(ss,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":_.id,onClick:f,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(Ra,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":_.id,onClick:x,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(Ze,{className:"w-4 h-4"})})]})]},_.id)};return t.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(Rt,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:t.map(h)})},Ui=({selectedEvents:t,onToggleEvent:s})=>{const a=l=>{const n=l.currentTarget.dataset.event;n&&s(n)};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:tr.map(l=>{const n=t.includes(l.value);return e.jsxs("button",{type:"button","data-event":l.value,onClick:a,className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${n?"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 ${n?"bg-brand border-brand":"border-gray-300"}`,children:n&&e.jsx(Ye,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${n?"text-brand":"text-gray-800"}`,children:l.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:l.description})]},l.value)})})]})},Wi=({showModal:t,editing:s,form:a,setForm:l,smtp:n,showChannelSmtpPassword:c,setShowChannelSmtpPassword:u,saving:p,onClose:m,onSave:f})=>{const x=Ct[a.type],h=y=>l(j=>({...j,name:y.target.value})),_=y=>{const j=y.currentTarget.dataset.type;j&&l(z=>({...z,type:j,config:{}}))},S=y=>{const j=y.currentTarget.dataset.field;j&&l(z=>({...z,config:{...z.config,[j]:y.target.value}}))},q=()=>l(y=>({...y,config:y.config.use_custom_smtp===!0?{...y.config,use_custom_smtp:!1}:Xa(y.config,n)})),w=y=>l(j=>({...j,config:{...j.config,smtp_use_tls:y.target.checked,smtp_use_ssl:y.target.checked?!1:j.config.smtp_use_ssl}})),O=y=>l(j=>({...j,config:{...j.config,smtp_use_ssl:y.target.checked,smtp_use_tls:y.target.checked?!1:j.config.smtp_use_tls}})),P=y=>l(j=>({...j,event_types:j.event_types.includes(y)?j.event_types.filter(z=>z!==y):[...j.event_types,y]})),G=()=>l(y=>({...y,enabled:!y.enabled})),H=()=>u(y=>!y),X=(y,j)=>e.jsx("li",{children:y},j);return t?Oe.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:s?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:m,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(ke,{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:h,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(Ct).map(y=>{const j=Ct[y],z=j.icon,A=a.type===y;return e.jsxs("button",{"data-type":y,type:"button",onClick:_,className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${A?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(z,{className:`w-5 h-5 ${A?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${A?"text-brand":"text-gray-600"}`,children:j.label})]},y)})})]}),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(Rt,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",x.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:x.guide.steps.map(X)}),x.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:x.guide.urlFormat})]}),x.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",x.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:x.fields.map(y=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[y.label,y.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":y.key,type:y.type==="password"?"password":y.type==="number"?"number":"text",value:String(a.config[y.key]||""),onChange:S,placeholder:y.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),y.help&&e.jsx("p",{className:"text-xs text-gray-500",children:y.help})]},y.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:q,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:S,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:S,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:S,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:c?"text":"password",value:String(a.config.smtp_password||""),onChange:S,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:H,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:c?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:S,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:S,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:w}),"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:O}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Ui,{selectedEvents:a.event_types,onToggleEvent:P}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:G,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:m,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:f,disabled:p,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[p?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Ye,{className:"w-4 h-4"}),p?"保存中...":"保存"]})]})]})}),document.body):null},Ji=({smtp:t,setSmtp:s,smtpSaving:a,showPassword:l,setShowPassword:n,onSave:c})=>{const u=_=>{const S=_.currentTarget.dataset.field;S&&s(q=>({...q,[S]:_.target.value}))},p=_=>{s(S=>({...S,smtp_port:parseInt(_.target.value,10)||587}))},m=_=>{s(S=>({...S,smtp_use_tls:_.target.checked,smtp_use_ssl:_.target.checked?!1:S.smtp_use_ssl}))},f=_=>{s(S=>({...S,smtp_use_ssl:_.target.checked,smtp_use_tls:_.target.checked?!1:S.smtp_use_tls}))},x=_=>{s(S=>({...S,smtp_password:_.target.value}))},h=()=>n(_=>!_);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(Ta,{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:t.smtp_server||"",onChange:u,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:t.smtp_port||587,onChange:p,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:t.smtp_user||"",onChange:u,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:l?"text":"password",value:t.smtp_password||"",onChange:x,placeholder:t.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:h,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:l?e.jsx(bt,{className:"w-4 h-4"}):e.jsx(mt,{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:t.smtp_from_name||"",onChange:u,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:t.smtp_from_address||t.smtp_user||"",onChange:u,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:t.smtp_use_tls!==!1,onChange:m}),"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:t.smtp_use_ssl===!0,onChange:f}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:c,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(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},Gi=t=>{const[s,a]=r.useState([]),[l,n]=r.useState(!0),[c,u]=r.useState(!1),[p,m]=r.useState(null),[f,x]=r.useState(!1),[h,_]=r.useState(""),[S,q]=r.useState(null),[w,O]=r.useState({}),[P,G]=r.useState(!1),[H,X]=r.useState(!1),[y,j]=r.useState(!1),[z,A]=r.useState(fa),F=r.useRef(0),d=r.useRef(null),B=r.useRef(0),Z=r.useRef(null),M=r.useRef(0),b=r.useRef(null),k=r.useRef(null),D=r.useCallback((L,V)=>{q({type:L,text:V}),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{k.current=null,q(null)},3e3)},[]),C=r.useCallback(async()=>{var Y;const L=++F.current;(Y=d.current)==null||Y.abort();const V=new AbortController;d.current=V,n(!0);try{const se=await Ka({signal:V.signal});if(!Ae(L,F.current))return;a(se.data||[])}catch(se){Ae(L,F.current)&&!V.signal.aborted&&console.error("加载通知渠道失败",se)}finally{Ae(L,F.current)&&n(!1)}},[]),W=r.useCallback(async()=>{var Y;const L=++B.current;(Y=Z.current)==null||Y.abort();const V=new AbortController;Z.current=V;try{const se=await Wa({signal:V.signal});Ae(L,B.current)&&O(se||{})}catch(se){Ae(L,B.current)&&!V.signal.aborted&&console.error("加载 SMTP 配置失败",se)}},[]);r.useEffect(()=>{var L;return C(),t?W():(B.current+=1,(L=Z.current)==null||L.abort(),O({})),(()=>{var V,Y;F.current+=1,(V=d.current)==null||V.abort(),B.current+=1,(Y=Z.current)==null||Y.abort()})},[t,C,W]),r.useEffect(()=>(()=>{k.current!==null&&window.clearTimeout(k.current)}),[]);const K=r.useCallback(()=>{m(null),A(fa()),j(!1),u(!0)},[]),N=r.useCallback(L=>{m(L),A(qi(L,w)),j(!1),u(!0)},[w]),ee=r.useCallback(()=>{var L;M.current+=1,(L=b.current)==null||L.abort(),x(!1),u(!1)},[]),be=r.useCallback(async()=>{var se;const L=Bi(z);if(L){D("error",L);return}const V=++M.current;(se=b.current)==null||se.abort();const Y=new AbortController;b.current=Y,x(!0);try{const ue=Fi(z);if(p?await aa(p.id,ue,{signal:Y.signal}):await rn(ue,{signal:Y.signal}),!Ae(V,M.current)||(u(!1),await C(),!Ae(V,M.current)))return;D("success",p?"已更新":"已创建")}catch(ue){Ae(V,M.current)&&!Y.signal.aborted&&D("error",Dt(ue,"保存失败"))}finally{Ae(V,M.current)&&x(!1)}},[p,z,C,D]),U=r.useCallback(async L=>{var se;if(!confirm(`确认删除渠道「${L.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const V=++M.current;(se=b.current)==null||se.abort();const Y=new AbortController;b.current=Y;try{if(await ln(L.id,{signal:Y.signal}),!Ae(V,M.current)||(await C(),!Ae(V,M.current)))return;D("success","已删除")}catch(ue){Ae(V,M.current)&&!Y.signal.aborted&&D("error",Dt(ue,"删除失败"))}},[C,D]),re=r.useCallback(async L=>{var se;const V=++M.current;(se=b.current)==null||se.abort();const Y=new AbortController;b.current=Y;try{if(await aa(L.id,{enabled:!L.enabled},{signal:Y.signal}),!Ae(V,M.current))return;a(ue=>ue.map(ve=>ve.id===L.id?{...ve,enabled:!ve.enabled}:ve))}catch(ue){Ae(V,M.current)&&!Y.signal.aborted&&D("error",Dt(ue,"切换失败"))}},[D]),ge=r.useCallback(async L=>{var se;_(L.id);const V=++M.current;(se=b.current)==null||se.abort();const Y=new AbortController;b.current=Y;try{await on(L.id,{signal:Y.signal}),Ae(V,M.current)&&D("success","测试通知已发送,请检查对应渠道")}catch(ue){Ae(V,M.current)&&!Y.signal.aborted&&D("error",Dt(ue,"发送失败"))}finally{Ae(V,M.current)&&_("")}},[D]),$=r.useCallback(async()=>{var Y;const L=++B.current;(Y=Z.current)==null||Y.abort();const V=new AbortController;Z.current=V,G(!0);try{const se={smtp_server:w.smtp_server||"",smtp_port:w.smtp_port||587,smtp_user:w.smtp_user||"",smtp_from_name:w.smtp_from_name||"",smtp_from_address:w.smtp_from_address||w.smtp_user||"",smtp_use_tls:w.smtp_use_tls!==!1,smtp_use_ssl:w.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(w,"smtp_password")&&(se.smtp_password=w.smtp_password),await Ja(se,{signal:V.signal}),Ae(L,B.current)&&D("success","SMTP 配置已保存")}catch(se){Ae(L,B.current)&&!V.signal.aborted&&D("error",Dt(se,"保存失败"))}finally{Ae(L,B.current)&&G(!1)}},[D,w]);return{channels:s,loading:l,showModal:c,editing:p,saving:f,testingId:h,toast:S,smtp:w,smtpSaving:P,showSmtpPassword:H,showChannelSmtpPassword:y,form:z,setForm:A,setSmtp:O,setShowSmtpPassword:X,setShowChannelSmtpPassword:j,loadChannels:C,openCreate:K,openEdit:N,closeModal:ee,showToast:D,handleSave:be,handleDelete:U,handleToggleEnabled:re,handleTest:ge,handleSaveSmtp:$}},Ki=({isAdmin:t=!1})=>{const s=Gi(t);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:s.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(We,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:s.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(nt,{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(Rt,{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:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),s.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(_e,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(zi,{channels:s.channels,testingId:s.testingId,onEdit:s.openEdit,onDelete:s.handleDelete,onToggleEnabled:s.handleToggleEnabled,onTest:s.handleTest}),t&&e.jsx(Ji,{smtp:s.smtp,setSmtp:s.setSmtp,smtpSaving:s.smtpSaving,showPassword:s.showSmtpPassword,setShowPassword:s.setShowSmtpPassword,onSave:s.handleSaveSmtp}),e.jsx(Wi,{showModal:s.showModal,editing:s.editing,form:s.form,setForm:s.setForm,smtp:s.smtp,showChannelSmtpPassword:s.showChannelSmtpPassword,setShowChannelSmtpPassword:s.setShowChannelSmtpPassword,saving:s.saving,onClose:s.closeModal,onSave:s.handleSave}),s.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 ${s.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[s.toast.type==="success"?e.jsx(Ye,{className:"w-4 h-4"}):e.jsx(ke,{className:"w-4 h-4"}),s.toast.text]})]})},sr=[["尊嘟假嘟","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"]],Vi=t=>t,Qi=new Map(sr.map(([t,s])=>[t,s])),Hi=t=>t.split(/(\[[^\]]+\])/g).map((s,a)=>{const l=s.startsWith("[")?Qi.get(s.slice(1,-1)):void 0;return l?e.jsx("img",{src:l,alt:s,title:s,className:"mx-0.5 inline-block h-7 w-7 align-middle"},a):e.jsx(As.Fragment,{children:s},a)}),Zi=(t,s,a)=>{const l=s.trim().toLowerCase();return t.filter(n=>a&&n.unread_count<=0?!1:l?[n.buyer_name,n.buyer_id,n.item_title,n.last_message].some(c=>(c||"").toLowerCase().includes(l)):!0)},Yi=(t,s)=>{const a=new Set(t.map(l=>l.message_key));return[...s.filter(l=>!a.has(l.message_key)),...t]},fs=(t,s)=>{const a=t.findIndex(l=>l.message_key===s.message_key);return a<0?[...t,s]:t.map((l,n)=>n===a?s:l)},Fe=(t,s,a)=>t===s&&!a.aborted,_t=t=>t instanceof Error&&t.message==="请求已取消",Xi=t=>{if(!t)return"";const s=new Date(t<1e10?t*1e3:t),a=new Date;return s.toDateString()===a.toDateString()?s.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):s.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},eo=t=>new Date(t<1e10?t*1e3:t).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),to=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(""),[n,c]=r.useState({}),[u,p]=r.useState(""),[m,f]=r.useState([]),[x,h]=r.useState(""),[_,S]=r.useState(!1),[q,w]=r.useState(""),[O,P]=r.useState(!0),[G,H]=r.useState(!1),[X,y]=r.useState(!1),[j,z]=r.useState(!1),[A,F]=r.useState(),[d,B]=r.useState({}),[Z,M]=r.useState({}),[b,k]=r.useState(!1),[D,C]=r.useState(!1),[W,K]=r.useState(!1),[N,ee]=r.useState(""),[be,U]=r.useState("connecting"),[re,ge]=r.useState(null),[$,L]=r.useState(null),V=r.useRef(""),Y=r.useRef(""),se=r.useRef(null),ue=r.useRef({accountID:"",chatID:""}),ve=r.useRef(!0),R=r.useRef(!1),T=r.useRef(null),g=r.useRef(new Set),le=r.useRef(0),oe=r.useRef(null),ne=r.useRef(0),de=r.useRef(null),Se=r.useRef(0),Ee=r.useRef(null),Te=r.useRef(0),Ue=r.useRef(null);r.useEffect(()=>{V.current=a},[a]),r.useEffect(()=>{Y.current=u},[u]);const Me=r.useCallback(async J=>{var E;const ie=++le.current;(E=oe.current)==null||E.abort();const v=new AbortController;oe.current=v;try{const ae=await is(J,void 0,{signal:v.signal},!0);return Fe(le.current,ie,v.signal)?(c(ce=>({...ce,[J]:ae.sessions})),B(ce=>({...ce,[J]:ae.next_cursor})),M(ce=>({...ce,[J]:ae.has_more})),ae.sessions):[]}catch(ae){return Fe(le.current,ie,v.signal)&&!_t(ae)&&ee(ae instanceof Error?ae.message:"同步会话失败"),[]}},[]);r.useEffect(()=>{const J=new AbortController;return(async()=>{var v;P(!0);try{const[E,ae]=await Promise.all([Ft({signal:J.signal}),Cs({signal:J.signal})]),fe=E.map(me=>{var o,Q;return{...me,runtime_state:((o=ae[me.id])==null?void 0:o.state)||(me.enabled?"connecting":"disabled"),runtime_connected:((Q=ae[me.id])==null?void 0:Q.connected)===!0}}).filter(me=>me.enabled),De=await Promise.all(fe.map(async me=>[me.id,await is(me.id,void 0,{signal:J.signal})]));if(J.signal.aborted)return;s(fe),c(Object.fromEntries(De.map(([me,o])=>[me,o.sessions]))),B(Object.fromEntries(De.map(([me,o])=>[me,o.next_cursor]))),M(Object.fromEntries(De.map(([me,o])=>[me,o.has_more])));const Ne=window.localStorage.getItem("ydisks.chat.account.v1")||"",Pe=fe.some(me=>me.id===Ne)?Ne:((v=fe[0])==null?void 0:v.id)||"";l(Pe)}catch(E){J.signal.aborted||ee(E instanceof Error?E.message:"加载聊天数据失败")}finally{J.signal.aborted||P(!1)}})(),(()=>J.abort())},[]),r.useEffect(()=>{let J=!1,ie=0,v=null;const E=async()=>{v=new AbortController;try{const ae=await Cs({signal:v.signal,timeoutMs:1e4});J||s(ce=>ce.map(fe=>{var De,Ne;return{...fe,runtime_state:((De=ae[fe.id])==null?void 0:De.state)||fe.runtime_state,runtime_connected:((Ne=ae[fe.id])==null?void 0:Ne.connected)??fe.runtime_connected}}))}catch{}finally{J||(ie=window.setTimeout(E,3e3))}};return ie=window.setTimeout(E,3e3),(()=>{J=!0,window.clearTimeout(ie),v==null||v.abort()})},[]),r.useEffect(()=>{if(!a)return;window.localStorage.setItem("ydisks.chat.account.v1",a);const J=n[a]||[];p(ie=>{var v;return J.some(E=>E.chat_id===ie)?ie:((v=J[0])==null?void 0:v.chat_id)||""})},[a,n]),r.useEffect(()=>{!a||g.current.has(a)||(g.current.add(a),Me(a))},[a,Me]),r.useEffect(()=>{var v;if(!a||!u){f([]);return}const J=++ne.current;(v=de.current)==null||v.abort();const ie=new AbortController;return de.current=ie,H(!0),Promise.all([Ys(a,u,void 0,void 0,{signal:ie.signal}),Xs(a,u,{signal:ie.signal})]).then(([E])=>{Fe(ne.current,J,ie.signal)&&(f(E.messages),z(E.has_more),F(E.next_cursor),E.session&&c(ae=>({...ae,[a]:(ae[a]||[]).map(ce=>{var fe;return ce.chat_id===((fe=E.session)==null?void 0:fe.chat_id)?E.session:ce})})),c(ae=>({...ae,[a]:(ae[a]||[]).map(ce=>ce.chat_id===u?{...ce,unread_count:0}:ce)})))}).catch(E=>{Fe(ne.current,J,ie.signal)&&!_t(E)&&ee(E instanceof Error?E.message:"加载消息失败")}).finally(()=>{Fe(ne.current,J,ie.signal)&&H(!1)}),(()=>ie.abort())},[a,u]),r.useEffect(()=>{var J;(J=Ee.current)==null||J.abort(),Se.current+=1},[a]),r.useEffect(()=>{var J;(J=Ue.current)==null||J.abort(),Te.current+=1},[a,u]),r.useEffect(()=>(()=>{var J,ie,v,E;(J=oe.current)==null||J.abort(),(ie=de.current)==null||ie.abort(),(v=Ee.current)==null||v.abort(),(E=Ue.current)==null||E.abort()}),[]);const Be=r.useCallback(async()=>{var ae;if(!a||!u||X||!j)return;const J=se.current,ie=(J==null?void 0:J.scrollHeight)||0,v=ne.current,E=new AbortController;R.current=!0,y(!0),ee("");try{const ce=(ae=m[0])==null?void 0:ae.id,fe=await Ys(a,u,A,ce,{signal:E.signal});if(!Fe(ne.current,v,E.signal))return;f(De=>Yi(De,fe.messages)),z(fe.has_more),F(fe.next_cursor),requestAnimationFrame(()=>{J&&(J.scrollTop+=J.scrollHeight-ie)})}catch(ce){R.current=!1,_t(ce)||ee(ce instanceof Error?ce.message:"加载历史消息失败")}finally{y(!1)}},[a,u,j,A,m,X]);r.useEffect(()=>{let J=!1,ie=0,v=0,E=null;const ae=()=>{if(J)return;U("connecting");const ce=window.location.protocol==="https:"?"wss:":"ws:";E=new WebSocket(`${ce}//${window.location.host}/api/v1/chat/ws`),E.onopen=()=>{v=0,U("online")},E.onmessage=fe=>{try{const Ne=JSON.parse(fe.data).message;if(!Ne)return;const Pe=Ne.account_id;c(me=>{const o=me[Pe]||[];return o.some(xe=>xe.chat_id===Ne.chat_id)?{...me,[Pe]:o.map(xe=>xe.chat_id===Ne.chat_id?{...xe,last_message:Ne.content,last_message_at:Ne.sent_at,unread_count:Ne.direction==="incoming"&&(V.current!==Pe||Y.current!==Ne.chat_id)?xe.unread_count+1:xe.unread_count}:xe).sort((xe,Le)=>Le.last_message_at-xe.last_message_at)}:(Me(Pe),me)}),V.current===Pe&&Y.current===Ne.chat_id&&(f(me=>fs(me,Ne)),Ne.direction==="incoming"&&Xs(Pe,Ne.chat_id))}catch{}},E.onclose=()=>{if(J)return;U("offline");const fe=Math.min(15e3,1e3*2**Math.min(v++,4));ie=window.setTimeout(ae,fe)},E.onerror=()=>E==null?void 0:E.close()};return ae(),(()=>{J=!0,window.clearTimeout(ie),E==null||E.close()})},[Me]);const Je=r.useCallback(()=>{const J=se.current;if(!J)return;const ie=J.scrollHeight-J.scrollTop-J.clientHeight;ve.current=ie<=48},[]);r.useLayoutEffect(()=>{const J=ue.current.accountID!==a||ue.current.chatID!==u;ue.current={accountID:a,chatID:u},J&&(ve.current=!0);const ie=se.current;if(ie){if(R.current){R.current=!1;return}(G||ve.current)&&(ie.scrollTop=ie.scrollHeight)}},[a,u,m,G]);const He=t.find(J=>J.id===a),we=n[a]||[],pe=we.find(J=>J.chat_id===u),Ke=r.useMemo(()=>Zi(we,x,_),[we,x,_]),it=r.useCallback(J=>(n[J]||[]).reduce((ie,v)=>ie+v.unread_count,0),[n]),tt=r.useCallback(async()=>{var E;if(!a||b||!Z[a])return;const J=++Se.current;(E=Ee.current)==null||E.abort();const ie=new AbortController;Ee.current=ie;const v=a;k(!0),ee("");try{const ae=await is(v,d[v],{signal:ie.signal},!0);if(!Fe(Se.current,J,ie.signal))return;c(ce=>({...ce,[v]:ae.sessions})),B(ce=>({...ce,[v]:ae.next_cursor})),M(ce=>({...ce,[v]:ae.has_more}))}catch(ae){Fe(Se.current,J,ie.signal)&&!_t(ae)&&ee(ae instanceof Error?ae.message:"加载历史联系人失败")}finally{Fe(Se.current,J,ie.signal)&&k(!1)}},[a,d,b,Z]),Ve=r.useCallback(async(J,ie)=>{var ae;if(!pe||!a||W)return;const v=++Te.current;(ae=Ue.current)==null||ae.abort();const E=new AbortController;Ue.current=E,K(!0),ee("");try{const ce=await el({account_id:a,chat_id:pe.chat_id,buyer_id:pe.buyer_id,buyer_name:pe.buyer_name,item_id:pe.item_id,item_title:pe.item_title,text:J},{signal:E.signal});if(!Fe(Te.current,v,E.signal))return;w(""),ge(null),f(fe=>fs(fe,ce.message))}catch(ce){Fe(Te.current,v,E.signal)&&(ie&&ge(J),_t(ce)||ee(ce instanceof Error?ce.message:"消息发送失败"))}finally{Fe(Te.current,v,E.signal)&&K(!1)}},[a,pe,W]),Ge=r.useCallback(async(J,ie)=>{var ae;if(!pe||!a||W)return;const v=++Te.current;(ae=Ue.current)==null||ae.abort();const E=new AbortController;Ue.current=E,K(!0),ee("");try{const ce=await tl({account_id:a,chat_id:pe.chat_id,buyer_id:pe.buyer_id,buyer_name:pe.buyer_name,buyer_avatar_url:pe.buyer_avatar_url,item_id:pe.item_id,item_title:pe.item_title,image:J},{signal:E.signal});if(!Fe(Te.current,v,E.signal))return;L(null),f(fe=>fs(fe,ce.message))}catch(ce){Fe(Te.current,v,E.signal)&&(ie&&L(J),_t(ce)||ee(ce instanceof Error?ce.message:"图片发送失败"))}finally{Fe(Te.current,v,E.signal)&&(K(!1),T.current&&(T.current.value=""))}},[a,pe,W]),ot=r.useCallback(async()=>{const J=q.trim();!J||!pe||!a||W||await Ve(J,!0)},[a,q,pe,Ve,W]),pt=r.useCallback(async J=>{!J||!pe||!a||W||await Ge(J,!0)},[a,pe,Ge,W]),ht=r.useCallback(async()=>{re?await Ve(re,!1):$&&await Ge($,!1)},[$,re,Ge,Ve]);return{accounts:t,activeAccountID:a,activeSessions:we,selectedSession:pe,activeAccount:He,messages:m,search:x,unreadOnly:_,draft:q,loading:O,messagesLoading:G,olderLoading:X,hasOlder:j,contactsLoading:b,hasMoreContacts:Z[a]===!0,emojiOpen:D,sending:W,error:N,liveState:be,activeChatID:u,filteredSessions:Ke,scrollRef:se,imageInputRef:T,setActiveAccountID:l,setActiveChatID:p,setSearch:h,setUnreadOnly:S,setDraft:w,setEmojiOpen:C,reloadSessions:Me,loadMoreContacts:tt,loadOlderMessages:Be,handleMessageScroll:Je,handleSend:ot,handleImage:pt,retrySend:ht,retryAvailable:!!(re||$),unreadForAccount:it,emojiURL:Vi,xianyuEmojis:sr,renderXianyuText:Hi,formatClock:Xi,messageTime:eo}},so=()=>{const{accounts:t,activeAccountID:s,activeChatID:a,activeAccount:l,selectedSession:n,filteredSessions:c,messages:u,search:p,unreadOnly:m,draft:f,loading:x,messagesLoading:h,olderLoading:_,hasOlder:S,contactsLoading:q,hasMoreContacts:w,emojiOpen:O,sending:P,error:G,liveState:H,scrollRef:X,imageInputRef:y,setActiveAccountID:j,setActiveChatID:z,setSearch:A,setUnreadOnly:F,setDraft:d,setEmojiOpen:B,reloadSessions:Z,loadMoreContacts:M,loadOlderMessages:b,handleMessageScroll:k,handleSend:D,handleImage:C,retrySend:W,retryAvailable:K,unreadForAccount:N,emojiURL:ee,xianyuEmojis:be,renderXianyuText:U,formatClock:re,messageTime:ge}=to();return x?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(_e,{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 ${H==="online"?"bg-emerald-50 text-emerald-700":H==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[H==="online"?e.jsx(Rr,{className:"h-3.5 w-3.5"}):e.jsx(Ir,{className:"h-3.5 w-3.5"}),H==="online"?"实时同步中":H==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:t.map($=>{const L=$.id===s,V=N($.id),Y=$.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":L,onClick:(()=>j($.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${L?"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 ${Y?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:$.nickname||$.remark||$.id}),V>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:V>99?"99+":V})]},$.id)})})]}),t.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(ys,{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(St,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:p,onChange:($=>A($.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:(()=>F($=>!$)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${m?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:m?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void Z(s)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(We,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[c.map($=>e.jsxs("button",{type:"button",onClick:(()=>z($.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${$.chat_id===a?"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:$.buyer_avatar_url?e.jsx("img",{src:$.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(Zt,{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:$.buyer_name||`用户 ${$.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:re($.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:$.last_message||"暂无消息"}),$.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:$.unread_count})]}),$.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",$.item_title]})]})]},$.chat_id)),c.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),w&&!p&&!m&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void M()),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(_e,{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:n?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:n.buyer_name||n.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",n.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(l==null?void 0:l.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(l==null?void 0:l.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:X,onScroll:k,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:h?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(_e,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[S&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void b()),disabled:_,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:[_&&e.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}),_?"正在加载":"加载更早消息"]})}),u.map($=>{const L=$.direction==="outgoing";return $.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:[U($.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:ge($.sent_at)})]})},$.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${L?"justify-end":"justify-start"}`,children:[!L&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:n.buyer_avatar_url?e.jsx("img",{src:n.buyer_avatar_url,alt:n.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(Zt,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${L?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:L?(l==null?void 0:l.nickname)||(l==null?void 0:l.remark)||"我":n.buyer_name||$.sender_name||n.buyer_id}),$.message_type==="image"?e.jsx("a",{href:$.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${L?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:$.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):$.message_type==="video"?e.jsx("video",{src:$.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 ${L?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:U($.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[ge($.sent_at),L&&($.status==="failed"?e.jsx(ut,{className:"h-3 w-3 text-red-500"}):$.status==="sent"?e.jsx(Ar,{className:"h-3 w-3 text-sky-500"}):e.jsx(Ye,{className:"h-3 w-3"}))]})]}),L&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:l!=null&&l.avatar_url?e.jsx("img",{src:l.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(Zt,{className:"m-2 h-5 w-5 text-sky-600"})})]},$.message_key)})]})}),G&&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:G}),K&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void W()),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:(()=>B($=>!$)),disabled:P||(l==null?void 0:l.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(Or,{className:"h-5 w-5"})}),O&&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:be.map(([$,L])=>e.jsx("button",{type:"button",title:`[${$}]`,onClick:(()=>{d(V=>V+`[${$}]`),B(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:ee(L),alt:`[${$}]`,className:"h-8 w-8 object-contain"})},$))})]})]}),e.jsx("input",{ref:y,type:"file",accept:"image/*",className:"hidden",onChange:($=>{var L;return void C((L=$.target.files)==null?void 0:L[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var $;return($=y.current)==null?void 0:$.click()}),disabled:P||(l==null?void 0:l.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(Pr,{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:f,onChange:($=>d($.target.value)),rows:2,maxLength:2e3,onKeyDown:($=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),D())}),disabled:(l==null?void 0:l.runtime_state)!=="online",placeholder:(l==null?void 0:l.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 D()),disabled:!f.trim()||P||(l==null?void 0:l.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:P?e.jsx(_e,{className:"h-4 w-4 animate-spin"}):e.jsx(ss,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(ys,{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:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})},ar="ydisks.sidebar.v1",ao=()=>{try{return window.localStorage.getItem(ar)==="collapsed"}catch{return!1}},ro=t=>{try{window.localStorage.setItem(ar,t?"collapsed":"expanded")}catch{}},rr={"/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"},ya=Object.fromEntries(Object.entries(rr).map(([t,s])=>[s,t])),ja=()=>rr[window.location.pathname]||"dashboard",lo=()=>{const[t,s]=r.useState(!1),[a,l]=r.useState(!1),[n,c]=r.useState(ja),[u,p]=r.useState(!0),[m,f]=r.useState(!1),[x,h]=r.useState(""),[_,S]=r.useState(""),[q,w]=r.useState(!1),[O,P]=r.useState(""),[G,H]=r.useState(""),[X,y]=r.useState(""),[j,z]=r.useState(!1),[A,F]=r.useState(""),[d,B]=r.useState(),[Z,M]=r.useState(ao),b=K=>{const N=K==="settings"&&!a?"dashboard":K,ee=ya[N];ee&&ee!==window.location.pathname&&window.history.pushState({},"",ee),c(N)};r.useEffect(()=>{const K=()=>c(ja());return window.addEventListener("popstate",K),()=>window.removeEventListener("popstate",K)},[]),r.useEffect(()=>{qa().then(N=>{if((N==null?void 0:N.initialized)===!1){f(!0),s(!1),l(!1);return}f(!1),N!=null&&N.authenticated?(s(!0),l(N.is_admin===!0)):l(!1)}).catch(()=>{s(!1),l(!1)}).finally(()=>p(!1));const K=()=>{s(!1),l(!1)};return window.addEventListener("auth:logout",K),()=>window.removeEventListener("auth:logout",K)},[]),r.useEffect(()=>{!u&&t&&!a&&n==="settings"&&(window.history.replaceState({},"",ya.dashboard),c("dashboard"))},[u,t,a,n]);const k=async K=>{K.preventDefault(),w(!0),P("");try{const N=await Kr({username:x,password:_});N.success?(s(!0),l(N.is_admin===!0)):P(N.message||"登录失败")}catch(N){const ee=N instanceof Error?N.message:String(N);P(ee||"登录失败")}finally{w(!1)}},D=async K=>{if(K.preventDefault(),F(""),G.length<8){F("密码至少需要 8 个字符");return}if(G!==X){F("两次输入的密码不一致");return}z(!0);try{const N=await Vr(G);if(!N.success){F(N.message||"初始化失败,请重试");return}f(!1),s(!0),l(N.is_admin===!0),H(""),y("")}catch(N){const ee=N instanceof Error?N.message:String(N);F(ee||"初始化失败,请重试")}finally{z(!1)}},C=async()=>{try{await Hr()}catch(K){console.error("退出登录失败",K)}finally{s(!1),l(!1)}};if(u)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface",children:e.jsx(_e,{className:"w-8 h-8 text-brand animate-spin"})});if(m)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-xl border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:e.jsx(ws,{sizeClass:"w-24 h-24"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"首次设置管理员密码"}),e.jsx("p",{className:"text-gray-600 font-medium",children:"设置完成后会自动进入系统,管理员账号为 admin。"})]}),e.jsxs("form",{onSubmit:D,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(Js,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"设置管理员密码(至少 8 个字符)",value:G,onChange:K=>H(K.target.value),autoFocus:!0,className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(qt,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"再次输入密码",value:X,onChange:K=>y(K.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),A&&e.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4"})," ",A]}),e.jsx("button",{type:"submit",disabled:j,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:j?e.jsx(_e,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["设置密码并进入系统 ",e.jsx(Ns,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!t)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-lg border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"group mx-auto mb-6 flex cursor-pointer justify-center",children:e.jsx(ws,{sizeClass:"w-24 h-24",logoClassName:"w-full h-full text-white group-hover:scale-110 transition-transform"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),e.jsxs("form",{onSubmit:k,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(yt,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"text",placeholder:"管理员账号",value:x,onChange:K=>h(K.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(Js,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"密码",value:_,onChange:K=>S(K.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),O&&e.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4"})," ",O]}),e.jsx("button",{type:"submit",disabled:q,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:q?e.jsx(_e,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["立即登录 ",e.jsx(Ns,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:e.jsx("div",{className:"mt-6 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const W=()=>{switch(n){case"dashboard":return e.jsx(ds,{});case"accounts":return e.jsx(zn,{});case"chat":return e.jsx(so,{});case"orders":return e.jsx(ti,{});case"cards":return e.jsx(oi,{});case"items":return e.jsx(vi,{onConfigureDelivery:K=>{B({cookieId:K.cookie_id,itemId:K.item_id,requestId:Date.now()}),b("rules")}});case"rules":return e.jsx($i,{initialDeliveryTarget:d,onDeliveryTargetHandled:()=>B(void 0)});case"notifications":return e.jsx(Ki,{isAdmin:a});case"settings":return a?e.jsx(Li,{}):e.jsx(ds,{});default:return e.jsx(ds,{})}};return e.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[e.jsx(un,{activeTab:n,isAdmin:a,collapsed:Z,onToggleCollapsed:()=>M(K=>{const N=!K;return ro(N),N}),onNavigate:b,onLogout:C}),e.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${Z?"ml-16":"ml-64"} ${n==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[e.jsx("div",{className:"fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"}),e.jsx("div",{className:`${n==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:W()})]})]})},lr=document.getElementById("root");if(!lr)throw new Error("Could not find root element to mount to");const no=ir.createRoot(lr);no.render(e.jsx(As.StrictMode,{children:e.jsx(lo,{})})); diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html index 9b4c451..872f35d 100644 --- a/internal/webui/static/index.html +++ b/internal/webui/static/index.html @@ -6,7 +6,7 @@ Ydisks闲鱼助手 - 自动发货与管家系统 - +