diff --git a/docs/architecture/api-versioning-migration.md b/docs/architecture/api-versioning-migration.md index 3af8768..ffdded5 100644 --- a/docs/architecture/api-versioning-migration.md +++ b/docs/architecture/api-versioning-migration.md @@ -6,7 +6,7 @@ | 领域 | 现有路径 | 目标 `/api/v1` 路径 | 迁移状态 | | --- | --- | --- | --- | -| 会话 | `/verify`、`/logout` | `/api/v1/session`、`/api/v1/session/logout` | 旧路径保留,待前端统一请求层后迁移 | +| 会话 | `/login`、`/initialize`、`/verify`、`/logout` | `/api/v1/session/login`、`/api/v1/session/initialize`、`/api/v1/session`、`/api/v1/session/logout` | React 会话调用方已迁移到版本化入口;旧路径保留并由同一 handler 提供 | | 账号 | `/cookies/details`、`/cookies/{cid}/...` | `/api/v1/accounts/...` | 旧路径保留,详情/设置/资料/暂停 DTO 已落地 | | 商品 | `/items...` | `/api/v1/items...` | 旧路径保留,发布/同步/列表/详情 DTO 已落地 | | 商品批量 | `/items/publish-batches...` | `/api/v1/items/publish-batches...` | 旧路径保留,类目推荐/预检/任务 DTO 已落地 | @@ -43,6 +43,7 @@ - 关键词回复、默认回复和账号任务分别使用 `keywordBasicResponse`/`keywordItemResponse`/`keywordTypedResponse`、`itemReplyResponse`、`defaultReplyResponse`、`accountTaskSettingsResponse`、`accountTaskRunsResponse` 与 `accountTaskRunResponseEnvelope`。 - 管理员和统计分别使用 `adminUserResponse`/`adminCookieResponse`/`adminStatsResponse`、`dashboardStatsResponse`、`orderAnalyticsResponse` 与 `validOrdersResponse`;二维码生成使用 `qrLoginGenerateResponse`。 - 动态设置和二维码兼容边界分别使用 `settingsResponse`、`qrLoginStatusResponse` 与 `qrLoginVerificationResponse`;二维码状态契约测试确认 `cookies` 等敏感字段不会回传。 +- 会话登录、初始化、校验和登出已由 React 请求层迁移到 `/api/v1/session/...`,Go 契约测试确认版本化入口与旧路径共用 handler 且旧路径仍可用。 - 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。 - React `frontend/types.ts` 与 `frontend/services/api.ts` 已同步具名成功响应类型,同时保留旧字段归一逻辑。 -- 旧路径仍由现有路由提供,尚未宣称 `/api/v1` 已经可用。 +- 会话版本化入口已可用;除会话外的 `/api/v1` 领域入口仍未宣称可用,旧路径继续保留。 diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 270deec..030be1b 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -138,7 +138,8 @@ app shell / routes - 已完成阶段 3 第八个 PR 切片“剩余商品批量操作与设置/卡券/通知成功响应收口”:商品类目推荐、批量发布预检/任务、系统与用户设置、账号 AI 设置、卡券 CRUD/批量、通知渠道与账号绑定均改用具名 DTO;React 客户端同步具名契约类型;补充跨领域契约测试;保留动态设置键、旧路径和批量逐行字段;全量门禁通过并合并为一个可回滚提交; - 已完成阶段 3 第九个 PR 切片“剩余关键词回复、默认回复与账号任务成功响应收口”:关键词基础/商品/类型规则、指定商品回复、默认回复、账号任务设置与运行记录均改用具名 DTO;React 客户端同步具名契约类型;新增跨领域契约测试;保留旧路径和兼容字段;全量门禁通过并合并为一个可回滚提交; - 已完成阶段 3 第十个 PR 切片“分析统计、管理员与剩余公共成功响应收口”:管理员用户/账号/统计、用户仪表盘、订单分析、有效订单分页和二维码生成均改用具名 DTO;React 客户端同步统计和二维码契约类型;新增跨领域契约测试;保留动态设置和二维码状态的兼容边界;全量门禁通过并合并为一个可回滚提交; -- 阶段 3 下一 PR 切片为“公共成功响应兼容收尾与版本化迁移入口审计”:审计剩余动态设置、二维码状态及 `/api/v1` 迁移适配边界,不拆分单个 handler 提交; +- 已完成阶段 3 第十二个 PR 切片“HTTP API 版本化兼容入口与会话调用方迁移”:新增 `/api/v1/session/login`、`/api/v1/session/initialize`、`/api/v1/session` 与 `/api/v1/session/logout` 薄适配入口,复用旧 handler;React 登录、初始化、会话校验和登出已迁移,旧路径保留;新增 Go/React 契约测试并保持独立可回滚提交; +- 阶段 3 下一 PR 切片为“账号 API 版本化兼容入口与调用方迁移”:先迁移账号摘要、详情和状态的一组调用方,不删除旧路径,不拆分单个 handler 提交; - 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。 ## 6. 阶段 0:治理文档与强约束 @@ -526,3 +527,4 @@ npm --prefix frontend run build | 2026-08-14 | 完成阶段 3 第九个 PR 切片“剩余关键词回复、默认回复与账号任务成功响应收口” | 关键词基础/商品/类型规则、指定商品回复、默认回复、账号任务设置与运行记录已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:分析统计、管理员与剩余公共成功响应收口 | | 2026-08-14 | 完成阶段 3 第十个 PR 切片“分析统计、管理员与剩余公共成功响应收口” | 管理员用户/账号/统计、用户仪表盘、订单分析、有效订单分页和二维码生成已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:公共成功响应兼容收尾与版本化迁移入口审计 | | 2026-08-14 | 完成阶段 3 第十一个 PR 切片“公共成功响应兼容收尾与版本化迁移入口审计” | 系统、管理员和用户动态设置统一通过具名 map 边界类型;二维码状态保留非敏感扩展字段并过滤 Cookie,验证完成使用具名 DTO;React API 清理剩余 `Promise`/`get` 成功响应并补齐兼容类型;新增动态设置与二维码契约测试,明确旧路径仍保留、尚未宣称 `/api/v1` 可用;所有修改合并为一个可回滚提交 | 阶段 3:HTTP API 版本化兼容入口落地与调用方迁移 | +| 2026-08-14 | 完成阶段 3 第十二个 PR 切片“HTTP API 版本化兼容入口与会话调用方迁移” | 新增 `/api/v1/session/login`、`/api/v1/session/initialize`、`/api/v1/session` 与 `/api/v1/session/logout` 薄适配入口,全部复用既有认证 handler;React 登录、初始化、会话校验和登出调用已迁移;Go/React 契约测试确认新旧路径兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:账号 API 版本化兼容入口与调用方迁移 | diff --git a/frontend/services/api.test.ts b/frontend/services/api.test.ts index faed46b..e5b98e3 100644 --- a/frontend/services/api.test.ts +++ b/frontend/services/api.test.ts @@ -39,7 +39,7 @@ import { sendChatMessage, markChatRead, updateAccountTaskSettings, - runAccountTask, + runAccountTask, login, initializeAdmin, verifySession, } from './api'; afterEach(() => { @@ -303,7 +303,7 @@ test('logout calls backend session invalidation route', async () => { vi.stubGlobal('fetch', fetchMock); await logout(); - expect(fetchMock).toHaveBeenCalledWith('/logout', expect.objectContaining({ + expect(fetchMock).toHaveBeenCalledWith('/api/v1/session/logout', expect.objectContaining({ method: 'POST', credentials: 'include', })); @@ -740,3 +740,26 @@ test('updateShippingRule posts review request text action without card requireme }), ]); }); + +// 会话 API 使用版本化兼容入口。 +const runVersionedSessionAPITest = async () => { + // fetchMock 是会话 API 请求的测试替身。 + const fetchMock = vi.fn() + .mockResolvedValueOnce(jsonResponse({ success: true, authenticated: true })) + .mockResolvedValueOnce(jsonResponse({ success: true, authenticated: true })) + .mockResolvedValueOnce(jsonResponse({ success: true, authenticated: true })) + .mockResolvedValueOnce(jsonResponse({ success: true, authenticated: true })); + vi.stubGlobal('fetch', fetchMock); + + await login({ username: 'admin', password: 'pw' }); + await initializeAdmin('long-password'); + await verifySession(); + await logout(); + + expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/session/login', expect.objectContaining({ method: 'POST' })); + expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/session/initialize', expect.objectContaining({ method: 'POST' })); + expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/session', expect.objectContaining({ method: 'GET' })); + expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/session/logout', expect.objectContaining({ method: 'POST' })); +}; + +test('session APIs use versioned compatibility routes', runVersionedSessionAPITest); diff --git a/frontend/services/api.ts b/frontend/services/api.ts index 7c8bd41..5f3a546 100644 --- a/frontend/services/api.ts +++ b/frontend/services/api.ts @@ -19,19 +19,19 @@ const normalizeSettings = (settings: Record): SystemSettings => { // Auth export const login = async (data: { username?: string; password?: string; email?: string; verification_code?: string }): Promise => { - return post('/login', data, { skipAuthLogout: true }); + return post('/api/v1/session/login', data, { skipAuthLogout: true }); }; export const initializeAdmin = async (password: string): Promise => { - return post('/initialize', { password }, { skipAuthLogout: true }); + return post('/api/v1/session/initialize', { password }, { skipAuthLogout: true }); }; export const verifySession = async (): Promise<{ authenticated: boolean; initialized?: boolean; user_id?: number; username?: string; is_admin?: boolean }> => { - return get('/verify'); + return get('/api/v1/session'); }; export const logout = async (): Promise => { - return post('/logout', {}); + return post('/api/v1/session/logout', {}); }; export const changePassword = async (currentPassword: string, newPassword: string): Promise => { diff --git a/internal/server/server.go b/internal/server/server.go index 7f5831d..961e596 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -153,7 +153,7 @@ func (s *Server) Router() http.Handler { r.Use(s.requestLogger) // 健康检查(无需认证)。 - r.Get("/health", s.health) + s.mountHealthAndVersionedSession(r) // 认证组(无需登录的端点,但解析会话以判断登录态)。 r.Group(func(r chi.Router) { diff --git a/internal/server/versioned_session_contract_test.go b/internal/server/versioned_session_contract_test.go new file mode 100644 index 0000000..58517a1 --- /dev/null +++ b/internal/server/versioned_session_contract_test.go @@ -0,0 +1,87 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestVersionedSessionRoutesPreserveLegacyContracts 验证版本化会话入口复用旧 handler 并保留旧路径。 +func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) { + // srv 是用于验证版本化会话路由的 HTTP 测试服务。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // handler 是当前测试使用的完整路由树。 + handler := srv.Router() + // loginBody 是版本化登录请求体。 + loginBody := `{"username":"admin","password":"pw"}` + // loginReq 是通过版本化入口登录的请求。 + loginReq := httptest.NewRequest(http.MethodPost, "/api/v1/session/login", strings.NewReader(loginBody)) + // loginRecorder 是捕获版本化登录响应的记录器。 + loginRecorder := httptest.NewRecorder() + handler.ServeHTTP(loginRecorder, loginReq) + if loginRecorder.Code != http.StatusOK { + t.Fatalf("versioned login status=%d body=%s", loginRecorder.Code, loginRecorder.Body.String()) + } + // loginResponseValue 是版本化登录响应 DTO。 + var loginResponseValue loginResponse + // loginDecodeErr 是版本化登录响应反序列化失败的原因。 + if loginDecodeErr := json.Unmarshal(loginRecorder.Body.Bytes(), &loginResponseValue); loginDecodeErr != nil { + t.Fatalf("decode versioned login response: %v", loginDecodeErr) + } + if !loginResponseValue.Success || loginResponseValue.Username != "admin" { + t.Fatalf("versioned login response=%+v", loginResponseValue) + } + // sessionCookie 是版本化登录成功后下发的会话 Cookie。 + sessionCookie := loginRecorder.Result().Cookies()[0] + + // verifyReq 是通过版本化入口校验会话的请求。 + verifyReq := httptest.NewRequest(http.MethodGet, "/api/v1/session", nil) + verifyReq.AddCookie(sessionCookie) + // verifyRecorder 是捕获版本化会话校验响应的记录器。 + verifyRecorder := httptest.NewRecorder() + handler.ServeHTTP(verifyRecorder, verifyReq) + if verifyRecorder.Code != http.StatusOK { + t.Fatalf("versioned verify status=%d body=%s", verifyRecorder.Code, verifyRecorder.Body.String()) + } + // verifyResponseValue 是版本化会话校验响应 DTO。 + var verifyResponseValue sessionVerificationResponse + // verifyDecodeErr 是版本化会话校验响应反序列化失败的原因。 + if verifyDecodeErr := json.Unmarshal(verifyRecorder.Body.Bytes(), &verifyResponseValue); verifyDecodeErr != nil { + t.Fatalf("decode versioned verify response: %v", verifyDecodeErr) + } + if !verifyResponseValue.Authenticated || verifyResponseValue.Username != "admin" { + t.Fatalf("versioned verify response=%+v", verifyResponseValue) + } + + // legacyVerifyReq 是通过旧入口复核兼容性的请求。 + legacyVerifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil) + legacyVerifyReq.AddCookie(sessionCookie) + // legacyVerifyRecorder 是捕获旧入口响应的记录器。 + legacyVerifyRecorder := httptest.NewRecorder() + handler.ServeHTTP(legacyVerifyRecorder, legacyVerifyReq) + if legacyVerifyRecorder.Code != http.StatusOK { + t.Fatalf("legacy verify status=%d body=%s", legacyVerifyRecorder.Code, legacyVerifyRecorder.Body.String()) + } + + // logoutReq 是通过版本化入口注销会话的请求。 + logoutReq := httptest.NewRequest(http.MethodPost, "/api/v1/session/logout", nil) + logoutReq.AddCookie(sessionCookie) + // logoutRecorder 是捕获版本化注销响应的记录器。 + logoutRecorder := httptest.NewRecorder() + handler.ServeHTTP(logoutRecorder, logoutReq) + if logoutRecorder.Code != http.StatusOK { + t.Fatalf("versioned logout status=%d body=%s", logoutRecorder.Code, logoutRecorder.Body.String()) + } + + // legacyLoginReq 是验证旧登录入口仍可用的请求。 + legacyLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(loginBody)) + // legacyLoginRecorder 是捕获旧登录响应的记录器。 + legacyLoginRecorder := httptest.NewRecorder() + handler.ServeHTTP(legacyLoginRecorder, legacyLoginReq) + if legacyLoginRecorder.Code != http.StatusOK { + t.Fatalf("legacy login status=%d body=%s", legacyLoginRecorder.Code, legacyLoginRecorder.Body.String()) + } +} diff --git a/internal/server/versioned_session_routes.go b/internal/server/versioned_session_routes.go new file mode 100644 index 0000000..f91ceeb --- /dev/null +++ b/internal/server/versioned_session_routes.go @@ -0,0 +1,20 @@ +package server + +import "github.com/go-chi/chi/v5" + +// mountHealthAndVersionedSession 挂载健康检查和版本化会话入口。 +func (s *Server) mountHealthAndVersionedSession(r chi.Router) { + r.Get("/health", s.health) + s.mountVersionedSession(r) +} + +// mountVersionedSession 挂载会话 API 的 `/api/v1` 兼容入口,复用现有 handler。 +func (s *Server) mountVersionedSession(r chi.Router) { + r.Group(func(r chi.Router) { + r.Use(s.Auth.Middleware) + r.Post("/api/v1/session/login", s.login) + r.Post("/api/v1/session/initialize", s.initialize) + r.Get("/api/v1/session", s.verify) + r.Post("/api/v1/session/logout", s.logout) + }) +} diff --git a/internal/webui/static/assets/index-DA3sXl2j.js b/internal/webui/static/assets/index-B_ErP0wz.js similarity index 75% rename from internal/webui/static/assets/index-DA3sXl2j.js rename to internal/webui/static/assets/index-B_ErP0wz.js index f9aa68b..5c8b7b5 100644 --- a/internal/webui/static/assets/index-DA3sXl2j.js +++ b/internal/webui/static/assets/index-B_ErP0wz.js @@ -1,4 +1,4 @@ -import{j as e,r,c as ys,b as qe,d as Wa}from"./react-vendor-C_od1ZSF.js";import{L as Ja,U as ha,M as is,C as os,B as ga,S as ba,Z as cs,a as jt,b as js,G as As,c as Ns,d as _s,e as Va,f as rt,A as $s,D as Qa,g as Ps,P as fa,h as qt,E as ya,T as Ga,i as Ka,j as Pe,X as Me,k as Ha,l as Za,m as vs,n as ja,o as He,Q as Xt,p as xt,q as Ke,r as yt,s as Tt,t as Rs,R as ze,u as Na,v as Ya,w as Qe,K as Xa,x as dt,y as lt,z as et,F as Es,H as _t,I as Nt,J as Dt,N as _a,O as el,V as Ds,W as Ts,Y as tl,_ as sl,$ as al,a0 as ll,a1 as es,a2 as Bt,a3 as ds,a4 as rl,a5 as nl,a6 as xs,a7 as Ms,a8 as il,a9 as ol,aa as Mt,ab as qs,ac as Gt,ad as va,ae as cl,af as dl,ag as Zt,ah as wa,ai as xl,aj as ml,ak as pl,al as ul,am as hl,an as gl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as bl,X as Bs,Y as zs,T as Ut,a as fl,C as ts,A as yl,b as jl,c as Nl,P as Us,d as Ws,L as _l}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const _ of m)if(_.type==="childList")for(const N of _.addedNodes)N.tagName==="LINK"&&N.rel==="modulepreload"&&i(N)}).observe(document,{childList:!0,subtree:!0});function l(m){const _={};return m.integrity&&(_.integrity=m.integrity),m.referrerPolicy&&(_.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?_.credentials="include":m.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function i(m){if(m.ep)return;m.ep=!0;const _=l(m);fetch(m.href,_)}})();const vl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),e.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:e.jsx(vl,{className:a})})]})]}),wl=({activeTab:t,isAdmin:a=!1,collapsed:l,onToggleCollapsed:i,onNavigate:m,onLogout:_})=>{const[N,R]=r.useState({version:"dev",commit:"unknown"});r.useEffect(()=>{const j=new AbortController;return fetch("/health",{signal:j.signal}).then(F=>F.ok?F.json():Promise.reject(new Error("health request failed"))).then(F=>R({version:String(F.version||"dev"),commit:String(F.commit||"unknown")})).catch(F=>{F instanceof DOMException&&F.name}),()=>j.abort()},[]);const g=[{id:"dashboard",icon:Ja,label:"仪表盘"},{id:"accounts",icon:ha,label:"账号管理"},{id:"chat",icon:is,label:"在线聊天"},{id:"cards",icon:os,label:"卡密库存"},{id:"items",icon:ga,label:"商品列表"},{id:"orders",icon:ba,label:"订单管理"},{id:"rules",icon:cs,label:"自动化规则"},{id:"notifications",icon:jt,label:"通知设置"},...a?[{id:"settings",icon:js,label:"系统与AI"}]:[]],C=/^\d+\.\d+\.\d+$/.test(N.version)?`v${N.version}`:N.version;return e.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${l?"w-16":"w-64"}`,children:[e.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${l?"justify-center px-2":"gap-3 px-5"}`,children:[e.jsx(ms,{sizeClass:"h-10 w-10"}),!l&&e.jsxs("div",{className:"min-w-0 leading-tight",children:[e.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),e.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),e.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${l?"px-2":"px-3"}`,"aria-label":"主导航",children:g.map(j=>{const F=j.icon,G=t===j.id;return e.jsx(ys.Fragment,{children:e.jsxs("button",{type:"button",title:l?j.label:void 0,"aria-label":j.label,"aria-current":G?"page":void 0,onClick:()=>m(j.id),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${l?"justify-center":"gap-3 px-3.5"} ${G?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(F,{className:`h-[19px] w-[19px] shrink-0 ${G?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!l&&e.jsx("span",{className:"truncate text-sm font-bold",children:j.label}),G&&!l&&e.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},j.id)})}),e.jsxs("div",{children:[e.jsx("div",{title:l?`版本 ${N.version} · ${N.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${l?"flex justify-center px-1":"px-6"}`,children:l?e.jsx(As,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${N.version}`}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[e.jsx(As,{className:"h-3.5 w-3.5"}),"运行版本"]}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[e.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:C}),e.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:N.commit})]})]})}),e.jsxs("div",{className:`space-y-2 p-2 ${l?"":"p-3"}`,children:[e.jsxs("button",{type:"button",onClick:i,title:l?"展开侧边栏":"收起侧边栏","aria-label":l?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${l?"justify-center":"gap-3 px-3"}`,children:[l?e.jsx(Ns,{className:"h-5 w-5"}):e.jsx(_s,{className:"h-5 w-5"}),!l&&e.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),e.jsxs("button",{type:"button",onClick:_,title:l?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${l?"justify-center":"gap-3 px-3"}`,children:[e.jsx(Va,{className:"h-5 w-5"}),!l&&e.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},kl=3e4,Cl=10*6e4;let ss=!1;const ka=()=>{ss||typeof window>"u"||(ss=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{ss=!1}))},Sl=t=>{if(!t)return"";const a=new URLSearchParams;for(const[i,m]of Object.entries(t))m!=null&&a.set(i,String(m));const l=a.toString();return l?`?${l}`:""},Yt=async(t,a,l={})=>{var C;const i=Sl(l.params),m=`${a}${i}`,_=Ca(l.signal,l.timeoutMs??kl);let N;try{N=await fetch(m,{method:t,credentials:"include",signal:_.signal,headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)})}catch(j){throw _.signal.aborted?new Error((C=l.signal)!=null&&C.aborted?"请求已取消":"请求超时,请稍后重试"):j}finally{_.cleanup()}const g=(N.headers.get("content-type")||"").includes("application/json");if(!N.ok){N.status===401&&!l.skipAuthLogout&&ka();const j=g?await N.json().catch(()=>{}):await N.text().catch(()=>{}),F=Sa(j,N.status);throw new Error(F)}return g?await N.json():await N.text()},Le=async(t,a,l)=>Yt("GET",t,{params:a,...l}),Ce=async(t,a,l)=>Yt("POST",t,{body:a,...l}),Be=async(t,a,l)=>Yt("PUT",t,{body:a,...l}),Ze=async(t,a,l)=>Yt("DELETE",t,{params:a,...l}),wt=async(t,a,l={})=>{var g;const i=Ca(l.signal,l.timeoutMs??Cl);let m;try{m=await fetch(t,{method:"POST",credentials:"include",signal:i.signal,body:a})}catch(C){throw i.signal.aborted?new Error((g=l.signal)!=null&&g.aborted?"请求已取消":"上传超时,请稍后重试"):C}finally{i.cleanup()}const R=(m.headers.get("content-type")||"").includes("application/json")?await m.json().catch(()=>{}):await m.text().catch(()=>{});if(!m.ok){m.status===401&&ka();const C=Sa(R,m.status),j=new Error(C);throw j.payload=R,j}return R},Ca=(t,a)=>{const l=new AbortController,i=()=>l.abort(t==null?void 0:t.reason);t!=null&&t.aborted?i():t==null||t.addEventListener("abort",i,{once:!0});const m=globalThis.setTimeout(()=>l.abort(new DOMException("timeout","TimeoutError")),Math.max(1,a));return{signal:l.signal,cleanup:()=>{globalThis.clearTimeout(m),t==null||t.removeEventListener("abort",i)}}},Ll=t=>{if(typeof t!="object"||t===null)return!1;const a=t;return typeof a.code=="string"&&typeof a.message=="string"},Sa=(t,a)=>typeof t=="string"?t:Ll(t)?t.message:`请求失败: ${a}`,Kt=t=>{const a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${a}-${l}-${i}`},ws=(t,a)=>{const l=new Date(t);return l.setHours(12,0,0,0),l.setDate(l.getDate()+a),l},ps=(t,a)=>({startDate:Kt(ws(t,-(a-1))),endDate:Kt(t)}),Js=(t,a=new Date,l="",i="")=>{if(t==="custom"&&l&&i){if(l>i)throw new Error("开始日期不能晚于结束日期");return{startDate:l,endDate:i}}return t==="yesterday"?ps(ws(a,-1),1):ps(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Ol=t=>{const a=new Date(`${t.startDate}T12:00:00`),l=new Date(`${t.endDate}T12:00:00`),i=Math.round((l.getTime()-a.getTime())/864e5)+1,m=ws(a,-1);return ps(m,i)},Il=t=>{const a={...t};if("renewal_log_retention_days"in a){const l=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(l)?l:10}return a},Al=async t=>Ce("/login",t,{skipAuthLogout:!0}),$l=async t=>Ce("/initialize",{password:t},{skipAuthLogout:!0}),La=async()=>Le("/verify"),Pl=async()=>Ce("/logout",{}),Rl=async t=>Be("/account/credentials",t),El=(t,a)=>{const l=t.avatar_url||"";if(!l)return"";try{const i=new URL(l,window.location.origin);return i.hostname.endsWith("alicdn.com")&&i.searchParams.set("_v",a),i.toString()}catch{return l}},Ft=async t=>{const a=await Le("/cookies/details",void 0,t),l=Date.now().toString();return a.map(i=>({id:i.id,value:"",cookie:"",enabled:i.enabled,auto_confirm:i.auto_confirm,remark:i.remark,note:i.remark,pause_duration:i.pause_duration,paused_until:Number(i.paused_until||0),paused:i.paused===!0,username:i.username||"",login_password:"",show_browser:i.show_browser===!0||i.show_browser===1||i.show_browser==="1"||i.show_browser==="true",nickname:i.nickname||i.remark||`账号 ${i.id.substring(0,6)}`,avatar_url:El(i,l),profile_error:i.profile_error||"",ai_enabled:!1,auto_rate_enabled:i.auto_rate_enabled,rate_content:i.rate_content||"不错的买家,交易愉快",auto_polish_enabled:i.auto_polish_enabled,polish_time:i.polish_time||"03:00",last_rate_scan_at:Number(i.last_rate_scan_at||0),last_polish_date:i.last_polish_date||"",last_polish_at:Number(i.last_polish_at||0)}))},Dl=async t=>Le(`/api/account-tasks/${t}`),Vs=async(t,a)=>Be(`/api/account-tasks/${t}`,a),Tl=async(t,a)=>Ce(`/api/account-tasks/${t}/run`,{task_type:a},{timeoutMs:12e4}),as=async(t,a,l,i=!1)=>{const m=await Le("/api/chat/sessions",{account_id:t,cursor:a,refresh:i?1:void 0},i?{timeoutMs:6e4,...l}:l);return{sessions:m.sessions||[],has_more:m.has_more===!0,next_cursor:m.next_cursor}},us=async(t,a,l,i,m)=>{const _=await Le("/api/chat/messages",{account_id:t,chat_id:a,cursor:l,before_id:i},m);return{messages:_.messages||[],has_more:_.has_more===!0,next_cursor:_.next_cursor,session:_.session}},Ml=async(t,a,l,i)=>(await us(t,a,void 0,l,i)).messages,ql=async t=>Ce("/api/chat/messages",t),Fl=async t=>{const a=new FormData;return Object.entries(t).forEach(([l,i])=>a.append(l,i)),wt("/api/chat/images",a,{timeoutMs:12e4})},Qs=async(t,a)=>Ce("/api/chat/read",{account_id:t,chat_id:a}),hs=async t=>Le("/cookies/runtime-status",void 0,t),Bl=async t=>Ce("/qr-login/generate",void 0,{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),zl=async(t,a)=>Le(`/qr-login/check/${t}`,void 0,{signal:a,timeoutMs:1e4}),Ul=async(t,a)=>Ce(`/qr-login/complete-verification/${t}`,{target_account_id:a||""}),Wl=async(t,a)=>Be(`/cookies/${t}/status`,{enabled:a}),Jl=async t=>Ze(`/cookies/${t}`),Vl=async(t,a)=>Be(`/cookies/${t}/pause-duration`,{pause_duration:a}),Ql=async(t,a)=>Be(`/cookies/${t}/settings`,a),Gl=async t=>Le(`/cookies/${t}/long-login`),Kl=async(t,a)=>Be(`/cookies/${t}/long-login`,{enabled:a}),Hl=async t=>Ce("/password-login",t),Zl=async(t,a)=>Le(`/password-login/check/${t}`,void 0,{signal:a,timeoutMs:1e4}),Yl=async t=>Ze(`/password-login/cancel/${t}`),Xl=async t=>Ce(`/cookies/${t}/refresh-profile`,{}),er=async t=>Le("/ai-reply-settings",void 0,t),Oa=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},tr=async(t,a,l=1,i=20,m)=>{const _={page:l,page_size:i};t&&(_.cookie_id=t),a&&a!=="all"&&(_.status=a),m!=null&&m.trim()&&(_.search=m.trim());const N=await Le("/api/orders",_),g=(N.orders||N.data||[]).map(C=>({...C,id:C.id||C.order_id,status:Oa(C.status||C.order_status),quantity:Number(C.quantity||1)}));return{success:!0,data:g,total:N.total||g.length,page:N.page||l,page_size:N.page_size||i,total_pages:N.total_pages||1}},sr=async(t,a)=>Be(`/api/orders/${t}`,a),ar=async t=>Ze(`/api/orders/${t}`),lr=async(t,a)=>{const l=new FormData;return t&&l.append("cookie_id",t),a&&l.append("status",a),wt("/api/orders/refresh",l)},rr=async t=>Ce(`/api/orders/${t}/refresh`),nr=async(t,a)=>Ce("/api/orders/manual-ship",{order_ids:t,ship_mode:a}),ir=async t=>t instanceof FormData?wt("/api/orders/import",t):Ce("/api/orders/import",t),or=async()=>Le("/dashboard/stats"),Gs=async(t=7)=>{let a;if(typeof t=="number"){const l=new Date,i=new Date;i.setDate(i.getDate()-t),a={start_date:Kt(i),end_date:Kt(l)}}else a=t;return Le("/analytics/orders",{...a,timezone_offset_minutes:-new Date().getTimezoneOffset()})},cr=async t=>{const a=await Le("/analytics/orders/valid",{start_date:t.start_date,end_date:t.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()}),i=(Array.isArray(a)?a:a.orders||[]).map(m=>({...m,id:m.id||m.order_id,status:Oa(m.status||m.order_status),quantity:Number(m.quantity||1)}));return{orders:i,total:Array.isArray(a)?i.length:Number(a.total??i.length),truncated:Array.isArray(a)?!1:a.truncated===!0}},dr=t=>{let a=t.api_config;if(typeof a=="string"&&a.trim())try{a=JSON.parse(a)}catch{a=void 0}return{...t,api_config:a||void 0}},Ia=t=>({...t,api_config:t.api_config?JSON.stringify(t.api_config):""}),Xe=async()=>{const t=await Le("/cards");return(Array.isArray(t)?t:t.cards||[]).map(dr)},xr=async t=>Ce("/cards",Ia(t)),Ks=async(t,a)=>Be(`/cards/${t}`,Ia(a)),mr=async t=>Ze(`/cards/${t}`),pr=async t=>{const a=new FormData;return a.append("file",t),wt("/cards/batch",a)},ur=async(t,a)=>Ce(`/cards/${t}/append-data`,{content:a}),ls=t=>t===!0||t===1||t==="1",vt=async t=>{const a=await Le("/items",void 0);return(Array.isArray(a)?a:a.items||[]).map(i=>({...i,id:i.id||`${i.cookie_id}-${i.item_id}`,is_multi_spec:ls(i.is_multi_spec),is_multi_qty_ship:ls(i.is_multi_qty_ship??i.multi_quantity_delivery),multi_quantity_delivery:ls(i.multi_quantity_delivery??i.is_multi_qty_ship)}))},hr=async t=>Ce("/items/get-all-from-account",{cookie_id:t}),gr=async(t,a)=>Ze(`/items/${t}/${a}`),br=async(t,a)=>Ce(`/items/${t}`,a),fr=async t=>{const a=new FormData;a.set("cookie_id",t.cookie_id),a.set("title",t.title),a.set("description",t.description),a.set("price",t.price),a.set("original_price",t.original_price||""),a.set("quantity",String(t.quantity)),a.set("postage_mode",t.postage_mode),a.set("postage",t.postage||""),t.location&&a.set("location",JSON.stringify(t.location));for(const l of t.images)a.append("images",l);return wt("/items/publish",a)},yr=async(t,a)=>Ce("/items/publish-categories/recommend",{cookie_id:t,keyword:a}),jr=async t=>{const a=new FormData;return a.set("file",t.file),t.imagesZip&&a.set("images_zip",t.imagesZip),t.defaultCookieId&&a.set("default_cookie_id",t.defaultCookieId),a.set("fallback_category_id",t.fallbackCategory.catId),a.set("fallback_category_name",t.fallbackCategory.catName),a.set("fallback_channel_category_id",t.fallbackCategory.channelCatId||""),a.set("fallback_tb_category_id",t.fallbackCategory.tbCatId||""),t.location&&a.set("location",JSON.stringify(t.location)),wt("/items/publish-batches/preview",a)},Nr=async t=>Ce("/items/publish-batches",{preview_id:t}),bt=async t=>Le(`/items/publish-batches/${t}`),Hs=async(t=20)=>{const a=await Le("/items/publish-batches",{limit:t});return Array.isArray(a)?a:a.batches||[]},_r=async t=>Ze(`/items/publish-batches/${t}`),vr=async t=>Ce(`/items/publish-batches/${t}/cancel`,{}),wr=async t=>Ce(`/items/publish-batches/${t}/retry-failed`,{}),kr=async(t,a,l)=>Be(`/items/${t}/${a}`,l),Aa=t=>t.map(a=>{var l,i;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((l=(a.actions||[]).find(m=>m.action_type==="send_card"))==null?void 0:l.card_id)||0),card_group_name:((i=(a.actions||[]).find(m=>m.action_type==="send_card"))==null?void 0:i.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(m=>({id:m.id?String(m.id):void 0,action_type:m.action_type,card_id:Number(m.card_id||0),card_name:m.card_name||"",delivery_count:Number(m.delivery_count||1),message_template:m.message_template||"",delay_seconds:Number(m.delay_seconds||0),config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:Number(m.sort_order||0)})),variants:(a.actions||[]).filter(m=>m.action_type==="send_card").map(m=>{let _={};try{_=JSON.parse(m.config_json||"{}")}catch{}return{id:m.id?String(m.id):void 0,spec_name:_.spec_name||"",spec_value:_.spec_value||"",card_id:Number(m.card_id||0),card_name:m.card_name||"",delivery_count:Number(m.delivery_count||1),enabled:m.enabled!==!1,delay_override:_.delay_override===!0,delay_seconds:Number(m.delay_seconds||0),config_json:m.config_json||"{}"}})}}),gs=async()=>{const t=await Le("/automation-rules"),a=Array.isArray(t)?t:t.data||[];return Aa(a)},Cr=async({cookieId:t,triggerType:a,enabled:l,search:i,page:m=1,pageSize:_=10}={})=>{const N=await Le("/automation-rules",{page:m,page_size:_,cookie_id:t||void 0,trigger_type:a||void 0,enabled:l,search:(i==null?void 0:i.trim())||void 0}),R=Aa(Array.isArray(N)?N:N.data||[]);return{success:!0,data:R,total:Number(Array.isArray(N)?R.length:N.total??R.length),page:Number(Array.isArray(N)?m:N.page??m),page_size:Number(Array.isArray(N)?_:N.page_size??_),total_pages:Number(Array.isArray(N)?R.length?1:0:N.total_pages??(R.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(Array.isArray(N)?{}:N.trigger_counts||{}).map(([g,C])=>[g,Number(C)]))}},Sr=(t,a)=>{if(t!=="order_paid")return a.map((m,_)=>({...m,sort_order:m.sort_order||_+1}));const l=a.filter(m=>m.action_type==="send_card").map((m,_)=>({...m,sort_order:_+1})),i=a.filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment");return[...l,...i.map((m,_)=>({...m,sort_order:l.length+_+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:l.length+i.length+1}]},Zs=async t=>{const a=t.trigger_type||"order_paid",i=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[a]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),m=(t.actions||[]).filter(g=>g.action_type!=="send_card"&&g.action_type!=="confirm_shipment"),_=t.variants&&t.variants.length>0?[...t.variants.map((g,C)=>({action_type:"send_card",card_id:g.card_id,delivery_count:g.delivery_count||1,enabled:g.enabled!==!1,sort_order:C+1,delay_seconds:g.delay_seconds||0,config_json:JSON.stringify({spec_name:g.spec_name||"",spec_value:g.spec_value||"",delay_override:g.delay_override===!0})})),...m]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],N=Sr(a,_),R={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||i||"自动化规则",trigger_type:a,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:N.map((g,C)=>({action_type:g.action_type,card_id:g.card_id||0,delivery_count:g.delivery_count||1,message_template:g.message_template||"",delay_seconds:g.delay_seconds||0,config_json:g.config_json||"{}",enabled:g.enabled!==!1,sort_order:g.sort_order||C+1}))};return t.id?Be(`/automation-rules/${t.id}`,R):Ce("/automation-rules",R)},Lr=async t=>Ze(`/automation-rules/${t}`),Or=async()=>{const t=await Le("/automation-issues");return{runs:Array.isArray(t==null?void 0:t.runs)?t.runs:[],pending_tasks:Array.isArray(t==null?void 0:t.pending_tasks)?t.pending_tasks:[]}},Ir=async(t,a)=>Ce(`/automation-runs/${t}/resolve`,{resolution:a}),Ar=async(t,a)=>Ce(`/automation-pending-tasks/${t}/resolve`,{resolution:a}),$r=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Pr=async t=>{const a=await Le(`/keywords-with-type/${t}`);return Array.isArray(a)?a.map($r):[]},Rr=async t=>t?(await Pr(t)).map(l=>({id:l.id,keyword:l.keyword||"",reply_content:l.reply||"",match_type:"fuzzy",enabled:!0,item_id:l.item_id||"",type:l.type==="image"?"image":"text",image_url:l.image_url||""})):[],Er=async(t,a)=>{const l=t.type||"text",i={keyword:t.keyword||"",reply:l==="text"&&t.reply_content||"",item_id:t.item_id||"",type:l,image_url:l==="image"&&t.image_url||""};return t.id?Be(`/keywords-with-type/${a}/${t.id}`,i):Ce(`/keywords-with-item-id/${a}`,i)},Dr=async(t,a)=>Ze(`/keywords-with-type/${a}/${t}`),$a=async()=>{const t=await Le("/system-settings");return Il(t.data||t)},Pa=async t=>{const a=Object.fromEntries(Object.entries(t).filter(([,l])=>l!=null));return Be("/system-settings",a)},Tr=async(t,a)=>Le(`/ai-reply-settings/${t}`,void 0,a),Mr=async(t,a)=>{const l={ai_enabled:a.ai_enabled??!1,max_discount_percent:a.max_discount_percent??10,max_discount_amount:a.max_discount_amount??100,max_bargain_rounds:a.max_bargain_rounds??3,custom_prompts:a.custom_prompts??""};return Be(`/ai-reply-settings/${t}`,l)},qr=async(t,a="")=>(await Ce("/ai-models",{base_url:t,api_key:a})).models||[],Fr=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const a=JSON.parse(t);if(Array.isArray(a))return a.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(a=>a.trim()).filter(Boolean)},Ra=t=>{const a=Array.from(new Set((t||[]).filter(Boolean)));return a.length>0?JSON.stringify(a):""},Ea=async t=>({success:!0,data:(await Le("/notification-channels",void 0,t)||[]).map(i=>{let m;try{m=typeof i.config=="string"?JSON.parse(i.config):i.config}catch{m={}}return{id:String(i.id),name:i.name,type:i.type==="ding_talk"?"dingtalk":i.type==="lark"?"feishu":i.type,config:m,event_types:Fr(i.event_types),enabled:i.enabled,created_at:i.created_at,updated_at:i.updated_at}})}),Br=async t=>Ce("/notification-channels",{...t,config:JSON.stringify(t.config),event_types:Ra(t.event_types)}),Ys=async(t,a)=>{const l={...a};return"config"in a&&(l.config=JSON.stringify(a.config)),"event_types"in a&&(l.event_types=Ra(a.event_types)),Be(`/notification-channels/${t}`,l)},zr=async t=>Ze(`/notification-channels/${t}`),Ur=async(t,a)=>{const l=await Le(`/message-notifications/${t}`,void 0,a);return(l==null?void 0:l.channel_ids)||[]},Wr=async t=>Ce(`/notification-channels/${t}/test`,{}),Xs=async()=>Le("/api/default-replies"),Jr=async t=>{const a=await Le(`/api/default-reply/${t}`);return{cookie_id:t,enabled:a.enabled||!1,reply_content:a.reply_content||"",reply_once:a.reply_once||!1,reply_image_url:a.reply_image_url||""}},Vr=async(t,a)=>Be(`/api/default-reply/${t}`,{enabled:a.enabled??!1,reply_content:a.reply_content||"",reply_once:a.reply_once??!1,reply_image_url:a.reply_image_url||""}),Qr=async t=>Ze(`/api/default-reply/${t}`),Gr=async t=>Ce(`/api/default-reply/${t}/clear-records`,{}),At=t=>String(t).padStart(2,"0"),bs=t=>{if(t==null||t==="")return"-";const a=t instanceof Date?t:new Date(t);return Number.isNaN(a.getTime())?"-":[a.getFullYear(),At(a.getMonth()+1),At(a.getDate())].join("-")+" "+[At(a.getHours()),At(a.getMinutes()),At(a.getSeconds())].join(":")},_e=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Kr=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},Wt=({title:t,value:a,icon:l,colorClass:i,trend:m})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${i} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${i} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(l,{className:`w-6 h-6 ${i.replace("bg-","text-")}`})}),m&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(Ga,{className:"w-3 h-3"})," ",m]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:a}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),rs=()=>{var V,X;const[t,a]=r.useState(null),[l,i]=r.useState(null),[m,_]=r.useState(""),[N,R]=r.useState("7days"),[g,C]=r.useState(""),[j,F]=r.useState(""),[G,me]=r.useState(null),[oe,v]=r.useState(""),[q,ce]=r.useState([]),[Q,ee]=r.useState(0),[B,ge]=r.useState(!1),[ue,k]=r.useState(!1),[Z,se]=r.useState([]),[K,ve]=r.useState({}),J=r.useRef(0),I=[_e("brand"),_e("brand-highlight"),_e("success-500"),_e("warning-500"),_e("accent-500")],E=c=>`¥${Number(c||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`,$=async c=>{let d;try{d=Js(c,new Date,g,j)}catch(Se){_(Se instanceof Error?Se.message:"日期范围无效");return}const{startDate:D,endDate:S}=d,Y={start_date:D,end_date:S},O=Ol(d),de=++J.current;k(!0),_("");try{const[Se,fe,Oe]=await Promise.all([Gs(Y),Gs({start_date:O.startDate,end_date:O.endDate}),cr(Y)]);if(de!==J.current)return;i(Se),me(fe),ce(Oe.orders),ee(Oe.total),ge(Oe.truncated)}catch(Se){de===J.current&&_(Se instanceof Error?Se.message:"经营数据加载失败")}finally{de===J.current&&k(!1)}},be=()=>{if(!l||!G)return null;const c=l.revenue_stats.total_amount,d=G.revenue_stats.total_amount;if(d===0)return c>0?"+100%":"0%";const D=(c-d)/d*100;return`${D>=0?"+":""}${D.toFixed(1)}%`};if(r.useEffect(()=>{let c=!1;return Promise.all([or(),vt()]).then(([d,D])=>{if(c)return;a(d),se(D);const S={};D.forEach(Y=>{S[Y.item_id]=Y.item_title||Y.item_id}),ve(S)}).catch(d=>{c||_(d instanceof Error?d.message:"概览加载失败")}),()=>{c=!0}},[]),r.useEffect(()=>{N!=="custom"&&$(N)},[N]),m&&(!t||!l))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(rt,{className:"w-8 h-8"}),e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:()=>window.location.reload(),children:"重新加载"})]});if(!t||!l)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx($s,{className:"w-8 h-8 animate-spin text-brand"})});const Re=((V=l.daily_stats)==null?void 0:V.map(c=>({name:c.date.slice(5),amount:c.amount,orders:c.order_count,avgAmount:c.order_count>0?(c.amount/c.order_count).toFixed(2):0})))||[],ae=l.item_stats||[],T=l.revenue_stats.total_orders||0,p=l.revenue_stats.total_amount||0,b=ae.length>0?ae.map(c=>({name:(K[c.item_id]||c.item_id).length>12?(K[c.item_id]||c.item_id).substring(0,12)+"...":K[c.item_id]||c.item_id,sales:c.order_count})).sort((c,d)=>d.sales-c.sales).slice(0,10):[],U=Math.max(...b.map(c=>c.sales),1),M=ae.length>0?ae.map(c=>({name:(K[c.item_id]||c.item_id).length>10?(K[c.item_id]||c.item_id).substring(0,10)+"...":K[c.item_id]||c.item_id,value:c.order_count,percent:T>0?c.order_count/T*100:0})).sort((c,d)=>d.value-c.value).slice(0,6).map((c,d)=>({...c,color:I[d%I.length]})):[],ne=ae.length>0?ae.map(c=>({name:(K[c.item_id]||c.item_id).length>12?(K[c.item_id]||c.item_id).substring(0,12)+"...":K[c.item_id]||c.item_id,value:c.total_amount,orderCount:c.order_count,percentage:p>0?c.total_amount/p*100:0})).sort((c,d)=>d.value-c.value).slice(0,5).map((c,d)=>({...c,color:I[d%I.length],percentage:c.percentage.toFixed(1)})):[],he=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}],ye=((X=he.find(c=>c.key===N))==null?void 0:X.label)||"所选范围";let Ee;try{Ee=Js(N,new Date,g,j)}catch{Ee={startDate:g,endDate:j}}const ke=oe.trim().toLowerCase(),x=q.filter(c=>{var d,D,S,Y;return((d=c.order_id)==null?void 0:d.toLowerCase().includes(ke))||((D=c.item_id)==null?void 0:D.toLowerCase().includes(ke))||((S=c.item_title)==null?void 0:S.toLowerCase().includes(ke))||((Y=c.buyer_id)==null?void 0:Y.toLowerCase().includes(ke))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[he.map(c=>e.jsx("button",{onClick:()=>R(c.key),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${N===c.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:c.label},c.key)),N==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:g,onChange:c=>C(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:j,onChange:c=>F(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:()=>{try{_(""),$("custom")}catch(c){_(c instanceof Error?c.message:"日期范围无效")}},className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(Wt,{title:"累计营收 (CNY)",value:`¥${l.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:Qa,colorClass:"bg-blue-400",trend:be()||void 0}),e.jsx(Wt,{title:"活跃账号 / 总数",value:`${t.active_cookies} / ${t.total_cookies}`,icon:ha,colorClass:"bg-blue-500"}),e.jsx(Wt,{title:"订单数",value:l.revenue_stats.total_orders.toLocaleString(),icon:Ps,colorClass:"bg-blue-500"}),e.jsx(Wt,{title:"库存卡密余量",value:t.available_card_stock,icon:fa,colorClass:"bg-purple-500"})]}),e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[ye,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:Re.length===0||l.revenue_stats.total_amount===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(Ps,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):Re.length<=2?e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(bl,{data:Re,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Bs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:_e("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(zs,{axisLine:!1,tickLine:!1,tick:{fill:_e("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:c=>`¥${c}`}),e.jsx(Ut,{contentStyle:{backgroundColor:_e("white"),borderRadius:"8px",border:`1px solid ${_e("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:_e("neutral-500"),fontWeight:500},itemStyle:{color:_e("brand"),fontWeight:600},cursor:{fill:_e("brand",.08)},formatter:c=>[`¥${Number(c).toFixed(2)}`,"营收"]}),e.jsx(fl,{dataKey:"amount",fill:_e("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:Re.map((c,d)=>e.jsx(ts,{fill:_e("brand"),stroke:"none",strokeWidth:0},`cell-${d}`))})]})}):e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(yl,{data:Re,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:_e("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:_e("brand"),stopOpacity:0})]})}),e.jsx(Bs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:_e("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(zs,{axisLine:!1,tickLine:!1,tick:{fill:_e("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(jl,{vertical:!1,stroke:_e("neutral-100"),strokeDasharray:"3 3"}),e.jsx(Ut,{contentStyle:{backgroundColor:_e("white"),borderRadius:"8px",border:`1px solid ${_e("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:_e("neutral-500"),fontWeight:500},itemStyle:{color:_e("brand"),fontWeight:600},cursor:{stroke:_e("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Nl,{type:"monotone",dataKey:"amount",stroke:_e("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:_e("white"),stroke:_e("brand"),strokeWidth:2}})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:b.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:b.map((c,d)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${d<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:d+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:c.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[c.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${Math.max(8,c.sales/U*100)}%`}})})]},`${c.name}-${d}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${T} 单`,children:M.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(Us,{accessibilityLayer:!1,children:[e.jsx(Ws,{data:M,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:M.map((c,d)=>e.jsx(ts,{fill:c.color},`cell-${d}`))}),e.jsx(Ut,{formatter:c=>`${Number(c||0)} 单`,wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:_e("white"),border:`1px solid ${_e("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(_l,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:c=>e.jsx("span",{style:{color:_e("neutral-500"),fontWeight:500},children:c})})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:T}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),B&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",q.length," / ",Q," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:oe,onChange:c=>v(c.target.value),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:ue?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx($s,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):x.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(qt,{className:"w-7 h-7 text-gray-300"})}),ke?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",q.length," 单参与统计,但没有订单号、商品、买家匹配“",oe,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",Ee.startDate," 至 ",Ee.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",l.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:x.map(c=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(qt,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:c.item_title||c.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:c.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",c.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:c.buyer_id}),c.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:bs(c.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",c.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(Kr,{status:c.status||c.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${c.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(ya,{className:"w-4 h-4"})})})]},c.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),ne.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${E(p)}`,children:[e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(Us,{accessibilityLayer:!1,children:[e.jsx(Ws,{data:ne,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:ne.map((c,d)=>e.jsx(ts,{fill:c.color||I[d%I.length]},`cell-${d}`))}),e.jsx(Ut,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:_e("white"),border:`1px solid ${_e("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:c=>`¥${Number(c||0).toLocaleString()}`})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:E(p)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:ne.map(c=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:c.color||I[ne.indexOf(c)%I.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:c.name,children:c.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",c.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[c.percentage,"%"]})]})]},c.name))})]})]})]})]})},Hr=(t,a)=>{const l=a.pause_duration||0;return t!==l},Zr=(t,a)=>{const l=a.username!==(t.username||""),i=a.show_browser!==(t.show_browser||!1),m=a.login_password!=="",_=a.clear_password===!0;if(!l&&!i&&!m&&!_)return null;const N={username:a.username,show_browser:a.show_browser};return _?N.clear_password=!0:m&&(N.login_password=a.login_password),N},Yr=(t,a)=>t&&a,Xr=(t,a)=>{if(!t||!a)return!1;const l=Date.parse(t),i=Date.parse(a);return Number.isFinite(l)&&Number.isFinite(i)&&it.map(l=>{const i=a[l.id];return!i||Xr(l.runtime_updated_at,i.updated_at)?l:{...l,runtime_state:i.state,runtime_message:i.message||"",runtime_connected:i.connected,runtime_updated_at:i.updated_at}}),tn=new Set(["expired","cancelled","error","not_found"]),Jt=()=>{let t=0;return{next:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:a=>a===t}},sn=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let a=null,l=null,i=-1,m=0;const _=()=>{m+=1,l==null||l.abort(),l=null,a!==null&&(t.clearInterval(a),a=null)};return{start:(R,g,C,j=2e3)=>{_();const F=m;l=new AbortController;const G=l.signal;a=t.setInterval(()=>{i===F||F!==m||(i=F,(async()=>{var me,oe;try{const v=await g(R,G);if(v.status==="success"){_(),await C.onSuccess(v);return}if(v.status==="scanned"){(me=C.onScanned)==null||me.call(C,v);return}if(v.status==="verification_required"){(oe=C.onVerificationRequired)==null||oe.call(C,v);return}v.status&&tn.has(v.status)&&(_(),C.onTerminalError(v))}catch(v){if(G.aborted||F!==m)return;_(),C.onPollError(v)}finally{i===F&&(i=-1)}})())},j)},stop:_,isActive:()=>a!==null}},an=({faceQrUrl:t,verificationScreenshot:a})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(Ka,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:t?e.jsx("img",{src:t,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):a?e.jsx("img",{src:a,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(Pe,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),ea=({src:t,alt:a,className:l=""})=>e.jsx("img",{src:t,alt:a,className:`block aspect-square h-auto w-full object-contain ${l}`.trim()}),ta=({checked:t,onChange:a,label:l})=>e.jsx("button",{type:"button","aria-label":l,"aria-pressed":t,onClick:a,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-6":""}`})}),ln=({account:t,onClose:a,onSaved:l})=>{const[i,m]=r.useState({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),[_,N]=r.useState(!1),[R,g]=r.useState(""),[C,j]=r.useState(""),[F,G]=r.useState(null),me=async()=>{N(!0),j("");try{const v=await Vs(t.id,i);m(v),l(v)}catch(v){j(v instanceof Error?v.message:"保存失败")}finally{N(!1)}},oe=async v=>{g(v),j(""),G(null);try{await Vs(t.id,i);const q=await Tl(t.id,v),ce=await Dl(t.id);G(q.summary),m(ce),l(ce)}catch(q){j(q instanceof Error?q.message:"任务执行失败")}finally{g("")}};return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:a,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(Me,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(Ha,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(ta,{checked:i.auto_rate_enabled,onChange:()=>m(v=>({...v,auto_rate_enabled:!v.auto_rate_enabled})),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:i.rate_content,maxLength:500,onChange:v=>m(q=>({...q,rate_content:v.target.value})),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",i.last_rate_scan_at?new Date(i.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:R!==""||!t.enabled,onClick:()=>void oe("auto_rate"),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[R==="auto_rate"?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(Za,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(vs,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(ta,{checked:i.auto_polish_enabled,onChange:()=>m(v=>({...v,auto_polish_enabled:!v.auto_polish_enabled})),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:i.polish_time,onChange:v=>m(q=>({...q,polish_time:v.target.value})),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:R!==""||!t.enabled,onClick:()=>void oe("auto_polish"),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[R==="auto_polish"?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(ja,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",i.last_polish_at?new Date(i.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),F&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",F.found," 项,成功 ",F.success,",失败 ",F.failed,",跳过 ",F.skipped,"。",F.message||""]}),C&&e.jsx("div",{className:"rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:C})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:a,disabled:_||R!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:()=>void me(),disabled:_||R!==""||i.auto_rate_enabled&&!i.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[_?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(He,{className:"h-4 w-4"}),"保存"]})]})})]})})},rn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState(!0),[m,_]=r.useState(""),[N,R]=r.useState(""),[g,C]=r.useState(""),[j,F]=r.useState(null),[G,me]=r.useState(""),[oe,v]=r.useState(!1),[q,ce]=r.useState(""),[Q,ee]=r.useState("pending"),[B,ge]=r.useState(""),[ue,k]=r.useState(""),[Z,se]=r.useState(""),[K,ve]=r.useState(null),[J,I]=r.useState(null),[E,$]=r.useState(null),[be,Re]=r.useState(null),[ae,T]=r.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[p,b]=r.useState([]),[U,M]=r.useState([]),[ne,he]=r.useState(!1),[ye,Ee]=r.useState(!1),[ke,x]=r.useState(!1),[V,X]=r.useState(""),[c,d]=r.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),[D,S]=r.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[Y,O]=r.useState(!1),[de,Se]=r.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),fe=r.useRef(null),Oe=r.useRef(null),re=r.useRef(null),h=r.useRef(null),f=r.useRef(null),P=r.useRef(null),z=r.useRef(null),Ie=r.useRef(null),Ae=r.useRef(null),we=r.useRef(null),De=r.useRef(null),te=r.useRef(null),je=r.useRef(0);fe.current===null&&(fe.current=sn()),Oe.current===null&&(Oe.current=Jt()),re.current===null&&(re.current=Jt()),h.current===null&&(h.current=Jt()),f.current===null&&(f.current=Jt());const u=()=>{De.current!==null&&(window.clearTimeout(De.current),De.current=null)},L=()=>{te.current!==null&&(window.clearTimeout(te.current),te.current=null)},le=()=>{var s;(s=fe.current)==null||s.stop()},Ne=()=>{var s,o;(s=Ae.current)==null||s.abort(),(o=Oe.current)==null||o.cancel(),le(),u(),v(!1)},Ue=()=>{u(),De.current=window.setTimeout(()=>{De.current=null,v(!1),Fe()},1e3)},Fe=async()=>{var y,A,W,pe,xe;const s=re.current.next();(y=P.current)==null||y.abort();const o=new AbortController;P.current=o,i(!0);try{const $e={signal:o.signal},[ie,Ye]=await Promise.allSettled([Ft($e),er($e)]);if(!((A=re.current)!=null&&A.isCurrent(s)))return;if(ie.status==="rejected")throw ie.reason;const Ve=ie.value,It=Ye.status==="fulfilled"?Ye.value:{};Ye.status==="rejected"&&console.error("Failed to load AI settings:",Ye.reason);const Ua=Ve.map(gt=>{var Cs,Ss,Ls,Os,Is;return{...gt,ai_enabled:((Cs=It[gt.id])==null?void 0:Cs.ai_enabled)??!1,max_discount_percent:((Ss=It[gt.id])==null?void 0:Ss.max_discount_percent)??10,max_discount_amount:((Ls=It[gt.id])==null?void 0:Ls.max_discount_amount)??100,max_bargain_rounds:((Os=It[gt.id])==null?void 0:Os.max_bargain_rounds)??3,custom_prompts:((Is=It[gt.id])==null?void 0:Is.custom_prompts)??""}});(W=re.current)!=null&&W.isCurrent(s)&&a(Ua)}catch($e){(pe=re.current)!=null&&pe.isCurrent(s)&&!o.signal.aborted&&console.error("Failed to load accounts:",$e)}finally{(xe=re.current)!=null&&xe.isCurrent(s)&&i(!1)}};r.useEffect(()=>{let s=!1,o=null;const y=new AbortController,A=async()=>{try{const W=await hs({signal:y.signal,timeoutMs:1e4});s||a(pe=>en(pe,W))}catch(W){s||console.error("Failed to load account runtime statuses:",W)}finally{s||(o=window.setTimeout(()=>void A(),2e3))}};return Fe().finally(()=>{s||A()}),()=>{s=!0,y.abort(),o!==null&&window.clearTimeout(o)}},[]),r.useEffect(()=>()=>{var s,o,y,A,W,pe,xe,$e,ie;le(),(s=Oe.current)==null||s.cancel(),(o=re.current)==null||o.cancel(),(y=h.current)==null||y.cancel(),(A=f.current)==null||A.cancel(),(W=P.current)==null||W.abort(),(pe=z.current)==null||pe.abort(),(xe=Ie.current)==null||xe.abort(),($e=Ae.current)==null||$e.abort(),(ie=we.current)==null||ie.abort(),u(),je.current+=1,L()},[]);const tt=s=>{if(!s.enabled||s.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(s.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},kt=async(s,o)=>{await Wl(s,!o),Fe()},Je=s=>{g||(me(""),F(s))},We=()=>{g||(me(""),F(null))},Ct=async()=>{const s=j;if(!(!s||g)){C(s.id),me("");try{await Jl(s.id),a(o=>o.filter(y=>y.id!==s.id)),F(null)}catch(o){console.error("删除账号失败:",o),me((o==null?void 0:o.message)||"删除账号失败,请稍后重试")}finally{C("")}}},St=async s=>{R(s.id);try{const o=await Xl(s.id);o!=null&&o.profile_error&&alert("资料刷新失败:"+o.profile_error),await Fe()}catch(o){console.error("刷新账号资料失败:",o),alert((o==null?void 0:o.message)||"刷新账号资料失败,请先重新授权该账号")}finally{R("")}},mt=async s=>{var pe,xe;const o=h.current.next();(pe=z.current)==null||pe.abort();const y=new AbortController;z.current=y,Ee(!0),he(!1),x(!1),X("");const[A,W]=await Promise.allSettled([Ea({signal:y.signal}),Ur(s,{signal:y.signal})]);(xe=h.current)!=null&&xe.isCurrent(o)&&(A.status==="fulfilled"?b(A.value.data||[]):(b([]),X("通知渠道列表加载失败,请重试")),W.status==="fulfilled"?(M(W.value||[]),he(!0)):(M([]),X("通知绑定加载失败;本次保存不会修改现有绑定")),Ee(!1))},Lt=async s=>{var y;je.current+=1,(y=we.current)==null||y.abort(),L(),Se({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),$(s),d({remark:s.remark||s.note||"",cookie:s.cookie||s.value||"",auto_confirm:s.auto_confirm||!1,pause_duration:s.pause_duration||0,username:s.username||"",login_password:s.login_password||"",show_browser:s.show_browser||!1,showLoginPassword:!1,clear_password:!1}),I("edit"),T({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,o]=await Promise.allSettled([mt(s.id),Gl(s.id)]);o.status==="fulfilled"?T({loading:!1,saving:!1,canOpen:o.value.can_open_long_login,enabled:o.value.enabled,error:""}):T({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"})},nt=async()=>{if(!E||ae.loading||ae.saving||!ae.canOpen)return;const s=!ae.enabled;T(o=>({...o,saving:!0,error:""}));try{const o=await Kl(E.id,s);T({loading:!1,saving:!1,canOpen:o.can_open_long_login,enabled:o.enabled,error:""})}catch(o){T(y=>({...y,saving:!1,error:o instanceof Error?o.message:"保存登录信息设置失败"}))}},it=async s=>{var A,W,pe,xe;const o=f.current.next();(A=Ie.current)==null||A.abort();const y=new AbortController;Ie.current=y,$(s),I("ai-settings"),O(!0);try{const $e=await Tr(s.id,{signal:y.signal});if(!((W=f.current)!=null&&W.isCurrent(o)))return;S({ai_enabled:$e.ai_enabled??!1,max_discount_percent:$e.max_discount_percent??10,max_discount_amount:$e.max_discount_amount??100,max_bargain_rounds:$e.max_bargain_rounds??3,custom_prompts:$e.custom_prompts??""})}catch($e){(pe=f.current)!=null&&pe.isCurrent(o)&&console.error("Failed to load AI settings:",$e)}finally{(xe=f.current)!=null&&xe.isCurrent(o)&&O(!1)}},Ot=async()=>{if(E){O(!0);try{const s={};c.remark!==(E.remark||E.note||"")&&(s.remark=c.remark),c.cookie&&c.cookie!==(E.cookie||E.value||"")&&(s.cookie=c.cookie),c.auto_confirm!==E.auto_confirm&&(s.auto_confirm=c.auto_confirm),Hr(c.pause_duration,E)&&(s.pause_duration=c.pause_duration);const o=Zr(E,c);o&&Object.assign(s,o),Yr(ne,ke)&&(s.channel_ids=U),Object.keys(s).length>0&&await Ql(E.id,s),I(null),Fe()}catch(s){console.error("更新账号失败:",s),alert("更新失败,请重试")}finally{O(!1)}}},pt=async()=>{if(!(!E||c.pause_duration<=0)){O(!0);try{const s=await Vl(E.id,c.pause_duration);$({...E,pause_duration:c.pause_duration,paused:(s==null?void 0:s.paused)===!0,paused_until:Number((s==null?void 0:s.paused_until)||0)}),await Fe()}catch(s){alert(s instanceof Error?s.message:"重新暂停失败")}finally{O(!1)}}},ut=async()=>{if(E){O(!0);try{await Mr(E.id,D),I(null),Fe()}catch(s){console.error("更新AI设置失败:",s),alert("更新失败,请重试")}finally{O(!1)}}},st=async(s,o)=>{var A;(A=we.current)==null||A.abort();const y=new AbortController;we.current=y;try{const W=await Zl(s,y.signal);if(o!==je.current)return;if(W.status==="success"){L(),Se({sessionId:s,status:"success",message:W.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}),d(pe=>({...pe,login_password:"",showLoginPassword:!1})),await Fe();return}if(W.status==="processing"||W.status==="verification_required"){Se({sessionId:s,status:W.status,message:W.message||(W.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:W.qr_code_url||""}),L(),te.current=window.setTimeout(()=>void st(s,o),1500);return}L(),Se({sessionId:s,status:"failed",message:W.error||W.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""})}catch(W){if(o!==je.current)return;L(),Se({sessionId:s,status:"failed",message:W instanceof Error?W.message:"查询密码登录状态失败",qrCodeUrl:""})}},ht=async()=>{var y;if(!E)return;const s=c.username.trim();if(!s||!c.login_password){alert("请先填写登录账号和本次登录密码");return}L(),(y=we.current)==null||y.abort();const o=++je.current;Se({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const A=await Hl({account_id:E.id,account:s,password:c.login_password,show_browser:c.show_browser});if(o!==je.current)return;if(!A.success||!A.session_id)throw new Error(A.message||"无法启动密码登录");Se({sessionId:A.session_id,status:"processing",message:A.message||"登录处理中",qrCodeUrl:""}),await st(A.session_id,o)}catch(A){if(o!==je.current)return;Se({sessionId:"",status:"failed",message:A instanceof Error?A.message:"启动密码登录失败",qrCodeUrl:""})}},Ge=async()=>{var o;const s=de.sessionId;if(je.current+=1,(o=we.current)==null||o.abort(),L(),s)try{await Yl(s)}catch(y){console.error("取消密码登录失败",y)}Se({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},ot=async()=>{var s,o;(s=h.current)==null||s.cancel(),(o=z.current)==null||o.abort(),(de.status==="processing"||de.status==="verification_required")&&await Ge(),I(null)},n=()=>{var s,o;(s=f.current)==null||s.cancel(),(o=Ie.current)==null||o.abort(),I(null)},w=async(s,o)=>{const y=await Ul(s,o==null?void 0:o.id);if(!y.success||!y.account_id)throw new Error(y.message||"保存扫码授权失败");return y.account_id},H=async s=>{var W,pe,xe,$e;le(),(W=Ae.current)==null||W.abort();const o=new AbortController;Ae.current=o;const y=Oe.current.next();u();const A=s||null;ve(A),v(!0),ee("loading"),ge(""),ce(""),k(""),se("");try{const ie=await Bl({signal:o.signal});if(!((pe=Oe.current)!=null&&pe.isCurrent(y)))return;if(!ie.success||!ie.qr_code_url||!ie.session_id)throw new Error(ie.message||"闲鱼未返回可用的登录二维码");if(ie.success&&ie.qr_code_url&&ie.session_id){const Ye=ie.session_id;ce(ie.qr_code_url),ee("waiting"),(xe=fe.current)==null||xe.start(Ye,zl,{onSuccess:async()=>{try{if(!await w(Ye,A)){ee("error");return}}catch(Ve){console.error("保存扫码授权失败",Ve),ee("error");return}ee("success"),Ue()},onScanned:()=>{ee("waiting")},onTerminalError:()=>{ee("error")},onPollError:Ve=>{console.error("轮询扫码状态失败",Ve),ee("error")},onVerificationRequired:Ve=>{ee("verification"),Ve.face_qr_url&&se(Ve.face_qr_url),Ve.verification_screenshot&&k(Ve.verification_screenshot)}})}}catch(ie){if(!(($e=Oe.current)!=null&&$e.isCurrent(y)))return;ge(ie instanceof Error?ie.message:"二维码获取失败,请稍后重试"),ee("error")}finally{Ae.current===o&&(Ae.current=null)}};if(l)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(Pe,{className:"w-8 h-8 text-brand animate-spin"})});const Te=t.filter(s=>{const o=m.trim().toLowerCase();return o?[s.id,s.nickname,s.remark,s.note,s.username,s.runtime_message].some(y=>(y||"").toLowerCase().includes(o)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:m,onChange:s=>_(s.target.value),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:()=>H(),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Xt,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",Te.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[Te.map(s=>{const o=tt(s),y=s.runtime_state==="auth_expired"||s.runtime_state==="verification_required";return e.jsx("div",{className:"ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-5 sm:gap-8",children:[e.jsxs("div",{className:"relative",children:[s.avatar_url?e.jsx("img",{src:s.avatar_url,alt:s.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(xt,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${o.dot}`,children:s.runtime_state==="online"&&e.jsx(Ke,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:s.nickname||s.remark||`账号 ${s.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${o.badge}`,children:o.label}),s.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(yt,{className:"w-3 h-3"})," AI"]}),s.auto_rate_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700",children:[e.jsx(Tt,{className:"h-3 w-3"})," 自动评价"]}),s.auto_polish_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700",children:[e.jsx(vs,{className:"h-3 w-3"})," 每日擦亮"]}),s.auto_confirm&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700",children:[e.jsx(Ke,{className:"h-3 w-3"})," 自动确认发货"]}),s.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:s.profile_error,children:[e.jsx(rt,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"text-sm font-medium text-gray-500",children:[e.jsx("p",{children:s.remark||s.note||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",s.id]})]}),s.runtime_message&&s.runtime_state!=="online"&&s.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${y?"text-red-700":"text-amber-700"}`,children:[e.jsx(rt,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:s.runtime_message}),y&&e.jsxs("button",{type:"button",onClick:()=>H(s),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(Xt,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),s.paused&&e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700",children:[e.jsx(Rs,{className:"h-3 w-3"})," 暂停处理中"]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>St(s),disabled:N===s.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(ze,{className:`w-5 h-5 ${N===s.id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>H(s),className:`p-3 rounded-xl transition-colors ${y?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(Xt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Lt(s),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Na,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>it(s),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(yt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Re(s),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(ja,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>kt(s.id,s.enabled),className:`p-3 rounded-xl transition-colors ${s.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:s.enabled?"停用账号":"启用账号",children:e.jsx(Ya,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Je(s),disabled:g!=="",className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:g===s.id?"删除中…":`删除账号 ${s.nickname||s.remark||s.id}`,children:g===s.id?e.jsx(Pe,{className:"w-5 h-5 animate-spin"}):e.jsx(Qe,{className:"w-5 h-5"})})]})]})]})]})},s.id)}),t.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(xt,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),t.length>0&&Te.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),be&&qe.createPortal(e.jsx(ln,{account:be,onClose:()=>Re(null),onSaved:s=>{a(o=>o.map(y=>y.id===be.id?{...y,auto_rate_enabled:s.auto_rate_enabled,rate_content:s.rate_content,auto_polish_enabled:s.auto_polish_enabled,polish_time:s.polish_time,last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}:y))}}),document.body),j&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",role:"presentation",children:e.jsxs("div",{className:"h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal",role:"dialog","aria-modal":"true","aria-labelledby":"delete-account-title","aria-describedby":"delete-account-description",children:[e.jsxs("div",{className:"relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5",children:[e.jsx("div",{className:"absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl"}),e.jsxs("div",{className:"relative flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200",children:e.jsx(Qe,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{id:"delete-account-title",className:"text-lg font-extrabold tracking-tight text-gray-950",children:"删除这个账号?"}),e.jsx("p",{id:"delete-account-description",className:"mt-1 text-xs leading-5 text-gray-600",children:"删除后,该账号的关联配置也会一并清理,此操作无法撤销。"})]}),e.jsx("button",{type:"button",onClick:We,disabled:g!=="",className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"关闭删除确认",children:e.jsx(Me,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:j.nickname||j.remark||"未命名账号"}),j.remark&&j.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",j.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",j.id]})]}),g===j.id&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(Pe,{className:"h-5 w-5 flex-shrink-0 animate-spin text-brand"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-blue-950",children:"正在删除账号"}),e.jsx("div",{className:"mt-0.5 text-xs text-blue-700",children:"正在清理关联数据,请保持页面打开…"})]})]}),G&&e.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3",role:"alert",children:[e.jsx(rt,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-red-800",children:"删除失败"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-red-700",children:G})]})]})]}),e.jsxs("div",{className:"flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4",children:[e.jsx("button",{type:"button",onClick:We,disabled:g!=="",className:"flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50",children:"取消"}),e.jsx("button",{type:"button",onClick:()=>void Ct(),disabled:g!=="",className:"flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400",children:g===j.id?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),oe&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:Ne,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:K?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:K?`请用闲鱼APP扫码,为「${K.nickname||K.remark||K.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${Q==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[Q==="loading"&&e.jsx(Pe,{className:"w-10 h-10 text-brand animate-spin"}),Q==="waiting"&&e.jsx(ea,{src:q,alt:"闲鱼登录二维码",className:"p-2"}),Q==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Ke,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),Q==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:B||"请关闭窗口后重新发起扫码登录。"})]}),Q==="verification"&&e.jsx(an,{faceQrUrl:Z,verificationScreenshot:ue})]}),Q!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),J==="edit"&&E&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:E.nickname||E.remark||E.id})]}),e.jsx("button",{onClick:()=>void ot(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:E.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:c.remark,onChange:s=>d({...c,remark:s.target.value}),placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:c.cookie,onChange:s=>d({...c,cookie:s.target.value}),placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",c.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:()=>d({...c,auto_confirm:!c.auto_confirm}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${c.auto_confirm?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${c.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(Rs,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:c.pause_duration,onChange:s=>d({...c,pause_duration:parseInt(s.target.value)||0}),placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),c.pause_duration>0&&!E.paused&&c.pause_duration===(E.pause_duration||0)&&e.jsx("button",{type:"button",disabled:Y,onClick:()=>void pt(),className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(Xa,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),ae.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:ae.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:ae.loading||ae.saving||!ae.canOpen,onClick:()=>void nt(),className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${ae.enabled?"bg-brand":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${ae.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:c.username,onChange:s=>d({...c,username:s.target.value}),placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:c.showLoginPassword?"text":"password",value:c.login_password,onChange:s=>d({...c,login_password:s.target.value,clear_password:!1}),placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:()=>d({...c,showLoginPassword:!c.showLoginPassword}),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:c.showLoginPassword?e.jsx(dt,{className:"w-5 h-5"}):e.jsx(lt,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:c.clear_password,onChange:s=>d({...c,clear_password:s.target.checked,login_password:s.target.checked?"":c.login_password}),className:"w-4 h-4 accent-brand"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:()=>d({...c,show_browser:!c.show_browser}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${c.show_browser?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${c.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),de.status==="processing"||de.status==="verification_required"?e.jsx("button",{type:"button",onClick:Ge,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:ht,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),de.message&&e.jsx("div",{className:`text-sm font-medium ${de.status==="failed"?"text-red-700":de.status==="success"?"text-green-700":"text-blue-800"}`,children:de.message}),de.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),de.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(ea,{src:de.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(p.length>0||ye||V)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(jt,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),ye&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Pe,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),V&&!ye&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:V}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:()=>mt(E.id),children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:p.map(s=>{const o=U.includes(Number(s.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:()=>{ne&&(M(y=>o?y.filter(A=>A!==Number(s.id)):[...y,Number(s.id)]),x(!0))},disabled:!ne,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${o?"bg-brand border-brand":"bg-white border-gray-300"}`,children:o&&e.jsx(Ke,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:s.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[s.type,s.enabled?"":" · 已停用"]})]})]},s.id)})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>void ot(),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Y,children:"取消"}),e.jsxs("button",{onClick:Ot,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Y,children:[Y?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),Y?"保存中...":"保存"]})]})})]})}),document.body),J==="ai-settings"&&E&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(yt,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:E.nickname||E.remark||E.id})]}),e.jsx("button",{onClick:n,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(yt,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:()=>S({...D,ai_enabled:!D.ai_enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${D.ai_enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${D.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:D.max_discount_percent,onChange:s=>S({...D,max_discount_percent:parseInt(s.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:D.max_discount_amount,onChange:s=>S({...D,max_discount_amount:parseInt(s.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:D.max_bargain_rounds,onChange:s=>S({...D,max_bargain_rounds:parseInt(s.target.value)||1}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:D.custom_prompts,onChange:s=>S({...D,custom_prompts:s.target.value}),placeholder:`输入自定义的AI回复规则或风格指引... +import{j as e,r,c as ys,b as qe,d as Wa}from"./react-vendor-C_od1ZSF.js";import{L as Ja,U as ha,M as is,C as os,B as ga,S as ba,Z as cs,a as jt,b as js,G as As,c as Ns,d as _s,e as Va,f as rt,A as $s,D as Qa,g as Ps,P as fa,h as qt,E as ya,T as Ga,i as Ka,j as Pe,X as Me,k as Ha,l as Za,m as vs,n as ja,o as He,Q as Xt,p as xt,q as Ke,r as yt,s as Tt,t as Rs,R as ze,u as Na,v as Ya,w as Qe,K as Xa,x as dt,y as lt,z as et,F as Es,H as _t,I as Nt,J as Dt,N as _a,O as el,V as Ds,W as Ts,Y as tl,_ as sl,$ as al,a0 as ll,a1 as es,a2 as Bt,a3 as ds,a4 as rl,a5 as nl,a6 as xs,a7 as Ms,a8 as il,a9 as ol,aa as Mt,ab as qs,ac as Gt,ad as va,ae as cl,af as dl,ag as Zt,ah as wa,ai as xl,aj as ml,ak as pl,al as ul,am as hl,an as gl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as bl,X as Bs,Y as zs,T as Ut,a as fl,C as ts,A as yl,b as jl,c as Nl,P as Us,d as Ws,L as _l}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const _ of m)if(_.type==="childList")for(const N of _.addedNodes)N.tagName==="LINK"&&N.rel==="modulepreload"&&i(N)}).observe(document,{childList:!0,subtree:!0});function l(m){const _={};return m.integrity&&(_.integrity=m.integrity),m.referrerPolicy&&(_.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?_.credentials="include":m.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function i(m){if(m.ep)return;m.ep=!0;const _=l(m);fetch(m.href,_)}})();const vl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),e.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:e.jsx(vl,{className:a})})]})]}),wl=({activeTab:t,isAdmin:a=!1,collapsed:l,onToggleCollapsed:i,onNavigate:m,onLogout:_})=>{const[N,R]=r.useState({version:"dev",commit:"unknown"});r.useEffect(()=>{const j=new AbortController;return fetch("/health",{signal:j.signal}).then(F=>F.ok?F.json():Promise.reject(new Error("health request failed"))).then(F=>R({version:String(F.version||"dev"),commit:String(F.commit||"unknown")})).catch(F=>{F instanceof DOMException&&F.name}),()=>j.abort()},[]);const g=[{id:"dashboard",icon:Ja,label:"仪表盘"},{id:"accounts",icon:ha,label:"账号管理"},{id:"chat",icon:is,label:"在线聊天"},{id:"cards",icon:os,label:"卡密库存"},{id:"items",icon:ga,label:"商品列表"},{id:"orders",icon:ba,label:"订单管理"},{id:"rules",icon:cs,label:"自动化规则"},{id:"notifications",icon:jt,label:"通知设置"},...a?[{id:"settings",icon:js,label:"系统与AI"}]:[]],C=/^\d+\.\d+\.\d+$/.test(N.version)?`v${N.version}`:N.version;return e.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${l?"w-16":"w-64"}`,children:[e.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${l?"justify-center px-2":"gap-3 px-5"}`,children:[e.jsx(ms,{sizeClass:"h-10 w-10"}),!l&&e.jsxs("div",{className:"min-w-0 leading-tight",children:[e.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),e.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),e.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${l?"px-2":"px-3"}`,"aria-label":"主导航",children:g.map(j=>{const F=j.icon,G=t===j.id;return e.jsx(ys.Fragment,{children:e.jsxs("button",{type:"button",title:l?j.label:void 0,"aria-label":j.label,"aria-current":G?"page":void 0,onClick:()=>m(j.id),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${l?"justify-center":"gap-3 px-3.5"} ${G?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(F,{className:`h-[19px] w-[19px] shrink-0 ${G?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!l&&e.jsx("span",{className:"truncate text-sm font-bold",children:j.label}),G&&!l&&e.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},j.id)})}),e.jsxs("div",{children:[e.jsx("div",{title:l?`版本 ${N.version} · ${N.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${l?"flex justify-center px-1":"px-6"}`,children:l?e.jsx(As,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${N.version}`}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[e.jsx(As,{className:"h-3.5 w-3.5"}),"运行版本"]}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[e.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:C}),e.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:N.commit})]})]})}),e.jsxs("div",{className:`space-y-2 p-2 ${l?"":"p-3"}`,children:[e.jsxs("button",{type:"button",onClick:i,title:l?"展开侧边栏":"收起侧边栏","aria-label":l?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${l?"justify-center":"gap-3 px-3"}`,children:[l?e.jsx(Ns,{className:"h-5 w-5"}):e.jsx(_s,{className:"h-5 w-5"}),!l&&e.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),e.jsxs("button",{type:"button",onClick:_,title:l?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${l?"justify-center":"gap-3 px-3"}`,children:[e.jsx(Va,{className:"h-5 w-5"}),!l&&e.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},kl=3e4,Cl=10*6e4;let ss=!1;const ka=()=>{ss||typeof window>"u"||(ss=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{ss=!1}))},Sl=t=>{if(!t)return"";const a=new URLSearchParams;for(const[i,m]of Object.entries(t))m!=null&&a.set(i,String(m));const l=a.toString();return l?`?${l}`:""},Yt=async(t,a,l={})=>{var C;const i=Sl(l.params),m=`${a}${i}`,_=Ca(l.signal,l.timeoutMs??kl);let N;try{N=await fetch(m,{method:t,credentials:"include",signal:_.signal,headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)})}catch(j){throw _.signal.aborted?new Error((C=l.signal)!=null&&C.aborted?"请求已取消":"请求超时,请稍后重试"):j}finally{_.cleanup()}const g=(N.headers.get("content-type")||"").includes("application/json");if(!N.ok){N.status===401&&!l.skipAuthLogout&&ka();const j=g?await N.json().catch(()=>{}):await N.text().catch(()=>{}),F=Sa(j,N.status);throw new Error(F)}return g?await N.json():await N.text()},Le=async(t,a,l)=>Yt("GET",t,{params:a,...l}),Ce=async(t,a,l)=>Yt("POST",t,{body:a,...l}),Be=async(t,a,l)=>Yt("PUT",t,{body:a,...l}),Ze=async(t,a,l)=>Yt("DELETE",t,{params:a,...l}),wt=async(t,a,l={})=>{var g;const i=Ca(l.signal,l.timeoutMs??Cl);let m;try{m=await fetch(t,{method:"POST",credentials:"include",signal:i.signal,body:a})}catch(C){throw i.signal.aborted?new Error((g=l.signal)!=null&&g.aborted?"请求已取消":"上传超时,请稍后重试"):C}finally{i.cleanup()}const R=(m.headers.get("content-type")||"").includes("application/json")?await m.json().catch(()=>{}):await m.text().catch(()=>{});if(!m.ok){m.status===401&&ka();const C=Sa(R,m.status),j=new Error(C);throw j.payload=R,j}return R},Ca=(t,a)=>{const l=new AbortController,i=()=>l.abort(t==null?void 0:t.reason);t!=null&&t.aborted?i():t==null||t.addEventListener("abort",i,{once:!0});const m=globalThis.setTimeout(()=>l.abort(new DOMException("timeout","TimeoutError")),Math.max(1,a));return{signal:l.signal,cleanup:()=>{globalThis.clearTimeout(m),t==null||t.removeEventListener("abort",i)}}},Ll=t=>{if(typeof t!="object"||t===null)return!1;const a=t;return typeof a.code=="string"&&typeof a.message=="string"},Sa=(t,a)=>typeof t=="string"?t:Ll(t)?t.message:`请求失败: ${a}`,Kt=t=>{const a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${a}-${l}-${i}`},ws=(t,a)=>{const l=new Date(t);return l.setHours(12,0,0,0),l.setDate(l.getDate()+a),l},ps=(t,a)=>({startDate:Kt(ws(t,-(a-1))),endDate:Kt(t)}),Js=(t,a=new Date,l="",i="")=>{if(t==="custom"&&l&&i){if(l>i)throw new Error("开始日期不能晚于结束日期");return{startDate:l,endDate:i}}return t==="yesterday"?ps(ws(a,-1),1):ps(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Ol=t=>{const a=new Date(`${t.startDate}T12:00:00`),l=new Date(`${t.endDate}T12:00:00`),i=Math.round((l.getTime()-a.getTime())/864e5)+1,m=ws(a,-1);return ps(m,i)},Il=t=>{const a={...t};if("renewal_log_retention_days"in a){const l=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(l)?l:10}return a},Al=async t=>Ce("/api/v1/session/login",t,{skipAuthLogout:!0}),$l=async t=>Ce("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),La=async()=>Le("/api/v1/session"),Pl=async()=>Ce("/api/v1/session/logout",{}),Rl=async t=>Be("/account/credentials",t),El=(t,a)=>{const l=t.avatar_url||"";if(!l)return"";try{const i=new URL(l,window.location.origin);return i.hostname.endsWith("alicdn.com")&&i.searchParams.set("_v",a),i.toString()}catch{return l}},Ft=async t=>{const a=await Le("/cookies/details",void 0,t),l=Date.now().toString();return a.map(i=>({id:i.id,value:"",cookie:"",enabled:i.enabled,auto_confirm:i.auto_confirm,remark:i.remark,note:i.remark,pause_duration:i.pause_duration,paused_until:Number(i.paused_until||0),paused:i.paused===!0,username:i.username||"",login_password:"",show_browser:i.show_browser===!0||i.show_browser===1||i.show_browser==="1"||i.show_browser==="true",nickname:i.nickname||i.remark||`账号 ${i.id.substring(0,6)}`,avatar_url:El(i,l),profile_error:i.profile_error||"",ai_enabled:!1,auto_rate_enabled:i.auto_rate_enabled,rate_content:i.rate_content||"不错的买家,交易愉快",auto_polish_enabled:i.auto_polish_enabled,polish_time:i.polish_time||"03:00",last_rate_scan_at:Number(i.last_rate_scan_at||0),last_polish_date:i.last_polish_date||"",last_polish_at:Number(i.last_polish_at||0)}))},Dl=async t=>Le(`/api/account-tasks/${t}`),Vs=async(t,a)=>Be(`/api/account-tasks/${t}`,a),Tl=async(t,a)=>Ce(`/api/account-tasks/${t}/run`,{task_type:a},{timeoutMs:12e4}),as=async(t,a,l,i=!1)=>{const m=await Le("/api/chat/sessions",{account_id:t,cursor:a,refresh:i?1:void 0},i?{timeoutMs:6e4,...l}:l);return{sessions:m.sessions||[],has_more:m.has_more===!0,next_cursor:m.next_cursor}},us=async(t,a,l,i,m)=>{const _=await Le("/api/chat/messages",{account_id:t,chat_id:a,cursor:l,before_id:i},m);return{messages:_.messages||[],has_more:_.has_more===!0,next_cursor:_.next_cursor,session:_.session}},Ml=async(t,a,l,i)=>(await us(t,a,void 0,l,i)).messages,ql=async t=>Ce("/api/chat/messages",t),Fl=async t=>{const a=new FormData;return Object.entries(t).forEach(([l,i])=>a.append(l,i)),wt("/api/chat/images",a,{timeoutMs:12e4})},Qs=async(t,a)=>Ce("/api/chat/read",{account_id:t,chat_id:a}),hs=async t=>Le("/cookies/runtime-status",void 0,t),Bl=async t=>Ce("/qr-login/generate",void 0,{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),zl=async(t,a)=>Le(`/qr-login/check/${t}`,void 0,{signal:a,timeoutMs:1e4}),Ul=async(t,a)=>Ce(`/qr-login/complete-verification/${t}`,{target_account_id:a||""}),Wl=async(t,a)=>Be(`/cookies/${t}/status`,{enabled:a}),Jl=async t=>Ze(`/cookies/${t}`),Vl=async(t,a)=>Be(`/cookies/${t}/pause-duration`,{pause_duration:a}),Ql=async(t,a)=>Be(`/cookies/${t}/settings`,a),Gl=async t=>Le(`/cookies/${t}/long-login`),Kl=async(t,a)=>Be(`/cookies/${t}/long-login`,{enabled:a}),Hl=async t=>Ce("/password-login",t),Zl=async(t,a)=>Le(`/password-login/check/${t}`,void 0,{signal:a,timeoutMs:1e4}),Yl=async t=>Ze(`/password-login/cancel/${t}`),Xl=async t=>Ce(`/cookies/${t}/refresh-profile`,{}),er=async t=>Le("/ai-reply-settings",void 0,t),Oa=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},tr=async(t,a,l=1,i=20,m)=>{const _={page:l,page_size:i};t&&(_.cookie_id=t),a&&a!=="all"&&(_.status=a),m!=null&&m.trim()&&(_.search=m.trim());const N=await Le("/api/orders",_),g=(N.orders||N.data||[]).map(C=>({...C,id:C.id||C.order_id,status:Oa(C.status||C.order_status),quantity:Number(C.quantity||1)}));return{success:!0,data:g,total:N.total||g.length,page:N.page||l,page_size:N.page_size||i,total_pages:N.total_pages||1}},sr=async(t,a)=>Be(`/api/orders/${t}`,a),ar=async t=>Ze(`/api/orders/${t}`),lr=async(t,a)=>{const l=new FormData;return t&&l.append("cookie_id",t),a&&l.append("status",a),wt("/api/orders/refresh",l)},rr=async t=>Ce(`/api/orders/${t}/refresh`),nr=async(t,a)=>Ce("/api/orders/manual-ship",{order_ids:t,ship_mode:a}),ir=async t=>t instanceof FormData?wt("/api/orders/import",t):Ce("/api/orders/import",t),or=async()=>Le("/dashboard/stats"),Gs=async(t=7)=>{let a;if(typeof t=="number"){const l=new Date,i=new Date;i.setDate(i.getDate()-t),a={start_date:Kt(i),end_date:Kt(l)}}else a=t;return Le("/analytics/orders",{...a,timezone_offset_minutes:-new Date().getTimezoneOffset()})},cr=async t=>{const a=await Le("/analytics/orders/valid",{start_date:t.start_date,end_date:t.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()}),i=(Array.isArray(a)?a:a.orders||[]).map(m=>({...m,id:m.id||m.order_id,status:Oa(m.status||m.order_status),quantity:Number(m.quantity||1)}));return{orders:i,total:Array.isArray(a)?i.length:Number(a.total??i.length),truncated:Array.isArray(a)?!1:a.truncated===!0}},dr=t=>{let a=t.api_config;if(typeof a=="string"&&a.trim())try{a=JSON.parse(a)}catch{a=void 0}return{...t,api_config:a||void 0}},Ia=t=>({...t,api_config:t.api_config?JSON.stringify(t.api_config):""}),Xe=async()=>{const t=await Le("/cards");return(Array.isArray(t)?t:t.cards||[]).map(dr)},xr=async t=>Ce("/cards",Ia(t)),Ks=async(t,a)=>Be(`/cards/${t}`,Ia(a)),mr=async t=>Ze(`/cards/${t}`),pr=async t=>{const a=new FormData;return a.append("file",t),wt("/cards/batch",a)},ur=async(t,a)=>Ce(`/cards/${t}/append-data`,{content:a}),ls=t=>t===!0||t===1||t==="1",vt=async t=>{const a=await Le("/items",void 0);return(Array.isArray(a)?a:a.items||[]).map(i=>({...i,id:i.id||`${i.cookie_id}-${i.item_id}`,is_multi_spec:ls(i.is_multi_spec),is_multi_qty_ship:ls(i.is_multi_qty_ship??i.multi_quantity_delivery),multi_quantity_delivery:ls(i.multi_quantity_delivery??i.is_multi_qty_ship)}))},hr=async t=>Ce("/items/get-all-from-account",{cookie_id:t}),gr=async(t,a)=>Ze(`/items/${t}/${a}`),br=async(t,a)=>Ce(`/items/${t}`,a),fr=async t=>{const a=new FormData;a.set("cookie_id",t.cookie_id),a.set("title",t.title),a.set("description",t.description),a.set("price",t.price),a.set("original_price",t.original_price||""),a.set("quantity",String(t.quantity)),a.set("postage_mode",t.postage_mode),a.set("postage",t.postage||""),t.location&&a.set("location",JSON.stringify(t.location));for(const l of t.images)a.append("images",l);return wt("/items/publish",a)},yr=async(t,a)=>Ce("/items/publish-categories/recommend",{cookie_id:t,keyword:a}),jr=async t=>{const a=new FormData;return a.set("file",t.file),t.imagesZip&&a.set("images_zip",t.imagesZip),t.defaultCookieId&&a.set("default_cookie_id",t.defaultCookieId),a.set("fallback_category_id",t.fallbackCategory.catId),a.set("fallback_category_name",t.fallbackCategory.catName),a.set("fallback_channel_category_id",t.fallbackCategory.channelCatId||""),a.set("fallback_tb_category_id",t.fallbackCategory.tbCatId||""),t.location&&a.set("location",JSON.stringify(t.location)),wt("/items/publish-batches/preview",a)},Nr=async t=>Ce("/items/publish-batches",{preview_id:t}),bt=async t=>Le(`/items/publish-batches/${t}`),Hs=async(t=20)=>{const a=await Le("/items/publish-batches",{limit:t});return Array.isArray(a)?a:a.batches||[]},_r=async t=>Ze(`/items/publish-batches/${t}`),vr=async t=>Ce(`/items/publish-batches/${t}/cancel`,{}),wr=async t=>Ce(`/items/publish-batches/${t}/retry-failed`,{}),kr=async(t,a,l)=>Be(`/items/${t}/${a}`,l),Aa=t=>t.map(a=>{var l,i;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((l=(a.actions||[]).find(m=>m.action_type==="send_card"))==null?void 0:l.card_id)||0),card_group_name:((i=(a.actions||[]).find(m=>m.action_type==="send_card"))==null?void 0:i.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(m=>({id:m.id?String(m.id):void 0,action_type:m.action_type,card_id:Number(m.card_id||0),card_name:m.card_name||"",delivery_count:Number(m.delivery_count||1),message_template:m.message_template||"",delay_seconds:Number(m.delay_seconds||0),config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:Number(m.sort_order||0)})),variants:(a.actions||[]).filter(m=>m.action_type==="send_card").map(m=>{let _={};try{_=JSON.parse(m.config_json||"{}")}catch{}return{id:m.id?String(m.id):void 0,spec_name:_.spec_name||"",spec_value:_.spec_value||"",card_id:Number(m.card_id||0),card_name:m.card_name||"",delivery_count:Number(m.delivery_count||1),enabled:m.enabled!==!1,delay_override:_.delay_override===!0,delay_seconds:Number(m.delay_seconds||0),config_json:m.config_json||"{}"}})}}),gs=async()=>{const t=await Le("/automation-rules"),a=Array.isArray(t)?t:t.data||[];return Aa(a)},Cr=async({cookieId:t,triggerType:a,enabled:l,search:i,page:m=1,pageSize:_=10}={})=>{const N=await Le("/automation-rules",{page:m,page_size:_,cookie_id:t||void 0,trigger_type:a||void 0,enabled:l,search:(i==null?void 0:i.trim())||void 0}),R=Aa(Array.isArray(N)?N:N.data||[]);return{success:!0,data:R,total:Number(Array.isArray(N)?R.length:N.total??R.length),page:Number(Array.isArray(N)?m:N.page??m),page_size:Number(Array.isArray(N)?_:N.page_size??_),total_pages:Number(Array.isArray(N)?R.length?1:0:N.total_pages??(R.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(Array.isArray(N)?{}:N.trigger_counts||{}).map(([g,C])=>[g,Number(C)]))}},Sr=(t,a)=>{if(t!=="order_paid")return a.map((m,_)=>({...m,sort_order:m.sort_order||_+1}));const l=a.filter(m=>m.action_type==="send_card").map((m,_)=>({...m,sort_order:_+1})),i=a.filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment");return[...l,...i.map((m,_)=>({...m,sort_order:l.length+_+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:l.length+i.length+1}]},Zs=async t=>{const a=t.trigger_type||"order_paid",i=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[a]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),m=(t.actions||[]).filter(g=>g.action_type!=="send_card"&&g.action_type!=="confirm_shipment"),_=t.variants&&t.variants.length>0?[...t.variants.map((g,C)=>({action_type:"send_card",card_id:g.card_id,delivery_count:g.delivery_count||1,enabled:g.enabled!==!1,sort_order:C+1,delay_seconds:g.delay_seconds||0,config_json:JSON.stringify({spec_name:g.spec_name||"",spec_value:g.spec_value||"",delay_override:g.delay_override===!0})})),...m]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],N=Sr(a,_),R={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||i||"自动化规则",trigger_type:a,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:N.map((g,C)=>({action_type:g.action_type,card_id:g.card_id||0,delivery_count:g.delivery_count||1,message_template:g.message_template||"",delay_seconds:g.delay_seconds||0,config_json:g.config_json||"{}",enabled:g.enabled!==!1,sort_order:g.sort_order||C+1}))};return t.id?Be(`/automation-rules/${t.id}`,R):Ce("/automation-rules",R)},Lr=async t=>Ze(`/automation-rules/${t}`),Or=async()=>{const t=await Le("/automation-issues");return{runs:Array.isArray(t==null?void 0:t.runs)?t.runs:[],pending_tasks:Array.isArray(t==null?void 0:t.pending_tasks)?t.pending_tasks:[]}},Ir=async(t,a)=>Ce(`/automation-runs/${t}/resolve`,{resolution:a}),Ar=async(t,a)=>Ce(`/automation-pending-tasks/${t}/resolve`,{resolution:a}),$r=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Pr=async t=>{const a=await Le(`/keywords-with-type/${t}`);return Array.isArray(a)?a.map($r):[]},Rr=async t=>t?(await Pr(t)).map(l=>({id:l.id,keyword:l.keyword||"",reply_content:l.reply||"",match_type:"fuzzy",enabled:!0,item_id:l.item_id||"",type:l.type==="image"?"image":"text",image_url:l.image_url||""})):[],Er=async(t,a)=>{const l=t.type||"text",i={keyword:t.keyword||"",reply:l==="text"&&t.reply_content||"",item_id:t.item_id||"",type:l,image_url:l==="image"&&t.image_url||""};return t.id?Be(`/keywords-with-type/${a}/${t.id}`,i):Ce(`/keywords-with-item-id/${a}`,i)},Dr=async(t,a)=>Ze(`/keywords-with-type/${a}/${t}`),$a=async()=>{const t=await Le("/system-settings");return Il(t.data||t)},Pa=async t=>{const a=Object.fromEntries(Object.entries(t).filter(([,l])=>l!=null));return Be("/system-settings",a)},Tr=async(t,a)=>Le(`/ai-reply-settings/${t}`,void 0,a),Mr=async(t,a)=>{const l={ai_enabled:a.ai_enabled??!1,max_discount_percent:a.max_discount_percent??10,max_discount_amount:a.max_discount_amount??100,max_bargain_rounds:a.max_bargain_rounds??3,custom_prompts:a.custom_prompts??""};return Be(`/ai-reply-settings/${t}`,l)},qr=async(t,a="")=>(await Ce("/ai-models",{base_url:t,api_key:a})).models||[],Fr=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const a=JSON.parse(t);if(Array.isArray(a))return a.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(a=>a.trim()).filter(Boolean)},Ra=t=>{const a=Array.from(new Set((t||[]).filter(Boolean)));return a.length>0?JSON.stringify(a):""},Ea=async t=>({success:!0,data:(await Le("/notification-channels",void 0,t)||[]).map(i=>{let m;try{m=typeof i.config=="string"?JSON.parse(i.config):i.config}catch{m={}}return{id:String(i.id),name:i.name,type:i.type==="ding_talk"?"dingtalk":i.type==="lark"?"feishu":i.type,config:m,event_types:Fr(i.event_types),enabled:i.enabled,created_at:i.created_at,updated_at:i.updated_at}})}),Br=async t=>Ce("/notification-channels",{...t,config:JSON.stringify(t.config),event_types:Ra(t.event_types)}),Ys=async(t,a)=>{const l={...a};return"config"in a&&(l.config=JSON.stringify(a.config)),"event_types"in a&&(l.event_types=Ra(a.event_types)),Be(`/notification-channels/${t}`,l)},zr=async t=>Ze(`/notification-channels/${t}`),Ur=async(t,a)=>{const l=await Le(`/message-notifications/${t}`,void 0,a);return(l==null?void 0:l.channel_ids)||[]},Wr=async t=>Ce(`/notification-channels/${t}/test`,{}),Xs=async()=>Le("/api/default-replies"),Jr=async t=>{const a=await Le(`/api/default-reply/${t}`);return{cookie_id:t,enabled:a.enabled||!1,reply_content:a.reply_content||"",reply_once:a.reply_once||!1,reply_image_url:a.reply_image_url||""}},Vr=async(t,a)=>Be(`/api/default-reply/${t}`,{enabled:a.enabled??!1,reply_content:a.reply_content||"",reply_once:a.reply_once??!1,reply_image_url:a.reply_image_url||""}),Qr=async t=>Ze(`/api/default-reply/${t}`),Gr=async t=>Ce(`/api/default-reply/${t}/clear-records`,{}),At=t=>String(t).padStart(2,"0"),bs=t=>{if(t==null||t==="")return"-";const a=t instanceof Date?t:new Date(t);return Number.isNaN(a.getTime())?"-":[a.getFullYear(),At(a.getMonth()+1),At(a.getDate())].join("-")+" "+[At(a.getHours()),At(a.getMinutes()),At(a.getSeconds())].join(":")},_e=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Kr=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},Wt=({title:t,value:a,icon:l,colorClass:i,trend:m})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${i} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${i} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(l,{className:`w-6 h-6 ${i.replace("bg-","text-")}`})}),m&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(Ga,{className:"w-3 h-3"})," ",m]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:a}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),rs=()=>{var V,X;const[t,a]=r.useState(null),[l,i]=r.useState(null),[m,_]=r.useState(""),[N,R]=r.useState("7days"),[g,C]=r.useState(""),[j,F]=r.useState(""),[G,me]=r.useState(null),[oe,v]=r.useState(""),[q,ce]=r.useState([]),[Q,ee]=r.useState(0),[B,ge]=r.useState(!1),[ue,k]=r.useState(!1),[Z,se]=r.useState([]),[K,ve]=r.useState({}),J=r.useRef(0),I=[_e("brand"),_e("brand-highlight"),_e("success-500"),_e("warning-500"),_e("accent-500")],E=c=>`¥${Number(c||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`,$=async c=>{let d;try{d=Js(c,new Date,g,j)}catch(Se){_(Se instanceof Error?Se.message:"日期范围无效");return}const{startDate:D,endDate:S}=d,Y={start_date:D,end_date:S},O=Ol(d),de=++J.current;k(!0),_("");try{const[Se,fe,Oe]=await Promise.all([Gs(Y),Gs({start_date:O.startDate,end_date:O.endDate}),cr(Y)]);if(de!==J.current)return;i(Se),me(fe),ce(Oe.orders),ee(Oe.total),ge(Oe.truncated)}catch(Se){de===J.current&&_(Se instanceof Error?Se.message:"经营数据加载失败")}finally{de===J.current&&k(!1)}},be=()=>{if(!l||!G)return null;const c=l.revenue_stats.total_amount,d=G.revenue_stats.total_amount;if(d===0)return c>0?"+100%":"0%";const D=(c-d)/d*100;return`${D>=0?"+":""}${D.toFixed(1)}%`};if(r.useEffect(()=>{let c=!1;return Promise.all([or(),vt()]).then(([d,D])=>{if(c)return;a(d),se(D);const S={};D.forEach(Y=>{S[Y.item_id]=Y.item_title||Y.item_id}),ve(S)}).catch(d=>{c||_(d instanceof Error?d.message:"概览加载失败")}),()=>{c=!0}},[]),r.useEffect(()=>{N!=="custom"&&$(N)},[N]),m&&(!t||!l))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(rt,{className:"w-8 h-8"}),e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:()=>window.location.reload(),children:"重新加载"})]});if(!t||!l)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx($s,{className:"w-8 h-8 animate-spin text-brand"})});const Re=((V=l.daily_stats)==null?void 0:V.map(c=>({name:c.date.slice(5),amount:c.amount,orders:c.order_count,avgAmount:c.order_count>0?(c.amount/c.order_count).toFixed(2):0})))||[],ae=l.item_stats||[],T=l.revenue_stats.total_orders||0,p=l.revenue_stats.total_amount||0,b=ae.length>0?ae.map(c=>({name:(K[c.item_id]||c.item_id).length>12?(K[c.item_id]||c.item_id).substring(0,12)+"...":K[c.item_id]||c.item_id,sales:c.order_count})).sort((c,d)=>d.sales-c.sales).slice(0,10):[],U=Math.max(...b.map(c=>c.sales),1),M=ae.length>0?ae.map(c=>({name:(K[c.item_id]||c.item_id).length>10?(K[c.item_id]||c.item_id).substring(0,10)+"...":K[c.item_id]||c.item_id,value:c.order_count,percent:T>0?c.order_count/T*100:0})).sort((c,d)=>d.value-c.value).slice(0,6).map((c,d)=>({...c,color:I[d%I.length]})):[],ne=ae.length>0?ae.map(c=>({name:(K[c.item_id]||c.item_id).length>12?(K[c.item_id]||c.item_id).substring(0,12)+"...":K[c.item_id]||c.item_id,value:c.total_amount,orderCount:c.order_count,percentage:p>0?c.total_amount/p*100:0})).sort((c,d)=>d.value-c.value).slice(0,5).map((c,d)=>({...c,color:I[d%I.length],percentage:c.percentage.toFixed(1)})):[],he=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}],ye=((X=he.find(c=>c.key===N))==null?void 0:X.label)||"所选范围";let Ee;try{Ee=Js(N,new Date,g,j)}catch{Ee={startDate:g,endDate:j}}const ke=oe.trim().toLowerCase(),x=q.filter(c=>{var d,D,S,Y;return((d=c.order_id)==null?void 0:d.toLowerCase().includes(ke))||((D=c.item_id)==null?void 0:D.toLowerCase().includes(ke))||((S=c.item_title)==null?void 0:S.toLowerCase().includes(ke))||((Y=c.buyer_id)==null?void 0:Y.toLowerCase().includes(ke))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[he.map(c=>e.jsx("button",{onClick:()=>R(c.key),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${N===c.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:c.label},c.key)),N==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:g,onChange:c=>C(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:j,onChange:c=>F(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:()=>{try{_(""),$("custom")}catch(c){_(c instanceof Error?c.message:"日期范围无效")}},className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(Wt,{title:"累计营收 (CNY)",value:`¥${l.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:Qa,colorClass:"bg-blue-400",trend:be()||void 0}),e.jsx(Wt,{title:"活跃账号 / 总数",value:`${t.active_cookies} / ${t.total_cookies}`,icon:ha,colorClass:"bg-blue-500"}),e.jsx(Wt,{title:"订单数",value:l.revenue_stats.total_orders.toLocaleString(),icon:Ps,colorClass:"bg-blue-500"}),e.jsx(Wt,{title:"库存卡密余量",value:t.available_card_stock,icon:fa,colorClass:"bg-purple-500"})]}),e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[ye,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:Re.length===0||l.revenue_stats.total_amount===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(Ps,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):Re.length<=2?e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(bl,{data:Re,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Bs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:_e("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(zs,{axisLine:!1,tickLine:!1,tick:{fill:_e("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:c=>`¥${c}`}),e.jsx(Ut,{contentStyle:{backgroundColor:_e("white"),borderRadius:"8px",border:`1px solid ${_e("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:_e("neutral-500"),fontWeight:500},itemStyle:{color:_e("brand"),fontWeight:600},cursor:{fill:_e("brand",.08)},formatter:c=>[`¥${Number(c).toFixed(2)}`,"营收"]}),e.jsx(fl,{dataKey:"amount",fill:_e("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:Re.map((c,d)=>e.jsx(ts,{fill:_e("brand"),stroke:"none",strokeWidth:0},`cell-${d}`))})]})}):e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(yl,{data:Re,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:_e("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:_e("brand"),stopOpacity:0})]})}),e.jsx(Bs,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:_e("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(zs,{axisLine:!1,tickLine:!1,tick:{fill:_e("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(jl,{vertical:!1,stroke:_e("neutral-100"),strokeDasharray:"3 3"}),e.jsx(Ut,{contentStyle:{backgroundColor:_e("white"),borderRadius:"8px",border:`1px solid ${_e("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:_e("neutral-500"),fontWeight:500},itemStyle:{color:_e("brand"),fontWeight:600},cursor:{stroke:_e("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Nl,{type:"monotone",dataKey:"amount",stroke:_e("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:_e("white"),stroke:_e("brand"),strokeWidth:2}})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:b.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:b.map((c,d)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${d<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:d+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:c.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[c.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${Math.max(8,c.sales/U*100)}%`}})})]},`${c.name}-${d}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${T} 单`,children:M.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(Us,{accessibilityLayer:!1,children:[e.jsx(Ws,{data:M,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:M.map((c,d)=>e.jsx(ts,{fill:c.color},`cell-${d}`))}),e.jsx(Ut,{formatter:c=>`${Number(c||0)} 单`,wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:_e("white"),border:`1px solid ${_e("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(_l,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:c=>e.jsx("span",{style:{color:_e("neutral-500"),fontWeight:500},children:c})})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:T}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),B&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",q.length," / ",Q," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:oe,onChange:c=>v(c.target.value),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:ue?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx($s,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):x.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(qt,{className:"w-7 h-7 text-gray-300"})}),ke?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",q.length," 单参与统计,但没有订单号、商品、买家匹配“",oe,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",Ee.startDate," 至 ",Ee.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",l.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:x.map(c=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(qt,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:c.item_title||c.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:c.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",c.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:c.buyer_id}),c.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:bs(c.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",c.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(Kr,{status:c.status||c.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${c.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(ya,{className:"w-4 h-4"})})})]},c.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),ne.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${E(p)}`,children:[e.jsx(zt,{width:"100%",height:"100%",children:e.jsxs(Us,{accessibilityLayer:!1,children:[e.jsx(Ws,{data:ne,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:ne.map((c,d)=>e.jsx(ts,{fill:c.color||I[d%I.length]},`cell-${d}`))}),e.jsx(Ut,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:_e("white"),border:`1px solid ${_e("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:c=>`¥${Number(c||0).toLocaleString()}`})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:E(p)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:ne.map(c=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:c.color||I[ne.indexOf(c)%I.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:c.name,children:c.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",c.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[c.percentage,"%"]})]})]},c.name))})]})]})]})]})},Hr=(t,a)=>{const l=a.pause_duration||0;return t!==l},Zr=(t,a)=>{const l=a.username!==(t.username||""),i=a.show_browser!==(t.show_browser||!1),m=a.login_password!=="",_=a.clear_password===!0;if(!l&&!i&&!m&&!_)return null;const N={username:a.username,show_browser:a.show_browser};return _?N.clear_password=!0:m&&(N.login_password=a.login_password),N},Yr=(t,a)=>t&&a,Xr=(t,a)=>{if(!t||!a)return!1;const l=Date.parse(t),i=Date.parse(a);return Number.isFinite(l)&&Number.isFinite(i)&&it.map(l=>{const i=a[l.id];return!i||Xr(l.runtime_updated_at,i.updated_at)?l:{...l,runtime_state:i.state,runtime_message:i.message||"",runtime_connected:i.connected,runtime_updated_at:i.updated_at}}),tn=new Set(["expired","cancelled","error","not_found"]),Jt=()=>{let t=0;return{next:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:a=>a===t}},sn=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let a=null,l=null,i=-1,m=0;const _=()=>{m+=1,l==null||l.abort(),l=null,a!==null&&(t.clearInterval(a),a=null)};return{start:(R,g,C,j=2e3)=>{_();const F=m;l=new AbortController;const G=l.signal;a=t.setInterval(()=>{i===F||F!==m||(i=F,(async()=>{var me,oe;try{const v=await g(R,G);if(v.status==="success"){_(),await C.onSuccess(v);return}if(v.status==="scanned"){(me=C.onScanned)==null||me.call(C,v);return}if(v.status==="verification_required"){(oe=C.onVerificationRequired)==null||oe.call(C,v);return}v.status&&tn.has(v.status)&&(_(),C.onTerminalError(v))}catch(v){if(G.aborted||F!==m)return;_(),C.onPollError(v)}finally{i===F&&(i=-1)}})())},j)},stop:_,isActive:()=>a!==null}},an=({faceQrUrl:t,verificationScreenshot:a})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(Ka,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:t?e.jsx("img",{src:t,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):a?e.jsx("img",{src:a,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(Pe,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),ea=({src:t,alt:a,className:l=""})=>e.jsx("img",{src:t,alt:a,className:`block aspect-square h-auto w-full object-contain ${l}`.trim()}),ta=({checked:t,onChange:a,label:l})=>e.jsx("button",{type:"button","aria-label":l,"aria-pressed":t,onClick:a,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-6":""}`})}),ln=({account:t,onClose:a,onSaved:l})=>{const[i,m]=r.useState({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),[_,N]=r.useState(!1),[R,g]=r.useState(""),[C,j]=r.useState(""),[F,G]=r.useState(null),me=async()=>{N(!0),j("");try{const v=await Vs(t.id,i);m(v),l(v)}catch(v){j(v instanceof Error?v.message:"保存失败")}finally{N(!1)}},oe=async v=>{g(v),j(""),G(null);try{await Vs(t.id,i);const q=await Tl(t.id,v),ce=await Dl(t.id);G(q.summary),m(ce),l(ce)}catch(q){j(q instanceof Error?q.message:"任务执行失败")}finally{g("")}};return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:a,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(Me,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(Ha,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(ta,{checked:i.auto_rate_enabled,onChange:()=>m(v=>({...v,auto_rate_enabled:!v.auto_rate_enabled})),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:i.rate_content,maxLength:500,onChange:v=>m(q=>({...q,rate_content:v.target.value})),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",i.last_rate_scan_at?new Date(i.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:R!==""||!t.enabled,onClick:()=>void oe("auto_rate"),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[R==="auto_rate"?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(Za,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(vs,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(ta,{checked:i.auto_polish_enabled,onChange:()=>m(v=>({...v,auto_polish_enabled:!v.auto_polish_enabled})),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:i.polish_time,onChange:v=>m(q=>({...q,polish_time:v.target.value})),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:R!==""||!t.enabled,onClick:()=>void oe("auto_polish"),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[R==="auto_polish"?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(ja,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",i.last_polish_at?new Date(i.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),F&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",F.found," 项,成功 ",F.success,",失败 ",F.failed,",跳过 ",F.skipped,"。",F.message||""]}),C&&e.jsx("div",{className:"rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:C})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:a,disabled:_||R!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:()=>void me(),disabled:_||R!==""||i.auto_rate_enabled&&!i.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[_?e.jsx(Pe,{className:"h-4 w-4 animate-spin"}):e.jsx(He,{className:"h-4 w-4"}),"保存"]})]})})]})})},rn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState(!0),[m,_]=r.useState(""),[N,R]=r.useState(""),[g,C]=r.useState(""),[j,F]=r.useState(null),[G,me]=r.useState(""),[oe,v]=r.useState(!1),[q,ce]=r.useState(""),[Q,ee]=r.useState("pending"),[B,ge]=r.useState(""),[ue,k]=r.useState(""),[Z,se]=r.useState(""),[K,ve]=r.useState(null),[J,I]=r.useState(null),[E,$]=r.useState(null),[be,Re]=r.useState(null),[ae,T]=r.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[p,b]=r.useState([]),[U,M]=r.useState([]),[ne,he]=r.useState(!1),[ye,Ee]=r.useState(!1),[ke,x]=r.useState(!1),[V,X]=r.useState(""),[c,d]=r.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),[D,S]=r.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[Y,O]=r.useState(!1),[de,Se]=r.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),fe=r.useRef(null),Oe=r.useRef(null),re=r.useRef(null),h=r.useRef(null),f=r.useRef(null),P=r.useRef(null),z=r.useRef(null),Ie=r.useRef(null),Ae=r.useRef(null),we=r.useRef(null),De=r.useRef(null),te=r.useRef(null),je=r.useRef(0);fe.current===null&&(fe.current=sn()),Oe.current===null&&(Oe.current=Jt()),re.current===null&&(re.current=Jt()),h.current===null&&(h.current=Jt()),f.current===null&&(f.current=Jt());const u=()=>{De.current!==null&&(window.clearTimeout(De.current),De.current=null)},L=()=>{te.current!==null&&(window.clearTimeout(te.current),te.current=null)},le=()=>{var s;(s=fe.current)==null||s.stop()},Ne=()=>{var s,o;(s=Ae.current)==null||s.abort(),(o=Oe.current)==null||o.cancel(),le(),u(),v(!1)},Ue=()=>{u(),De.current=window.setTimeout(()=>{De.current=null,v(!1),Fe()},1e3)},Fe=async()=>{var y,A,W,pe,xe;const s=re.current.next();(y=P.current)==null||y.abort();const o=new AbortController;P.current=o,i(!0);try{const $e={signal:o.signal},[ie,Ye]=await Promise.allSettled([Ft($e),er($e)]);if(!((A=re.current)!=null&&A.isCurrent(s)))return;if(ie.status==="rejected")throw ie.reason;const Ve=ie.value,It=Ye.status==="fulfilled"?Ye.value:{};Ye.status==="rejected"&&console.error("Failed to load AI settings:",Ye.reason);const Ua=Ve.map(gt=>{var Cs,Ss,Ls,Os,Is;return{...gt,ai_enabled:((Cs=It[gt.id])==null?void 0:Cs.ai_enabled)??!1,max_discount_percent:((Ss=It[gt.id])==null?void 0:Ss.max_discount_percent)??10,max_discount_amount:((Ls=It[gt.id])==null?void 0:Ls.max_discount_amount)??100,max_bargain_rounds:((Os=It[gt.id])==null?void 0:Os.max_bargain_rounds)??3,custom_prompts:((Is=It[gt.id])==null?void 0:Is.custom_prompts)??""}});(W=re.current)!=null&&W.isCurrent(s)&&a(Ua)}catch($e){(pe=re.current)!=null&&pe.isCurrent(s)&&!o.signal.aborted&&console.error("Failed to load accounts:",$e)}finally{(xe=re.current)!=null&&xe.isCurrent(s)&&i(!1)}};r.useEffect(()=>{let s=!1,o=null;const y=new AbortController,A=async()=>{try{const W=await hs({signal:y.signal,timeoutMs:1e4});s||a(pe=>en(pe,W))}catch(W){s||console.error("Failed to load account runtime statuses:",W)}finally{s||(o=window.setTimeout(()=>void A(),2e3))}};return Fe().finally(()=>{s||A()}),()=>{s=!0,y.abort(),o!==null&&window.clearTimeout(o)}},[]),r.useEffect(()=>()=>{var s,o,y,A,W,pe,xe,$e,ie;le(),(s=Oe.current)==null||s.cancel(),(o=re.current)==null||o.cancel(),(y=h.current)==null||y.cancel(),(A=f.current)==null||A.cancel(),(W=P.current)==null||W.abort(),(pe=z.current)==null||pe.abort(),(xe=Ie.current)==null||xe.abort(),($e=Ae.current)==null||$e.abort(),(ie=we.current)==null||ie.abort(),u(),je.current+=1,L()},[]);const tt=s=>{if(!s.enabled||s.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(s.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},kt=async(s,o)=>{await Wl(s,!o),Fe()},Je=s=>{g||(me(""),F(s))},We=()=>{g||(me(""),F(null))},Ct=async()=>{const s=j;if(!(!s||g)){C(s.id),me("");try{await Jl(s.id),a(o=>o.filter(y=>y.id!==s.id)),F(null)}catch(o){console.error("删除账号失败:",o),me((o==null?void 0:o.message)||"删除账号失败,请稍后重试")}finally{C("")}}},St=async s=>{R(s.id);try{const o=await Xl(s.id);o!=null&&o.profile_error&&alert("资料刷新失败:"+o.profile_error),await Fe()}catch(o){console.error("刷新账号资料失败:",o),alert((o==null?void 0:o.message)||"刷新账号资料失败,请先重新授权该账号")}finally{R("")}},mt=async s=>{var pe,xe;const o=h.current.next();(pe=z.current)==null||pe.abort();const y=new AbortController;z.current=y,Ee(!0),he(!1),x(!1),X("");const[A,W]=await Promise.allSettled([Ea({signal:y.signal}),Ur(s,{signal:y.signal})]);(xe=h.current)!=null&&xe.isCurrent(o)&&(A.status==="fulfilled"?b(A.value.data||[]):(b([]),X("通知渠道列表加载失败,请重试")),W.status==="fulfilled"?(M(W.value||[]),he(!0)):(M([]),X("通知绑定加载失败;本次保存不会修改现有绑定")),Ee(!1))},Lt=async s=>{var y;je.current+=1,(y=we.current)==null||y.abort(),L(),Se({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),$(s),d({remark:s.remark||s.note||"",cookie:s.cookie||s.value||"",auto_confirm:s.auto_confirm||!1,pause_duration:s.pause_duration||0,username:s.username||"",login_password:s.login_password||"",show_browser:s.show_browser||!1,showLoginPassword:!1,clear_password:!1}),I("edit"),T({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,o]=await Promise.allSettled([mt(s.id),Gl(s.id)]);o.status==="fulfilled"?T({loading:!1,saving:!1,canOpen:o.value.can_open_long_login,enabled:o.value.enabled,error:""}):T({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"})},nt=async()=>{if(!E||ae.loading||ae.saving||!ae.canOpen)return;const s=!ae.enabled;T(o=>({...o,saving:!0,error:""}));try{const o=await Kl(E.id,s);T({loading:!1,saving:!1,canOpen:o.can_open_long_login,enabled:o.enabled,error:""})}catch(o){T(y=>({...y,saving:!1,error:o instanceof Error?o.message:"保存登录信息设置失败"}))}},it=async s=>{var A,W,pe,xe;const o=f.current.next();(A=Ie.current)==null||A.abort();const y=new AbortController;Ie.current=y,$(s),I("ai-settings"),O(!0);try{const $e=await Tr(s.id,{signal:y.signal});if(!((W=f.current)!=null&&W.isCurrent(o)))return;S({ai_enabled:$e.ai_enabled??!1,max_discount_percent:$e.max_discount_percent??10,max_discount_amount:$e.max_discount_amount??100,max_bargain_rounds:$e.max_bargain_rounds??3,custom_prompts:$e.custom_prompts??""})}catch($e){(pe=f.current)!=null&&pe.isCurrent(o)&&console.error("Failed to load AI settings:",$e)}finally{(xe=f.current)!=null&&xe.isCurrent(o)&&O(!1)}},Ot=async()=>{if(E){O(!0);try{const s={};c.remark!==(E.remark||E.note||"")&&(s.remark=c.remark),c.cookie&&c.cookie!==(E.cookie||E.value||"")&&(s.cookie=c.cookie),c.auto_confirm!==E.auto_confirm&&(s.auto_confirm=c.auto_confirm),Hr(c.pause_duration,E)&&(s.pause_duration=c.pause_duration);const o=Zr(E,c);o&&Object.assign(s,o),Yr(ne,ke)&&(s.channel_ids=U),Object.keys(s).length>0&&await Ql(E.id,s),I(null),Fe()}catch(s){console.error("更新账号失败:",s),alert("更新失败,请重试")}finally{O(!1)}}},pt=async()=>{if(!(!E||c.pause_duration<=0)){O(!0);try{const s=await Vl(E.id,c.pause_duration);$({...E,pause_duration:c.pause_duration,paused:(s==null?void 0:s.paused)===!0,paused_until:Number((s==null?void 0:s.paused_until)||0)}),await Fe()}catch(s){alert(s instanceof Error?s.message:"重新暂停失败")}finally{O(!1)}}},ut=async()=>{if(E){O(!0);try{await Mr(E.id,D),I(null),Fe()}catch(s){console.error("更新AI设置失败:",s),alert("更新失败,请重试")}finally{O(!1)}}},st=async(s,o)=>{var A;(A=we.current)==null||A.abort();const y=new AbortController;we.current=y;try{const W=await Zl(s,y.signal);if(o!==je.current)return;if(W.status==="success"){L(),Se({sessionId:s,status:"success",message:W.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}),d(pe=>({...pe,login_password:"",showLoginPassword:!1})),await Fe();return}if(W.status==="processing"||W.status==="verification_required"){Se({sessionId:s,status:W.status,message:W.message||(W.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:W.qr_code_url||""}),L(),te.current=window.setTimeout(()=>void st(s,o),1500);return}L(),Se({sessionId:s,status:"failed",message:W.error||W.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""})}catch(W){if(o!==je.current)return;L(),Se({sessionId:s,status:"failed",message:W instanceof Error?W.message:"查询密码登录状态失败",qrCodeUrl:""})}},ht=async()=>{var y;if(!E)return;const s=c.username.trim();if(!s||!c.login_password){alert("请先填写登录账号和本次登录密码");return}L(),(y=we.current)==null||y.abort();const o=++je.current;Se({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const A=await Hl({account_id:E.id,account:s,password:c.login_password,show_browser:c.show_browser});if(o!==je.current)return;if(!A.success||!A.session_id)throw new Error(A.message||"无法启动密码登录");Se({sessionId:A.session_id,status:"processing",message:A.message||"登录处理中",qrCodeUrl:""}),await st(A.session_id,o)}catch(A){if(o!==je.current)return;Se({sessionId:"",status:"failed",message:A instanceof Error?A.message:"启动密码登录失败",qrCodeUrl:""})}},Ge=async()=>{var o;const s=de.sessionId;if(je.current+=1,(o=we.current)==null||o.abort(),L(),s)try{await Yl(s)}catch(y){console.error("取消密码登录失败",y)}Se({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},ot=async()=>{var s,o;(s=h.current)==null||s.cancel(),(o=z.current)==null||o.abort(),(de.status==="processing"||de.status==="verification_required")&&await Ge(),I(null)},n=()=>{var s,o;(s=f.current)==null||s.cancel(),(o=Ie.current)==null||o.abort(),I(null)},w=async(s,o)=>{const y=await Ul(s,o==null?void 0:o.id);if(!y.success||!y.account_id)throw new Error(y.message||"保存扫码授权失败");return y.account_id},H=async s=>{var W,pe,xe,$e;le(),(W=Ae.current)==null||W.abort();const o=new AbortController;Ae.current=o;const y=Oe.current.next();u();const A=s||null;ve(A),v(!0),ee("loading"),ge(""),ce(""),k(""),se("");try{const ie=await Bl({signal:o.signal});if(!((pe=Oe.current)!=null&&pe.isCurrent(y)))return;if(!ie.success||!ie.qr_code_url||!ie.session_id)throw new Error(ie.message||"闲鱼未返回可用的登录二维码");if(ie.success&&ie.qr_code_url&&ie.session_id){const Ye=ie.session_id;ce(ie.qr_code_url),ee("waiting"),(xe=fe.current)==null||xe.start(Ye,zl,{onSuccess:async()=>{try{if(!await w(Ye,A)){ee("error");return}}catch(Ve){console.error("保存扫码授权失败",Ve),ee("error");return}ee("success"),Ue()},onScanned:()=>{ee("waiting")},onTerminalError:()=>{ee("error")},onPollError:Ve=>{console.error("轮询扫码状态失败",Ve),ee("error")},onVerificationRequired:Ve=>{ee("verification"),Ve.face_qr_url&&se(Ve.face_qr_url),Ve.verification_screenshot&&k(Ve.verification_screenshot)}})}}catch(ie){if(!(($e=Oe.current)!=null&&$e.isCurrent(y)))return;ge(ie instanceof Error?ie.message:"二维码获取失败,请稍后重试"),ee("error")}finally{Ae.current===o&&(Ae.current=null)}};if(l)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(Pe,{className:"w-8 h-8 text-brand animate-spin"})});const Te=t.filter(s=>{const o=m.trim().toLowerCase();return o?[s.id,s.nickname,s.remark,s.note,s.username,s.runtime_message].some(y=>(y||"").toLowerCase().includes(o)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:m,onChange:s=>_(s.target.value),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:()=>H(),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Xt,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",Te.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[Te.map(s=>{const o=tt(s),y=s.runtime_state==="auth_expired"||s.runtime_state==="verification_required";return e.jsx("div",{className:"ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-5 sm:gap-8",children:[e.jsxs("div",{className:"relative",children:[s.avatar_url?e.jsx("img",{src:s.avatar_url,alt:s.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(xt,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${o.dot}`,children:s.runtime_state==="online"&&e.jsx(Ke,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:s.nickname||s.remark||`账号 ${s.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${o.badge}`,children:o.label}),s.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(yt,{className:"w-3 h-3"})," AI"]}),s.auto_rate_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700",children:[e.jsx(Tt,{className:"h-3 w-3"})," 自动评价"]}),s.auto_polish_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700",children:[e.jsx(vs,{className:"h-3 w-3"})," 每日擦亮"]}),s.auto_confirm&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700",children:[e.jsx(Ke,{className:"h-3 w-3"})," 自动确认发货"]}),s.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:s.profile_error,children:[e.jsx(rt,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"text-sm font-medium text-gray-500",children:[e.jsx("p",{children:s.remark||s.note||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",s.id]})]}),s.runtime_message&&s.runtime_state!=="online"&&s.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${y?"text-red-700":"text-amber-700"}`,children:[e.jsx(rt,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:s.runtime_message}),y&&e.jsxs("button",{type:"button",onClick:()=>H(s),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(Xt,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),s.paused&&e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700",children:[e.jsx(Rs,{className:"h-3 w-3"})," 暂停处理中"]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>St(s),disabled:N===s.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(ze,{className:`w-5 h-5 ${N===s.id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>H(s),className:`p-3 rounded-xl transition-colors ${y?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(Xt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Lt(s),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Na,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>it(s),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(yt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Re(s),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(ja,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>kt(s.id,s.enabled),className:`p-3 rounded-xl transition-colors ${s.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:s.enabled?"停用账号":"启用账号",children:e.jsx(Ya,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Je(s),disabled:g!=="",className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:g===s.id?"删除中…":`删除账号 ${s.nickname||s.remark||s.id}`,children:g===s.id?e.jsx(Pe,{className:"w-5 h-5 animate-spin"}):e.jsx(Qe,{className:"w-5 h-5"})})]})]})]})]})},s.id)}),t.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(xt,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),t.length>0&&Te.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),be&&qe.createPortal(e.jsx(ln,{account:be,onClose:()=>Re(null),onSaved:s=>{a(o=>o.map(y=>y.id===be.id?{...y,auto_rate_enabled:s.auto_rate_enabled,rate_content:s.rate_content,auto_polish_enabled:s.auto_polish_enabled,polish_time:s.polish_time,last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}:y))}}),document.body),j&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",role:"presentation",children:e.jsxs("div",{className:"h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal",role:"dialog","aria-modal":"true","aria-labelledby":"delete-account-title","aria-describedby":"delete-account-description",children:[e.jsxs("div",{className:"relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5",children:[e.jsx("div",{className:"absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl"}),e.jsxs("div",{className:"relative flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200",children:e.jsx(Qe,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{id:"delete-account-title",className:"text-lg font-extrabold tracking-tight text-gray-950",children:"删除这个账号?"}),e.jsx("p",{id:"delete-account-description",className:"mt-1 text-xs leading-5 text-gray-600",children:"删除后,该账号的关联配置也会一并清理,此操作无法撤销。"})]}),e.jsx("button",{type:"button",onClick:We,disabled:g!=="",className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"关闭删除确认",children:e.jsx(Me,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:j.nickname||j.remark||"未命名账号"}),j.remark&&j.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",j.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",j.id]})]}),g===j.id&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(Pe,{className:"h-5 w-5 flex-shrink-0 animate-spin text-brand"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-blue-950",children:"正在删除账号"}),e.jsx("div",{className:"mt-0.5 text-xs text-blue-700",children:"正在清理关联数据,请保持页面打开…"})]})]}),G&&e.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3",role:"alert",children:[e.jsx(rt,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-red-800",children:"删除失败"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-red-700",children:G})]})]})]}),e.jsxs("div",{className:"flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4",children:[e.jsx("button",{type:"button",onClick:We,disabled:g!=="",className:"flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50",children:"取消"}),e.jsx("button",{type:"button",onClick:()=>void Ct(),disabled:g!=="",className:"flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400",children:g===j.id?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),oe&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:Ne,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:K?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:K?`请用闲鱼APP扫码,为「${K.nickname||K.remark||K.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${Q==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[Q==="loading"&&e.jsx(Pe,{className:"w-10 h-10 text-brand animate-spin"}),Q==="waiting"&&e.jsx(ea,{src:q,alt:"闲鱼登录二维码",className:"p-2"}),Q==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Ke,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),Q==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:B||"请关闭窗口后重新发起扫码登录。"})]}),Q==="verification"&&e.jsx(an,{faceQrUrl:Z,verificationScreenshot:ue})]}),Q!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),J==="edit"&&E&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:E.nickname||E.remark||E.id})]}),e.jsx("button",{onClick:()=>void ot(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:E.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:c.remark,onChange:s=>d({...c,remark:s.target.value}),placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:c.cookie,onChange:s=>d({...c,cookie:s.target.value}),placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",c.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:()=>d({...c,auto_confirm:!c.auto_confirm}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${c.auto_confirm?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${c.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(Rs,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:c.pause_duration,onChange:s=>d({...c,pause_duration:parseInt(s.target.value)||0}),placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),c.pause_duration>0&&!E.paused&&c.pause_duration===(E.pause_duration||0)&&e.jsx("button",{type:"button",disabled:Y,onClick:()=>void pt(),className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(Xa,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),ae.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:ae.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:ae.loading||ae.saving||!ae.canOpen,onClick:()=>void nt(),className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${ae.enabled?"bg-brand":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${ae.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:c.username,onChange:s=>d({...c,username:s.target.value}),placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:c.showLoginPassword?"text":"password",value:c.login_password,onChange:s=>d({...c,login_password:s.target.value,clear_password:!1}),placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:()=>d({...c,showLoginPassword:!c.showLoginPassword}),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:c.showLoginPassword?e.jsx(dt,{className:"w-5 h-5"}):e.jsx(lt,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:c.clear_password,onChange:s=>d({...c,clear_password:s.target.checked,login_password:s.target.checked?"":c.login_password}),className:"w-4 h-4 accent-brand"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:()=>d({...c,show_browser:!c.show_browser}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${c.show_browser?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${c.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),de.status==="processing"||de.status==="verification_required"?e.jsx("button",{type:"button",onClick:Ge,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:ht,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),de.message&&e.jsx("div",{className:`text-sm font-medium ${de.status==="failed"?"text-red-700":de.status==="success"?"text-green-700":"text-blue-800"}`,children:de.message}),de.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),de.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(ea,{src:de.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(p.length>0||ye||V)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(jt,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),ye&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Pe,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),V&&!ye&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:V}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:()=>mt(E.id),children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:p.map(s=>{const o=U.includes(Number(s.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:()=>{ne&&(M(y=>o?y.filter(A=>A!==Number(s.id)):[...y,Number(s.id)]),x(!0))},disabled:!ne,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${o?"bg-brand border-brand":"bg-white border-gray-300"}`,children:o&&e.jsx(Ke,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:s.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[s.type,s.enabled?"":" · 已停用"]})]})]},s.id)})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>void ot(),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Y,children:"取消"}),e.jsxs("button",{onClick:Ot,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Y,children:[Y?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),Y?"保存中...":"保存"]})]})})]})}),document.body),J==="ai-settings"&&E&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(yt,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:E.nickname||E.remark||E.id})]}),e.jsx("button",{onClick:n,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(yt,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:()=>S({...D,ai_enabled:!D.ai_enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${D.ai_enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${D.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:D.max_discount_percent,onChange:s=>S({...D,max_discount_percent:parseInt(s.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:D.max_discount_amount,onChange:s=>S({...D,max_discount_amount:parseInt(s.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:D.max_bargain_rounds,onChange:s=>S({...D,max_bargain_rounds:parseInt(s.target.value)||1}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:D.custom_prompts,onChange:s=>S({...D,custom_prompts:s.target.value}),placeholder:`输入自定义的AI回复规则或风格指引... 例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Y,children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Y,children:[Y?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),Y?"保存中...":"保存"]})]})})]})}),document.body)]})},nn=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(a=>({order_id:String((a==null?void 0:a.order_id)||"unknown"),success:(a==null?void 0:a.success)===!0,message:String((a==null?void 0:a.message)||"")})):[]}),on=t=>(t==null?void 0:t.results.filter(a=>!a.success))||[],sa=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},cn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState([]),[m,_]=r.useState([]),[N,R]=r.useState({}),[g,C]=r.useState("all"),[j,F]=r.useState(""),[G,me]=r.useState(""),[oe,v]=r.useState(""),q=r.useRef(0),[ce,Q]=r.useState(1),[ee,B]=r.useState(1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState(!1),[ve,J]=r.useState(!1),[I,E]=r.useState(null),[$,be]=r.useState(null),[Re,ae]=r.useState({}),[T,p]=r.useState(!1),[b,U]=r.useState(""),[M,ne]=r.useState(!1),[he,ye]=r.useState(null),[Ee,ke]=r.useState(null),[x,V]=r.useState(null),[X,c]=r.useState(!1),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=async()=>{const u=++q.current;ue(!0);try{const L=await tr(j||void 0,g,ce,20,oe);if(u!==q.current)return;a(L.data),B(L.total_pages)}catch(L){console.error("加载订单失败:",L)}finally{u===q.current&&ue(!1)}},de=(u,L,le)=>{if(le&&le.trim())return le;if(N[`${u}:${L}`])return N[`${u}:${L}`];const Ne=l.find(Ue=>{if(le&&Ue.item_title){const Fe=le.toLowerCase(),tt=Ue.item_title.toLowerCase();return tt.includes(Fe)||Fe.includes(tt)}return!1});return Ne!=null&&Ne.item_title?Ne.item_title:"未知商品"},Se=u=>{const L={};u.forEach(le=>{le.item_id&&(L[`${le.cookie_id}:${le.item_id}`]=le.item_title||le.item_id)}),R(L)};r.useEffect(()=>{const u=window.setTimeout(()=>{Q(1),v(G.trim())},300);return()=>window.clearTimeout(u)},[G]),r.useEffect(()=>{O()},[j,g,ce,oe]),r.useEffect(()=>{Promise.all([Ft(),vt()]).then(([u,L])=>{_(u),i(L),Se(L)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const fe=r.useMemo(()=>new Map(m.map(u=>[u.id,u])),[m]),Oe=u=>{const L=fe.get(u),le=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return le?`${le} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},re=u=>{const L=fe.get(u);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"},h=async()=>{ue(!0);try{const u=await lr(j||void 0,g);await O(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{ue(!1)}},f=u=>{U(u),ye(null),p(!0)},P=async u=>{var L;ne(!0),ye(null);try{const le=await nr([b],u),Ne=(L=le==null?void 0:le.results)==null?void 0:L[0];Ne!=null&&Ne.success?(ye({success:!0,message:Ne.message}),O()):ye({success:!1,message:(Ne==null?void 0:Ne.message)||"发货失败"})}catch(le){ye({success:!1,message:(le==null?void 0:le.message)||"请求失败"})}finally{ne(!1)}},z=u=>{E(u),Z(!0)},Ie=u=>{be({...u}),K(!0)},Ae=async()=>{if(!(!$||!$.order_id))try{const u={};$.status!==void 0&&(u.order_status=$.status),$.buyer_id!==void 0&&(u.buyer_id=$.buyer_id),$.amount!==void 0&&(u.amount=$.amount),$.receiver_name!==void 0&&(u.receiver_name=$.receiver_name),$.receiver_phone!==void 0&&(u.receiver_phone=$.receiver_phone),$.receiver_address!==void 0&&(u.receiver_address=$.receiver_address),$.item_id!==void 0&&(u.item_id=$.item_id),$.quantity!==void 0&&(u.quantity=$.quantity),$.item_title!==void 0&&(u.item_title=$.item_title),await sr($.order_id,u),K(!1),be(null),O()}catch(u){console.error("更新订单失败:",u),alert("更新失败,请重试")}},we=async()=>{if(Ee){c(!0);try{const u=new FormData;u.append("file",Ee);const L=nn(await ir(u));V(L),ke(null),await O(),L.failed_count===0&&(J(!1),V(null),alert(`订单导入成功,共 ${L.success_count} 条`))}catch(u){alert((u==null?void 0:u.message)||"导入失败,请检查文件格式")}finally{c(!1)}}},De=()=>{X||(J(!1),ke(null),V(null))},te=async u=>{D(u);try{const L=await rr(u);L.success?await O():alert(L.message||"同步失败")}catch(L){console.error("同步订单失败:",L),alert((L==null?void 0:L.message)||"同步失败,请重试")}finally{D(null)}},je=async u=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){Y(u);try{await ar(u),t.length===1&&ce>1?Q(L=>L-1):await O()}catch(L){console.error("删除订单失败:",L),alert((L==null?void 0:L.message)||"删除失败,请重试"),await O()}finally{Y(null)}}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:O,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(ze,{className:`w-5 h-5 ${ge?"animate-spin":""}`})}),e.jsxs("button",{onClick:()=>{V(null),J(!0)},className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(et,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:h,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(Es,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:[{k:"all",v:"全部"},{k:"processing",v:"处理中"},{k:"shipped",v:"已发货"},{k:"pending_ship",v:"待发货"},{k:"completed",v:"已完成"},{k:"cancelled",v:"已取消"},{k:"refunding",v:"退款中"}].map(u=>e.jsx("button",{onClick:()=>{C(u.k),Q(1),me("")},className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${g===u.k?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:u.v},u.k))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:j,onChange:u=>{F(u.target.value),Q(1)},className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),m.map(u=>e.jsx("option",{value:u.id,children:Oe(u.id)},u.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(_t,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:G,onChange:u=>{me(u.target.value),Q(1)},className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:t.map(u=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:u.item_image?e.jsx("img",{src:u.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(qt,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:de(u.cookie_id,u.item_id,u.item_title)}),e.jsxs("div",{className:"mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:re(u.cookie_id),children:[e.jsx(xt,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:re(u.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",u.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",u.quantity," • ",bs(u.created_at)]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:u.buyer_id}),u.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:u.receiver_name})]}),u.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:u.receiver_phone})]}),u.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:u.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:u.amount?`¥${u.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(sa,{status:u.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[u.status==="pending_ship"&&e.jsx("button",{onClick:()=>f(u.order_id),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${u.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(ya,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>z(u),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(lt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Ie(u),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(Nt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>te(u.order_id),disabled:d===u.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(ze,{className:`w-4 h-4 ${d===u.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>je(u.order_id),disabled:S===u.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(Qe,{className:"w-4 h-4"})})]})]},u.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",ce," 页 / 共 ",ee," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:ce<=1,onClick:()=>Q(u=>u-1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(_s,{className:"w-5 h-5"})}),e.jsx("button",{disabled:ce>=ee,onClick:()=>Q(u=>u+1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(Ns,{className:"w-5 h-5"})})]})]})]}),k&&I&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:()=>Z(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:I.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"所属账号"}),e.jsx("div",{className:"truncate whitespace-nowrap text-sm font-bold text-blue-700",title:re(I.cookie_id),children:re(I.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(sa,{status:I.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:I.amount?`¥${I.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:I.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:bs(I.created_at)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[I.item_image&&e.jsx("img",{src:I.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:de(I.cookie_id,I.item_id,I.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",I.item_id]}),I.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",I.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:I.buyer_id})]}),I.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:I.receiver_name})]}),I.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:I.receiver_phone})]}),I.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:I.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>Z(!1),className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),I.status==="pending_ship"&&e.jsx("button",{onClick:()=>{Z(!1),f(I.order_id)},className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),ve&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:De,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:u=>{var L;return ke(((L=u.target.files)==null?void 0:L[0])||null)},className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),Ee&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:Ee.name})]})}),x&&x.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",x.success_count," 条,失败 ",x.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:on(x).map((u,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:u.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:u.message||"导入失败"})]},`${u.order_id}-${L}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:De,disabled:X,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:we,disabled:!Ee||X,className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:X?"正在导入…":"导入订单"})]})})]})}),document.body),T&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),e.jsx("button",{onClick:()=>{p(!1),ye(null)},className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:()=>P("status_only"),disabled:M,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(Es,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:()=>P("full_delivery"),disabled:M,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(qt,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),M&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(ze,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),he&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${he.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[he.success?"✓ ":"✗ ",he.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:()=>{p(!1),ye(null)},className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:he!=null&&he.success?"完成":"取消"})})]})}),document.body),se&&$&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:()=>K(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:$.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:$.status,onChange:u=>be({...$,status:u.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:$.buyer_id,onChange:u=>be({...$,buyer_id:u.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:$.amount,onChange:u=>be({...$,amount:u.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:$.receiver_name||"",onChange:u=>be({...$,receiver_name:u.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:$.receiver_phone||"",onChange:u=>be({...$,receiver_phone:u.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:$.receiver_address||"",onChange:u=>be({...$,receiver_address:u.target.value}),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:$.item_title||"",onChange:u=>be({...$,item_title:u.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>K(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Ae,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},dn=(t,a,l)=>{const i=l.trim().toLocaleLowerCase();return t.filter(m=>(!a||m.type===a)&&(!i||m.name.toLocaleLowerCase().includes(i)))},aa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),xn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState(!1),[m,_]=r.useState(!1),[N,R]=r.useState(null),[g,C]=r.useState({}),[j,F]=r.useState(aa),[G,me]=r.useState(!1),[oe,v]=r.useState("create"),[q,ce]=r.useState(null),[Q,ee]=r.useState(null),[B,ge]=r.useState(!1),[ue,k]=r.useState(""),[Z,se]=r.useState(""),[K,ve]=r.useState(null),[J,I]=r.useState(""),[E,$]=r.useState("");r.useEffect(()=>{Xe().then(a)},[]);const be=({type:x})=>{switch(x){case"text":return e.jsx(Ds,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Ts,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(al,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(os,{className:"w-5 h-5 text-gray-500"})}},Re=x=>{var V,X,c,d,D;R(x),C({id:x.id,name:x.name||"",type:x.type||"text",api_url:((V=x.api_config)==null?void 0:V.url)||"",api_method:((X=x.api_config)==null?void 0:X.method)||"GET",api_timeout:((c=x.api_config)==null?void 0:c.timeout)||10,api_headers:((d=x.api_config)==null?void 0:d.headers)||"",api_params:((D=x.api_config)==null?void 0:D.params)||"",text_content:x.text_content||"",data_content:x.data_content||"",image_url:x.image_url||"",delay_seconds:x.delay_seconds||0,description:x.description||"",enabled:x.enabled}),i(!0)},ae=async()=>{var x,V,X,c,d,D,S,Y;if(N){if(!((x=g.name)!=null&&x.trim())){alert("请输入卡密名称");return}if(!g.type){alert("请选择卡密类型");return}try{const O={name:g.name.trim(),type:g.type,description:(V=g.description)==null?void 0:V.trim(),delay_seconds:g.delay_seconds||0,enabled:g.enabled??!0};g.type==="api"?O.api_config={url:((X=g.api_url)==null?void 0:X.trim())||"",method:g.api_method,timeout:g.api_timeout||10,headers:((c=g.api_headers)==null?void 0:c.trim())||void 0,params:((d=g.api_params)==null?void 0:d.trim())||void 0}:g.type==="text"?O.text_content=((D=g.text_content)==null?void 0:D.trim())||"":g.type==="data"?O.data_content=((S=g.data_content)==null?void 0:S.trim())||"":g.type==="image"&&(O.image_url=((Y=g.image_url)==null?void 0:Y.trim())||""),await Ks(N.id,O),i(!1),Xe().then(a)}catch(O){console.error("更新卡密失败:",O),alert("更新失败,请重试")}}},T=async x=>{if(confirm("确认删除该卡密吗?"))try{await mr(x),Xe().then(a)}catch(V){console.error("删除卡密失败:",V),alert("删除失败,请重试")}},p=async()=>{if(!j.name.trim()){alert("请输入卡密名称");return}if(!j.content.trim()){alert(j.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const x={name:j.name.trim(),type:j.type,description:j.description.trim(),enabled:j.enabled,delay_seconds:j.delay_seconds};j.type==="text"&&(x.text_content=j.content.trim()),j.type==="data"&&(x.data_content=j.content.trim()),j.type==="image"&&(x.image_url=j.content.trim()),j.type==="api"&&(x.api_config={url:j.content.trim(),method:j.api_method,timeout:j.api_timeout,headers:j.api_headers.trim()||void 0,params:j.api_params.trim()||void 0}),await xr(x),_(!1),F(aa()),Xe().then(a)}catch(x){console.error("添加卡密失败:",x),alert("添加失败,请重试")}},b=async x=>{try{await Ks(x.id,{...x,enabled:!x.enabled}),Xe().then(a)}catch(V){console.error("切换状态失败:",V)}},U=async x=>{try{await navigator.clipboard.writeText(String(x)),alert(`已复制卡密组ID:${x}`)}catch{prompt("复制卡密组ID",String(x))}},M=t.filter(x=>x.type==="data"),ne=r.useMemo(()=>dn(t,J,E),[t,E,J]),he=()=>{const X=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 VIP-MONTH-002 diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html index 4706e66..33bdd56 100644 --- a/internal/webui/static/index.html +++ b/internal/webui/static/index.html @@ -6,7 +6,7 @@ Ydisks闲鱼助手 - 自动发货与管家系统 - +